Storing integers in preference class

烂漫一生 提交于 2019-12-18 09:51:16

问题


In my android app I have created a preference class(which extends PreferenceActivity) for storing about 10 integer values. I am not creating any xml file for that activity in R.xml as I don't want it. I just need to store 10 integer variables in this file(which can save it even after exit) and I want to get these values from another activity, perform some changes to the preferences, then save the preference class.

My queries are:

  1. How can I store an integer variable in preference class?
  2. How to call that variable from another activity?
  3. How to return that variable again to preference class?

回答1:


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;



来源:https://stackoverflow.com/questions/21245083/storing-integers-in-preference-class

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