Save Variable In Sharedpreferences Based On Which Button Is Clicked
Solution 1:
I think you're better off with using IntentExtras
, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= newIntent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
StringcountryCode= getIntent().getExtras().getString("country");
Solution 2:
In order to maintain Shared preference across the application i use it this way , take a look
I saved a AppPrefes class as a seprate class in the package
publicclassAppPrefes {
privateSharedPreferences appSharedPrefs;
privateEditor prefsEditor;
publicAppPrefes(Context context, StringPreferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */publicStringgetData(String key) {
return appSharedPrefs.getString(key, "");
}
publicIntegergetIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */publicvoidSaveData(StringTag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
publicvoidSaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/publicvoiddeleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Solution 3:
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferencesprefs= getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
StringstoredCountry= sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.
Post a Comment for "Save Variable In Sharedpreferences Based On Which Button Is Clicked"