Android Studio - 无法在新活动上保存共享偏好 [英] Android Studio - The shared perference can't be saved on the new activity

查看:54
本文介绍了Android Studio - 无法在新活动上保存共享偏好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所建议的,共享首选项无法保存在新活动中

As the question suggested, the shared preference can't be saved on the new activity

Set<String> temp = getSharedPreferences("pref", MODE_PRIVATE).getStringSet("attempt", null);
temp.add("one item");
SharedPreferences editor = getSharedPreferences("pref", MODE_PRIVATE);
editor.edit().putStringSet("attempt", temp).commit();

此代码在主要活动上完美运行.但是,当我尝试将此代码放在另一个活动上时它不起作用.

this code work perfectly on the main activity. However, it don't work when I tried to put this code on the another activity.

编辑的首选项可以在此代码之后查看,即使在新活动的 destroy(); 方法之后也是如此.但是,它正在刷新到保存的参考仅使用之前在主活动中添加的项目.

the edited preference can be view after this code, even after the destroy(); method of the new activity. However, it is being refreshed to the saved Reference only with the added item in the main activity before.

我已经搜索了半个小时,但我只找到了有关无法保存首选项"的问题;而不是无法保存偏好仅在新活动中"

I have been searching for a half hours but I only find question about "Can't save preference" instead of "Can't save preference only in new activity"

我想知道我的代码是否有任何错误,任何帮助将不胜感激.

I am wondering is there any mistake in my code, any help would be appreciated.

推荐答案

为了让你的 preferences 全局可用,我建议做一个 SharedPrefs.java 类来保存你的 SharedPreferences像这样:

To make your peferences global available I suggest to do a SharedPrefs.java class to save your SharedPreferences like this:

public class SharedPrefs {

public static SharedPreferences prefs(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context);
}

//Set your preference
public static void setMyPreference(Context context, String text) {
    prefs(context).edit().putString("MyPreference", text).apply();
}

//Get your preference
public static String getMyPreference(Context context) {
    return prefs(context).getString("MyPreference", "DefaultText");
}

使用以下代码,您可以将 Activity 中的数据保存为 SharedPreference 到您的 SharedPrefs.java 类:

And with the following code you can save data from your Activity as a SharedPreference to your SharedPrefs.java class:

//To save preferences in SharedPrefs
                String myString = "Hello world";
                SharedPrefs.setMyPreference(getContext(),myString);

或者从 SharedPrefs.java 获取它到你的 Activity:

Or getting it from SharedPrefs.java to your Activity:

//To get preferences from SharedPrefs
                String getMyPreference = SharedPrefs.getCustomString(getContext());
                System.out.println(getCustomString);
                //Result = Hello world

这篇关于Android Studio - 无法在新活动上保存共享偏好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆