SharedPreferences中的所有键都返回相同的值 [英] All keys in SharedPreferences return same value

查看:95
本文介绍了SharedPreferences中的所有键都返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次使用共享的首选项,并且遇到了错误.
我的代码是这样的:

I am using Shared preferences for the first time and getting errors.
my code is like this :

public class MainActivity extends Activity {
 static final String ONE = ""; 
 static final String TWO = "";
 private static SharedPreferences mSharedPreferences;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

SharedPreferences.Editor edi = mSharedPreferences.edit();
  edi.putString(ONE, "1");
  edi.putString(TWO, "2");
  edi.commit();

 String one = mSharedPreferences.getString(ONE,"1");
 String two = mSharedPreferences.getString(TWO,"2");
 System.out.println("Your Numbers: "one+ "   " + two);
 }
 }

预期输出:

 Your Numbers:  1   2

控制台输出:

 Your Numbers:  2   2

我无法弄清楚我在做什么错.分享您的看法.

I can't figure out what i am doing wrong in it. Share your views.

推荐答案

您需要在名称/键中添加一些字符串.当前两个键名均为空白,因此您的代码将覆盖相同的首选项值.如下更改静态字符串,它应该可以正常工作.

You need to add some string to the names/keys. Currently both key names are blank and hence your code is overwriting the same preference value . Change the static strings as follows and it should work fine.

static final String ONE = "one"; 
static final String TWO = "two";

也可以尝试使用帮助程序类,以使用共享的首选项使事情变得更简单.这是我写的: Android-SharedPreferences-Helper

Also try using a helper class to make things simpler with shared preferences. Here is one that i wrote: Android-SharedPreferences-Helper

这篇关于SharedPreferences中的所有键都返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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