Android Java - 共享首选项编辑器问题

时间:2014-03-17 17:37:54

标签: java android sharedpreferences

我试图将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。 当我在主要活动上执行此操作时。它向我展示了3次EAStrin。

textView2.setText((sharedpreferences.getString(MobileVerified, "")) + " , "+ (sharedpreferences.getString(NameVerified, "")) +  " , "+ (sharedpreferences.getString(EmailAddressVerified, "")));

3 个答案:

答案 0 :(得分:1)

你永远不会发起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";

否则你用下一个条目覆盖每个条目......

答案 1 :(得分:0)

您已声明但未启动SharedPreferences。这样做:

SharedReferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // common instance that will be shared for this context

答案 2 :(得分:0)

我认为您不包含@Override方法的onCreate(Bundle savedInstanceState)注释。在覆盖View onClick(View v)方法时,您也不会包含相同的注释。