Search code examples
androidsharedpreferences

How to check whether shared preferences is null or not in android?


In my apps for login and logout functionality, I am checking whether the shared preferences is null or not when activity starts, but I am still getting a NullPointerException.

Here is my code for HomeActivity.java:

// Username And Password Editbox
String eusername;
String epassword;

// Shared Preferences String declaration
String spusername;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     

    SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    spusername=spreferences.getString("spusername","");

    if(!spusername.equals(""))
    {   
        Log.e("Spusername not null","-->"+spusername);
    }
    if(spusername==null)
    {
        Log.e("Spusername null","-->"+spusername);
    }
}

Solution

  • you are giving eusername without initializing this variable so getting null pointer exception So try like this

    spusername = preferences.getString("spusername", "n/a");
    
    if(spusername!= null && !spusername.equals(""))
        {   
            Log.e("Spusername != null","-->"+spusername);
    
        }
       else{
                   // your code is here
        }