简体   繁体   English

(Android)在非活动类中使用SharedPreferences写入/读取时出错

[英](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. 我正在尝试采用OOP方法来使用SharedPreferences保存和检索我正在使用的android应用程序中的数据。 I believe the following code is correct as it works in the java classes when used directly in a non-OOP manor. 我相信以下代码是正确的,因为当直接在非OOP庄园中使用时,它可以在java类中工作。 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. 但是,在我制作的SharedPref类中,在MODE_PRIVATE的Eclipse中出现了一个错误,我不知道为什么。 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: 此外,如果我扩展Activity类,则getSharedPreferences会变成带有错误和以下消息的行:

"Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper" “无法从ContextWrapper类型静态引用非静态方法getSharedPreferences(String,int)”

Probably the easiest way to fix this is to pass a Context into your two methods, and have it look something like this: 解决此问题的最简单方法是将Context传递到您的两个方法中,并使它看起来像这样:

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();
}

Use Context.MODE_PRIVATE. 使用Context.MODE_PRIVATE。 Its not an Activity, so you have to retrieve it from the Context. 它不是活动,因此您必须从上下文中检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM