Storing integers in preference class

旧街凉风 提交于 2019-11-29 18:14:59

Hi here i added sample code for SharedPreferences for you concern .please try this code and let me know. Hope it should helpful for you. Thanks.

SharedPreferences Creation:

SharedPreferences sharedPref = getBaseContext().getSharedPreferences("USER_PREFS",Context.MODE_PRIVATE);

Store the values to SharedPreferences:

int userId = 2425;
String authtoken = "abcdef345345";
String authkey = "qrst";
sharedPref = getBaseContext().getSharedPreferences("USER_PREFS",prefMode);
SharedPreferences.Editor editor = vSmileSharedPreferences.edit();
editor.putString("AUTH_KEY", authkey);
editor.putString("AUTH_TOKEN", authtoken);
editor.putString("USER_ID", String.valueOf(userId));
editor.commit();

Retriving SharedPreferences values from another Activity:

String authtoken ="";
String authkey = "";
int UserId = 0;
SharedPreferences sharedPref =  getBaseContext().getSharedPreferences("USER_PREFS",Context.MODE_PRIVATE);
authtoken = sharedPref.getString("AUTH_TOKEN", null);
authkey = sharedPref.getString("AUTH_KEY", null);
UserId = sharedPref.getString("USER_ID", 0);

If the SharedPreference UserID is null or empty means it will take default as 0;

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