Reputation: 597
I want to save a string value in android activity using SharedPreferences
.
This is my SearchUserAdapter
class : here only passing the search people user id :
final String searchuserid = Order.get(SearchProfile.TAG_USER_ID);
username_search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(activity,
SearchProfile.class);
in.putExtra("UserId", searchuserid);
activity.startActivity(in);
}
});
return vi;
}
In this SearchProfile.class:
Intent i = getIntent();
userid = i.getStringExtra("UserId");
SharedPreferences loginPreferences = getSharedPreferences(M_SPF_NAME,
Context.MODE_PRIVATE);
loginPreferences.edit().putString(M_USERNAME, userid).commit();
Here if I have reloaded the SearchPorile
activity many times means that time also need to get the same user id when selecting the another user id from that SearchUserAdapter
class. How can I save this value ? Any suggestion or idea will be appreciated.
Upvotes: 1
Views: 2533
Reputation: 1726
Save Shared Preference:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
Get Shred Preference:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("storedName", "YourName");
Upvotes: 3
Reputation: 574
SharedPreferences myPrefs = getSharedPreferences("Userinfo", MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("Key", "Yourvalue");
editor.putString("Key", "Yourvalue");
editor.commit();
Upvotes: 0
Reputation: 685
I can propose you a different way. First, you prepare a class for shared preference which contain :
public static void put(Context context, String key, String value) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
Second, use this where you need and store data. For your purpose, you can call and use this on your adapter(Intent will not be required in this case).
Upvotes: 1