繁体   English   中英

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

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

您好,感谢您的阅读。

我正在尝试采用OOP方法来使用SharedPreferences保存和检索我正在使用的android应用程序中的数据。 我相信以下代码是正确的,因为当直接在非OOP庄园中使用时,它可以在java类中工作。 但是,在我制作的SharedPref类中,在MODE_PRIVATE的Eclipse中出现了一个错误,我不知道为什么。 谢谢。

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

此外,如果我扩展Activity类,则getSharedPreferences会变成带有错误和以下消息的行:

“无法从ContextWrapper类型静态引用非静态方法getSharedPreferences(String,int)”

解决此问题的最简单方法是将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();
}

使用Context.MODE_PRIVATE。 它不是活动,因此您必须从上下文中检索它。

暂无
暂无

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

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