All keys in SharedPreferences return same value

怎甘沉沦 提交于 2019-12-20 07:08:46

问题


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

Expected Output:

 Your Numbers:  1   2

Console Output:

 Your Numbers:  2   2

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


回答1:


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

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




回答2:


Because of this:

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

change it to:

static final String ONE = "One"; 
static final String TWO = "Two";

U need unique values for every preference. In your case the ONE gets overridden by the TWO.

Extra info

If u look in the android docs here you will see that putString requires two parameters:

  • key : String: The name of the preference to modify.
  • value : String: The new value for the preference.

and if u than look at getString here you will notice that it also has two parameters, both the same as putString:

  • key : String: The name of the preference to retrieve. -- important
  • defValue : String: Value to return if this preference does not exist.

The name/key is the part that let the get part know from which preference it needs to get the value.

Hope this will make things a bit clearer for u!




回答3:


Both the strings are empty

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

It should be like :

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


来源:https://stackoverflow.com/questions/37725158/all-keys-in-sharedpreferences-return-same-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!