【问题标题】:JSONObject string is not stored in sharedpreferencesJSONObject 字符串未存储在 sharedpreferences 中
【发布时间】:2016-08-11 12:22:01
【问题描述】:

我将一个 jsonobject 字符串值传递给我的共享首选项并提交它。但是在获取这个时,它会返回默认值。

用于放置:

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

}

【问题讨论】:

  • 你是如何初始化 app_prefs 的?
  • @Pr38y private SharedPreferences app_prefs;
  • @Pr38y public PreferenceHelperClass(Context context) { app_prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); this.context = 上下文; }
  • 请添加您的PreferenceHelperClass 代码。
  • 您是否存储和访问来自不同上下文/活动的数据

标签: android json parsing sharedpreferences


【解决方案1】:

如果您想在整个应用程序中使用相同的首选项管理器,请使用 defaultSharedPreferencegetSharedPreferences 仅返回该上下文的首选项文件,不同的上下文不同。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

您可以使用ApplicationContext 代替context

【讨论】:

  • 但是使用 getDefaultSharedPreferences 将不同的数据放在 prefs 中可以正常工作。两者有什么区别?
  • getSharedPreferences 仅返回该上下文的首选项文件,不同的上下文不同。 getDefaultSharedPreferences 为整个 app 返回一个文件,与上下文无关。您当前的代码正在创建两个PREF_NAME xml 文件,一个用于活动A,另一个用于活动B。您将数据保存在活动A 的文件中。并从活动 B 的文件中访问
猜你喜欢
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 2014-12-25
  • 2018-08-08
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
相关资源
最近更新 更多