[英]Android Java - Shared Preferences Editor Issue
我试图将3个不同字符串的值存储到共享首选项中。 字符串绝对包含值,因为我已经通过在textView中设置字符串来测试它们。
public class verified extends Activity{
SharedPreferences sharedpreferences;
TextView textView100;
String MyPREFERENCES = "MyPreferences" ;
String NString;
String MString;
String EAString;
public static final String MVerified = "";
public static final String NVerified = "";
public static final String EAVerified = "";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Bundle bundle = getIntent().getExtras();
NString = bundle.getString("NString");
MString = bundle.getString("MString");
EAString = bundle.getString("EAString");
textView100 = (TextView) findViewById(R.id.textView100);
textView100.setText(MString + " , " + NString + " , " + EAString);
Button VCompleteButton = (Button) findViewById(R.id.VCompleteButton);
VCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Editor editor = sharedpreferences.edit();
editor.putString(MVerified, MString);
editor.putString(NVerified, NString);
editor.putString(EAVerified, EAString);
editor.commit();
}
});
}
}
但是,现在的问题是EAString将其值存储在所有三个中。 sharedPreferences。 当我在主要活动上执行此操作时。 它向我显示了EAStrin 3次。
textView2.setText((sharedpreferences.getString(MobileVerified, "")) + " , "+ (sharedpreferences.getString(NameVerified, "")) + " , "+ (sharedpreferences.getString(EmailAddressVerified, "")));
您永远不会启动sharedpreferences
:
SharedPreferences sharedpreferences;
多数民众赞成在这里得到NullPointerException的原因:
Editor editor = sharedpreferences.edit();
在使用SharedPreferences之前,在您的onCreate方法中放入以下内容:
sharedpreferences = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
这是您的关键:
public static final String MVerified = "";
public static final String NVerified = "";
public static final String EAVerified = "";
每个键都是一个空字符串。 您必须为SharedPreferences中的每个条目定义一个键:
public static final String MVerified = "key1";
public static final String NVerified = "key2";
public static final String EAVerified = "key3";
否则,您将用下一个覆盖每个条目...
您已经声明但尚未启动SharedPreferences。 做这个:
SharedReferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // common instance that will be shared for this context
在我看来,好像您的onCreate(Bundle savedInstanceState)
方法不包含@Override
注释。 重写View
的onClick(View v)
方法时,也不会包含相同的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.