1

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.

1
  • You just need to saved value on Preferences in Activity onPause() and load it on Activity onResume() Commented Feb 5, 2014 at 5:37

3 Answers 3

3

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

0
SharedPreferences myPrefs = getSharedPreferences("Userinfo", MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("Key", "Yourvalue");
editor.putString("Key", "Yourvalue");
editor.commit();

1 Comment

Give some explanation with code so new future user can understand easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.