May mainting the session using Shared preference in android

白昼怎懂夜的黑 提交于 2019-12-13 20:18:24

问题


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.


回答1:


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.




回答2:


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.




回答3:


You're probably looking onSaveInstanceState. It can be used to save the state of a page and restore it later



来源:https://stackoverflow.com/questions/7173287/may-mainting-the-session-using-shared-preference-in-android

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