Skip to content
Advertisement

Shared Preferences on a Null Object Reference Android

I am new to android developing maybe its a silly question but please help me. I am getting this error while trying to save an int value.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)’ on a null object reference

And here is my code

JavaScript

And for write

JavaScript

I just want to set a SharedPreferences and want to read it at the first and write it inside the Activity. How can I solve it?

EDIT

JavaScript

I managed to save preferences with a different way but I couldn’t manage to read it in MainActivity extends Activity class.

log :

Caused by: java.lang.NullPointerException: Attempt to invoke interface method ‘int android.content.SharedPreferences.getInt(java.lang.String, int)’ on a null object reference

Advertisement

Answer

This is an example of SharedPreferences

To save name in SharedPreferences:

JavaScript

To get name from SharedPreferences:

JavaScript

For more details visit: http://developer.android.com/training/basics/data-storage/shared-preferences.html

Updated Code:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement