SharedPreferences keep getting default value

前端 未结 3 434
[愿得一人]
[愿得一人] 2020-12-22 11:58

I keep Getting the Default value either my UI will display null or if I use integers it displays that default value as well here it is in the string form plz help

         


        
相关标签:
3条回答
  • 2020-12-22 12:13

    This line

    editor.putString(newUserScore1, null);

    should be

    editor.putString("NewuserScore1",newUserScore1);
    

    and also don't forget to commit your changes using editor.commit();

    0 讨论(0)
  • 2020-12-22 12:19

    I have added some comment to you code please check:

    //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);
    
    0 讨论(0)
  • 2020-12-22 12:29

    Whenever you working with SharedPreference never forget to call commit() to save your changes.

        SharedPreferences.Editor editor = peepsScores2.edit();
        editor.putString("NewuserScore1", newUserScore1);
        editor.commit();
    
    0 讨论(0)
提交回复
热议问题