Hi i want to maintain some sessions in my application. May i use shared preference to maintain it? I not then plz suggest me the proper way with the simple example.
Asked
Active
Viewed 1,312 times
0
-
http://stackoverflow.com/questions/4572338/extending-application-to-share-variables-globally – Samuel Aug 24 '11 at 09:40
-
Yes, this is a good place to store data. – David Snabel-Caunt Aug 24 '11 at 09:45
3 Answers
0
Maybe you should make use of server to maintain sessions. Because as you have suggested here, using shared preference, you are leaving the option of clearing the preferences from memory to the user. So in this case if the user clears your app data, then your concept of sessions fails.

Andro Selva
- 53,910
- 52
- 193
- 240
-
If a user clears the app data they can expect to be logged out. – David Snabel-Caunt Aug 24 '11 at 09:43
-
0
Yes, you can use the shared preferences.
For example, to save username, password and session ID, you can:
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putString("User Name", username);
edit.putString("Password", password);
edit.putInt("Session ID", session_id);
edit.commit();
And to get them:
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
username = pref.getString("User Name", "");
password = pref.getString("Password", "");
session_id = pref.getInt("Session ID", 0);
This is just an example, it is better to use string constants instead of just "User Name" etc.

MByD
- 135,866
- 28
- 264
- 277
-
It depends on you, I just gave an example of how to use shared preferences, maybe you don't need session_id at all... – MByD Aug 24 '11 at 09:54
-
Actually as of my knowledge session id's value is generating by itself. Is it true??? – kushal45 Aug 24 '11 at 10:00
-
0
You're probably looking onSaveInstanceState. It can be used to save the state of a page and restore it later

Kurru
- 14,180
- 18
- 64
- 84