【问题标题】:Android: Retrieve int saved in PreferenceManager getDefaultSharedPreferences in another activityAndroid:在另一个活动中检索保存在 PreferenceManager getDefaultSharedPreferences 中的 int
【发布时间】:2013-12-03 14:56:49
【问题描述】:

我正在尝试使用默认的 Shared Preferences 保存数据,但无法使此代码正常工作。

我无法在另一个活动中检索 int 值。

在我的第一个活动中,在onCreate 中,我想创建一个scorecounter,每次您获得积分时都会计数。它将在第一次运行时启动。

SharedPreferences preferences =  PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

if (preferences.getBoolean("first_run", true)) 
{   
editor.putInt("totalpoang", 0);
editor.commit();
    preferences.edit().putBoolean("first_time", false);
}

在我的Activity B 中,我想检索该值,对其进行修改,然后再次将其保存在首选项中。

SharedPreferences preferences =  PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int poang = preferences.getInt(totalpoang, 0);
editor.putInt("antalpoang", totalpoang);
editor.commit();

但是我只得到错误 totalpoang 不能被解析为变量

我在第一个 Activity 中将其初始化为 int,并尝试将其检索为 int

我做错了什么?

【问题讨论】:

    标签: android save sharedpreferences


    【解决方案1】:

    改变这个

    int poang = preferences.getInt(totalpoang, 0);
    //editor.putInt("totalpoang", 0); // key is "totalpoang" 
    

    int poang = preferences.getInt("totalpoang", 0);
    

    然后

    editor.putInt("antalpoang", poang);
    

    【讨论】:

    • 在新activity中未创建时是否必须添加“”标记?
    • @user3061876 它是一个字符串,它需要“”。它就像一把钥匙。您使用键检索值。需要使用相同的键来检索值。这里使用的密钥是什么editor.putInt("totalpoang", 0) 检索时同样使用它
    • @user3061876 是totalpoang 一个整数值吗?如果是这样,请更改 editor.putInt("totalpoang", totalpoang); // 如果您有 int toatlpoang =2 或 soemthing,则键是“totalpoang”,值是 totalpoang。
    • 对不起,我在您的第二条评论后误解了。我的应用程序现在正在运行!谢谢你的帮助!问题是正如您所写的,我不知道如何定义字符串和值的区别。谢谢! :)
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 2017-10-07
    • 2011-12-18
    • 2013-12-05
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多