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
  • You can not convert null to integer. What are you storeing in your sharedpreferences? Commented Nov 8, 2015 at 21:19
  • @zkminusck What can I do to fix it? Commented Nov 8, 2015 at 21:28
  • Possible duplicate of What is a Null Pointer Exception, and how do I fix it? Commented Feb 7, 2016 at 11:22

3 Answers 3

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")); 
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

Hi, thank you for the answer. I understood what you wrote and it helped me, but the same erros occured
Are you in an activity or non-activity class??
It seems your abc is null. Log it and tell me result. Also you can remove "getApplicationContext()"
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 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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.