Hello and thanks for reading.
I am trying to take an OOP approach to using SharedPreferences to save and retrieve data in the android app I am working on. I believe the following code is correct as it works in the java classes when used directly in a non-OOP manor. However, in this SharedPref class I made, I am getting an error in Eclipse at the MODE_PRIVATE and I can’t figure out why. Thanks.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class SharedPref {
public static String File = "DPFile";
public static void saveToSP(String key, String value) {
SharedPreferences saveData = getSharedPreferences(File, MODE_PRIVATE);
SharedPreferences.Editor editor = saveData.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSavedData(String key) {
SharedPreferences preferences = getSharedPreferences(File, MODE_PRIVATE);
return preferences.getString(key, null);
}
}
Additionally, if I extend the Activity class getSharedPreferences becomes the line with the error and the following message:
“Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper”
Probably the easiest way to fix this is to pass a Context into your two methods, and have it look something like this: