我遇到了一些麻烦恢复SharedPreferences到活动从原来的分开。SharedPreferences分布在不同的活动在同一应用程序
我有被利用这一点,“NewCustomerActivity”和“OldCustomerActivity”两班。两者都应该具有对文件的读/写访问权限 - 目前我只是通过从NewCustomerActivity中写入来进行测试,NewCustomerActivity会在杀死活动时适当地恢复表单数据;不过,我在打开OldCustomerActivity时收到一个FC,该OldCustomerActivity尝试用与NullPointerException相同的NewCustomerActivity来恢复数据。
NewCustomerActivity:
public class NewCustomerActivity extends Activity {
public static final String USER_INFO = "UserInfoFile"; // This file will the store the user's information for later use.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcustomer);
SharedPreferences userInfo = getSharedPreferences(USER_INFO, 0); // Restore our earlier saved info.
EditText et;
...... (Other code is irrelevant)
}
OldActivityNew是一样的:
public class OldCustomerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.oldcustomer);
SharedPreferences userInfo = getSharedPreferences(NewCustomerActivity.USER_INFO, 0); // Restore our earlier saved info.
EditText et;
et = (EditText) findViewById(R.id.EditTextName);
et.setText(userInfo.getString("name",""));
..... (Continue to fill forms in this context)
}
这两个活动的填补与以前信息的形式,如果有什么改变了更新在提交的文件;然而只有NewCustomerActivity似乎是填充文件(或不强制关闭是具体的)
我试着在MODE_WORLD_READABLE(第二个参数= 1)设置SharedPreference以及无济于事;即使我相信我应该可以在PRIVATE中运行它。我也尝试引用USER_INFO作为NewCustomerActivity.USER_INFO
我必须失去了一些东西明显 - 但任何帮助,将感谢赞赏,因为这是我第一次尝试,!
编辑:
对于那些问我是怎么写入文件:
SharedPreferences userInfo = getSharedPreferences(USER_INFO, 0); // Save info for later
SharedPreferences.Editor userInfoEditor = userInfo.edit();
EditText et;
et = (EditText) findViewById(R.id.EditTextName);
String nameValue = et.getText().toString();
userInfoEditor.putString("name", nameValue);
如何在每个活动中写入SharedPreference? – 2012-01-18 01:18:48
这里的一个片段: SharedPreferences USERINFO = getSharedPreferences(USER_INFO,0); //保存以后的信息 \t \t SharedPreferences。编辑器userInfoEditor = userInfo.edit(); \t \t EditText et; \t \t et =(EditText)findViewById(R.id.EditTextName); \t \t String nameValue = et.getText()。toString(); \t \t userInfoEditor.putString(“name”,nameValue); – 2012-01-18 02:44:04
看起来你没有提交写操作。为了让'SharedPreferences'生效,在完成所有编辑之后,您需要执行'userInfoEditor.commit();' – curioustechizen 2012-01-18 03:02:10