繁体   English   中英

如何从非活动类获取非活动类的SharedPreference

[英]How to get SharedPreference from non activity class for non activity

在我的Activity类中,我将一些数据存储在Sharedpreference 我的非Activity类具有getter和setter来读取Sharedpreference数据。 我想在另一个Activity类中使用此数据。 但是我总是得到一个Nullpointer异常。

这是我的Activity类的代码段。

SharedPreferences prefs;

prefs = getActivity().getSharedPreferences(KEY_NAME_FOR_PREF, 0);
        SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name.getText().toString());
editor.commit();

这是我的第一个非活动课

private String name;
private Context mContext;

public PdfConsultantContacts(Context context){
    mContext = context;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

这是我的第二个非活动课。 上下文mContext; PdfConsultantContacts contact =新的PdfConsultantContacts(mContext);

void initContact() {
SharedPreferences prefs =        mContext.getApplicationContext().
getSharedPreferences("app_prefs", 0);
contact.setName(prefs.getString("name", null));
}

当我尝试contact.getName(); 我总是收到Nullpointer异常,但我知道SharedPreference正确保存。

用两个静态方法创建一个类,并在整个应用程序中使用它来存储和检索SharedPreferences中的数据。

public class Utils {    
            public static void putStringInPreferences(Context context, String value, String key, String pKey) {
                SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(key, value);
                editor.commit();
            }

            public static String getStringFromPreferences(Context context,String defaultValue, String key, String pKey) {
                SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
                String temp = sharedPreferences.getString(key, defaultValue);
                return temp;
            }
    }
  1. 确保“活动”中的“代码段”已真正执行,您可以通过打印一些日志来对其进行验证。

  2. 确保KEY_NAME_FOR_PREF等于“ app_prefs”。

暂无
暂无

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

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