Search code examples
nullpointerexceptiontextviewsharedpreferencesoncreatedata-retrieval

Null pointer exception when retrieving textView in onCreate using shared preference


Here is my code in onCreate method

    SharedPreferences sp = getSharedPreferences("key", Context.MODE_PRIVATE);
     String tValue = sp.getString("textvalue","");
     coins.setText(tValue);

This is where iam saving text value

    count++;
    coins.setText(String.valueOf(count));
    SharedPreferences sp = getSharedPreferences("key", 0);
     SharedPreferences.Editor sedt = sp.edit();
     sedt.putString("textvalue", coins.getText().toString());
     sedt.commit();

Solution

  • The problem will be resolved by this line..Try it

    TextView coins = (TextView) findViewById(R.id.yourcoinsid);
    
      coins.setText(""+tValue);
    

    Reason

    The instance variable coins was null , so we find it using findViewById and then it will work.