Atula Atula - 6 months ago 22
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;

@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.

Answer

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