0

I have weird problem with null checking. I'm using shared preferences where i have stored phonenumber.

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); String number = settings.getString("number1", null);

Before i use that String value i check if it's null

if(number != null){//trying to format number but it gives error: Attempt to invoke virtual method on a null object reference}

In my other app this works fine but in this project it gives me trouble. I dont understand if it has something to do with Services because working app is using background service and this uses JobIntentService.

Can someone tell why this gives error?

4
  • 4
    Please post more of your code - i.e., the stacktrace showing your have a NullPointerException, the line it points to, and any lines necessary for context. Commented Mar 18, 2019 at 16:56
  • 1
    Either settings object itself is null or the key is wrong, thus you are getting null. Check if "settings" is null and the shared prefs key you are using to store the phone number. is it "number1"? Commented Mar 18, 2019 at 16:57
  • If Your String is not null but contains only "" then You can get NPE when trying to parse number. Add !number.trim().equals("") to the null check Commented Mar 18, 2019 at 17:09
  • 1
    See the bellow links: - SharedPreferences return null - [SharedPreferences getString returns null ](stackoverflow.com/a/25968768/9944300) - sharedpreferences return null value Commented Mar 18, 2019 at 17:14

0

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.