David Tunnell
David Tunnell

Reputation: 7542

(Android) Error when using SharedPreferences write/read in non-activity class

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"

Upvotes: 0

Views: 2550

Answers (2)

Shashank Kadne
Shashank Kadne

Reputation: 8101

Use Context.MODE_PRIVATE. Its not an Activity, so you have to retrieve it from the Context.

Upvotes: 0

theelfismike
theelfismike

Reputation: 1621

Probably the easiest way to fix this is to pass a Context into your two methods, and have it look something like this:

public static void saveToSP(Context context, String key, String value) {
    SharedPreferences saveData = context.getSharedPreferences(File, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = saveData.edit();
    editor.putString(key, value);
    editor.commit();
}

Upvotes: 4

Related Questions