-1

I try to add and get data using sharedPreferences, but I only receive this error in logcat:

Attempt to invoke virtual method 'android.content.SharedPreferences
android.content.Context.getSharedPreferences(java.lang.String, int)'
on a null object reference

The line of code:

public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0); // <-error here

I need create first the xml file?

Ozgur
  • 3,738
  • 17
  • 34
Cofeina
  • 41
  • 1
  • 9

1 Answers1

1

You need to initialize it after activity created:

public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences prefs;

onCreate(){
    prefs = getSharedPreferences(PREFS_NAME, 0);
}
Ozgur
  • 3,738
  • 17
  • 34