0

我一直在获取默认值,或者我的 UI 将显示 null,或者如果我使用整数,它也会显示该默认值,这里它是字符串形式的 plz help

//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);


SharedPreferences peepsScores2= PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
  editor2.putString("userScore11",userScore11);
  editor2.commit();

  //getting it and editing it

  SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
    int u;
    int one =1;
    int newUsrScore1=1;
    String userScore11 = peepsScores2.getString("userScore11",null);
    u=Integer.parseInt(userScore11);
        newUsrScore1 = u+one;
        String newUserScore1  = Integer.toString(newUsrScore1);

    SharedPreferences.Editor editor = peepsScores2.edit();
    editor.putString(newUserScore1, NewUserScore1);
      editor.commit();

    //getting it and displaying it on the UI

    SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
    String userScore11 = peepsScores2.getString("NewuserScore1",null);


  pScore1.setText(" "+userScore11);
4

3 回答 3

1

这条线

editor.putString(newUserScore1, null);

应该

editor.putString("NewuserScore1",newUserScore1);

并且不要忘记使用提交您的更改editor.commit();

于 2012-10-31T12:31:50.233 回答
1

我为您的代码添加了一些注释,请检查:

//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);


SharedPreferences peepsScores2= 

PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
  editor2.putString("userScore11",userScore11);
  editor2.commit();

  //getting it and editing it

  SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
    int u;
    int one =1;
    int newUsrScore1=1;
    String userScore11 = peepsScores2.getString("userScore11",null);
    u=Integer.parseInt(userScore11);
        newUsrScore1 = u+one;
        String newUserScore1  = Integer.toString(newUsrScore1);

    SharedPreferences.Editor editor = peepsScores2.edit();

     //@Praful: here newUserScore1 seems to be integer value and you are storing 
    //null here. I think it it should be 
    //`editor.putString("NewuserScore1", newUsrScore1);`
    editor.putString(newUserScore1, null);

     //@Praful: call commit here
    editor.commit;

    //getting it and displaying it on the UI

    SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
    String userScore11 = peepsScores2.getString("NewuserScore1",null);


  pScore1.setText(" "+userScore11);
于 2012-10-31T12:32:32.400 回答
0

每当您使用 SharedPreference 时,永远不要忘记调用commit()以保存您的更改。

    SharedPreferences.Editor editor = peepsScores2.edit();
    editor.putString("NewuserScore1", newUserScore1);
    editor.commit();
于 2012-10-31T12:31:27.533 回答