2015-02-10 86 views
0

在我的活動類中,我將一些數據存儲在Sharedpreference中。我的非Activity類擁有getter和setter來讀取Sharedpreference數據。我想在另一個Activity類中使用這個數據。但是我總是得到一個Nullpointer異常。如何從非活動類中獲取SharedPreference以用於非活動

這是我的Activity類的代碼片段。

SharedPreferences prefs; 

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

這是我的第一個非Activity類

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

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

當我嘗試contact.getName();我總是得到一個空指針異常,但我知道SharedPreference被正確地保存。

+0

默認值爲空......您如何知道首選項已保存? – Navdroid 2015-02-10 09:16:58

+0

嘗試mContext.getSharedPreferences(「app_prefs」,0); – 2015-02-10 09:18:12

+0

可以請你說你在哪裏調用initContact()?在活動或非活動課上? – sUndeep 2015-02-10 09:19:22

回答

0
  1. 請確保您的活動中的「代碼段」真正執行,您可以通過打印一些日誌來驗證它。

  2. 確保KEY_NAME_FOR_PREF等於「app_prefs」。

2

使用兩個靜態方法創建一個類,並在整個應用程序中使用它來存儲和檢索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; 
      } 
    } 
+0

這是好方法。我也像上面那樣使用。 – sUndeep 2015-02-10 09:36:41

+0

當我像這樣使用它時,我得到了同樣的錯誤:testKlasse.getStringFromPreferences(mContext,null,「name」,「app_prefs」); – Byakko 2015-02-10 13:37:01