简体   繁体   English

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

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

In my Activity class I store some data in a Sharedpreference . 在我的Activity类中,我将一些数据存储在Sharedpreference My non Activity class has getter and setter to read the Sharedpreference data. 我的非Activity类具有getter和setter来读取Sharedpreference数据。 I want use this Data in an another Activity class. 我想在另一个Activity类中使用此数据。 But I get always a Nullpointer exception. 但是我总是得到一个Nullpointer异常。

This is a Code snippet from my Activity class. 这是我的Activity类的代码段。

SharedPreferences prefs;

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

This is my first non Activity class 这是我的第一个非活动课

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

And this is my second non Activity class. 这是我的第二个非活动课。 Context mContext; 上下文mContext; PdfConsultantContacts contact = new PdfConsultantContacts(mContext); PdfConsultantContacts contact =新的PdfConsultantContacts(mContext);

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

When I try to contact.getName(); 当我尝试contact.getName(); I get always a Nullpointer exception, but I know that the SharedPreference are saved correctly. 我总是收到Nullpointer异常,但我知道SharedPreference正确保存。

Create a class with two static methods and use this throughout your application to store and retrieve data from SharedPreferences. 用两个静态方法创建一个类,并在整个应用程序中使用它来存储和检索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. Make sure "Code snippet" from your Activity is really executed, you can verify it by print some log. 确保“活动”中的“代码段”已真正执行,您可以通过打印一些日志来对其进行验证。

  2. Make sure the KEY_NAME_FOR_PREF equals "app_prefs". 确保KEY_NAME_FOR_PREF等于“ app_prefs”。

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

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