2016-08-11 73 views
0

我傳遞一個jsonobject字符串值到我的共享首選項並提交它。但是在獲取這個時,它返回默認值。JSONObject字符串不存儲在sharedpreferences

對於推杆:

public void new_putMultipleProfileData(String got_multiple_json_data){ 

    Editor editor=app_prefs.edit(); 
    editor.putString(NEW_TESTING_PIC_ID, got_multiple_json_data); 
    editor.commit(); 
} 

爲了得到:

public String new_getMultipleProfileData(){ 
    return app_prefs.getString(NEW_TESTING_PIC_ID,"0"); 
} 

完全偏好助手類:

public class PreferenceHelper { 


private final String PREF_NAME = "Testing_xyz"; 
private SharedPreferences app_prefs; 

//For Testing 
public static final String NEW_TESTING_PIC_ID = "testing"; 

private Context context; 

public PreferenceHelper(Context context) { 
    app_prefs = context.getSharedPreferences(PREF_NAME, 
      Context.MODE_PRIVATE); 
    this.context = context; 
} 


public void new_putMultipleProfileData(String got_multiple_json_data){ 
    AppLog.Log("new_data_80503","got_multiple_json_data "+got_multiple_json_data); 
    Editor editor=app_prefs.edit(); 
    editor.putString(NEW_TESTING_PIC_ID, "hello"); 
    editor.commit(); 
} 

public String new_getMultipleProfileData(){ 
    AppLog.Log("new_data_80503","new_getMultipleProfileData "+app_prefs.getString(NEW_TESTING_PIC_ID,"0")); 
    return app_prefs.getString(NEW_TESTING_PIC_ID,"0"); 
} 

}

+0

你是如何初始化app_prefs? – Pr38y

+0

@ Pr38y private SharedPreferences app_prefs; –

+0

@ Pr38y public PreferenceHelperClass(Context context){ app_prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); this.context = context; } –

回答

0

如果要在使用相同的優先級經理a pp然後使用defaultSharedPreferencegetSharedPreferences僅返回該上下文的首選文件,但對於不同的上下文不同。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

可以使用ApplicationContext代替context

+0

但是,在prefs中,使用getDefaultSharedPreferences可以正常工作。兩者有什麼區別 ? –

+0

getSharedPreferences僅返回該上下文的首選項文件,它對於不同的上下文是不同的。無論上下文如何,getDefaultSharedPreferences都會爲整個應用程序返回一個文件。您當前的代碼正在創建兩個「PREF_NAME」xml文件,一個用於活動A,另一個用於活動B.您正在將數據保存在活動A的文件中。並從活動B的文件進行訪問 – Pr38y