同一应用程序中不同活动之间的java SharedReference
我在将SharedReference恢复到与原始活动不同的活动中时遇到了一些问题
我有两个类正在利用这个功能,“NewCustomerActivity”和“OldCustomerActivity”。两者都应该具有对文件的读/写访问权限——目前我只是通过从NewCustomerActivity写入来进行测试,它将在终止活动后适当地恢复表单数据;然而,我在打开OldCustomerActivity时收到了一个FC,它试图以与带有NullPointerException的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在填充文件(或者不强制关闭)
我尝试过在模式_WORLD_READABLE(第二个参数=1)下设置SharedReference,但没有成功;尽管我相信我应该可以私下进行。我还尝试将用户信息引用为NewCustomerActivity。用户信息
我肯定错过了一些明显的东西,但任何帮助都将不胜感激,因为这是我的第一次尝试,谢谢
编辑:
对于那些询问我如何写入文件的人:
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);
# 1 楼答案
看起来您试图在
oldCustomerActivity
中使用与您编写它们时不同的模式获取首选项。 在该类中更改此行:getSharedPreferences(NewCustomerActivity.USER_INFO, 1)
要对模式参数使用0,请执行以下操作:
getSharedPreferences(NewCustomerActivity.USER_INFO, 0)
传递给函数的int并不定义您是在读还是在写,而是定义您希望首选项在首次写入后的行为
要在加载首选项后编辑它们,需要调用:
SharedPreferences.Editor editor = userInfo .edit();
然后,您可以如下设置变量:
editor.putString("username", "Ash");
更多信息请参见here