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?

A. Kultala
  • 41
  • 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. – PPartisan Mar 18 '19 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"? – Ashray P. Shetty Mar 18 '19 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 – Pavel B. Mar 18 '19 at 17:09
  • 1
    See the bellow links: - [SharedPreferences return null](https://stackoverflow.com/a/31056106/9944300) - [SharedPreferences getString returns null ](https://stackoverflow.com/a/25968768/9944300) - [sharedpreferences return null value](https://stackoverflow.com/a/12489725/9944300) – Amin Soheyli Mar 18 '19 at 17:14

0 Answers0