-3

I am storing userId at the time of registration in SharedPreferencesand. Now I want to access the SharedPreferences stored UserId value. Till now I tried this code:

prefrence = PreferenceManager.getDefaultSharedPreferences(this);
edit3 = prefrence.edit();
edit3.putInt("user_id", userid);
Log.e("Commit", "SharedPreferences");
edit3.commit();

And on the next activity I am using this for access:

prefr = PreferenceManager.getDefaultSharedPreferences(this);

value = prefr.getInt("user_id", "");

How do I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rango
  • 28
  • 7

2 Answers2

4

You PUT in an INT and GET a STRING... Maybe that's causing a type cast error.

I see you changed your code, to get an int... the WRONG WAY!

You are doing so:

value = prefr.getInt("user_id", "");

Instead you should do so:

value = prefr.getInt("user_id", 0);

(You can't assign "" to an int.)

The above is valid if user_id is an int. If user_id is a string, then you should do a putString and a getString. Like:

edit3.putString("user_id", userid);

And then

value = prefr.getString("user_id", "");

So you grant the necessary type consistency.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
2

Try changing

prefr.getString("user_id", "");

to

prefr.getInt("user_id", 0);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29