0

I`ve problem with converting String to Integer.

   public SharedPreferences abc;
   abc = getApplicationContext().getSharedPreferences("Trening",0);



   Integer i = Integer.parseInt(abc.getString("T1",null).toString()); 

The Error is:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference

I learn to program for 3 days and hope you can help me and explain how to fix it, so I can learn.

Sorry for my english. :)

3 Answers3

1

When you are using null as second argument in abc.getString("T1", null), actualy you are saying: if "T1" value is not set, return null as default.
So you have parsInt(null) and it causes NullPointerExceprion.
You can replace
abc.getString("T1", null) with
abc.getString("T1", "0")
It will returns string "0" as default value of "T1" (if "T1" is null). So you have parsInt("0") that it works proprely.

Seyyed
  • 1,526
  • 3
  • 20
  • 30
  • Hi, thank you for the answer. I understood what you wrote and it helped me, but the same erros occured – GreenFace Nov 08 '15 at 21:51
  • Are you in an activity or non-activity class?? – Seyyed Nov 08 '15 at 21:59
  • It seems your abc is null. Log it and tell me result. Also you can remove "getApplicationContext()" – Seyyed Nov 08 '15 at 22:19
  • The mistace can be: I`ve public SharedPreferences abc; and abc = getApplicationContext().getSharedPreferences("Trening",0); in one class and Integer i = Integer.parseInt(abc.getString("T1",null).toString()); in other class. The second class extends the first class but not AppCompatActivity. Am I right ? – GreenFace Nov 08 '15 at 22:24
  • @GreenFace post more code so i can find that what is your activities structure. However `abc` is null and its because you are instantiating it in a class and using it in another. – Seyyed Nov 09 '15 at 20:07
1

If abc.getString("T1", null) returns null (this will happen if there is no Key-Value-Pair with the key "T1" in your SharedPreferences) then you try to get the String of null. This causes the NullPointerException. You should define another defaultValue which can be converted into a String.

Apart from that, you can leave toString() out because getString() returns a String:

Integer i = Integer.parseInt(abc.getString("T1", "-1")); 
Antict
  • 597
  • 5
  • 22
1

So the problem basically is that the variable abc is null, therefore the getSharedPreferences call fails to retrieve a valid reference.