Atula Atula - 8 months ago 45
Android Question

Shared Preference Issue

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;

public void onCreate(Bundle savedInstanceState) {

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

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.


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