2016-08-11 70 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