简体   繁体   中英

How to get SharedPreference from non activity class for non activity

In my Activity class I store some data in a Sharedpreference . My non Activity class has getter and setter to read the Sharedpreference data. I want use this Data in an another Activity class. But I get always a Nullpointer exception.

This is a Code snippet from my Activity class.

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; PdfConsultantContacts contact = new PdfConsultantContacts(mContext);

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

When I try to contact.getName(); I get always a Nullpointer exception, but I know that the SharedPreference are saved correctly.

Create a class with two static methods and use this throughout your application to store and retrieve data from 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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