Skip to content Skip to sidebar Skip to footer

Android: Nullpointerexception Working With Sharedpreferences

Working with SharedPreferences, this activity crashes upon launching. First I'll post the activity code, and then I'll post my LogCat. Thank you so much guys, you guys are always s

Solution 1:

You have to access the shared preferences AFTER onCreate is called. Or else the context would be null :) that's why you're getting a null pointer exception

move this line :

SharedPreferencessettings= getSharedPreferences("gBValues", 
     Context.MODE_PRIVATE);

in the onCreate()

Solution 2:

Move the instantiation of the settings instance variable into your onCreate method. After the super.onCreate call.

The way you are doing it now, it is getting set to null;

Solution 3:

publicclassMainActivityextendsActivity{

SharedPreferences sharedpreferences;    

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

sharedpreferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);  

            editor.putBoolean("sharedpreferences", true);
            editor.commit();

// your code ...

}

// your code ...
}

Post a Comment for "Android: Nullpointerexception Working With Sharedpreferences"