質問

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?
役に立ちましたか?

解決

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;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top