user1025050
user1025050

Reputation:

Android:implementing shared preference

I am making an app in which i have to save some string in shared preference and show it on another page means that i want to save name of user in shared preference in one activity and want to show the name of user on other activity.Any help regarding this will be appreciated. Thanks

Upvotes: 0

Views: 1964

Answers (3)

Prashant Solanki
Prashant Solanki

Reputation: 660

You might wanna see this library. It's Secure and Easy to use.

https://prashantsolanki3.github.io/Secure-Pref-Manager/

Sample Code:

SecurePrefManager.with(this)
            .set("user_name")
            .value("LoremIpsum")
            .go();

Upvotes: 0

Stefan
Stefan

Reputation: 4705

All you need to do is this (all the code is part of an acticity or Service (i.e. Context): Get a SharedPreferences object:

static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

To store a string:

String username = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString(USER_KEY, username);
editor.commit();

To read:

String username = settings.getString(USER_KEY,null); // 2nd param is default value, used if prefs value is undefined

Here are more details: http://developer.android.com/guide/topics/data/data-storage.html

Upvotes: 2

Chirag
Chirag

Reputation: 56935

To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.

public class SaveSharedPreference 
{
    static final String PREF_USER_NAME= "username";

    static SharedPreferences getSharedPreferences(Context ctx) {
        return PreferenceManager.getDefaultSharedPreferences(ctx);
    }

    public static void setUserName(Context ctx, String userName) 
    {
        Editor editor = getSharedPreferences(ctx).edit();
        editor.putBoolean(PREF_USER_NAME, userName);
        editor.commit();
    }

    public static boolean getUserName(Context ctx)
    {
        return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
    }
}

Now you can first set the value of username from a prticular activity and get the value of user name from any activity.

Upvotes: 0

Related Questions