Android: Simple Class For Easy Writing And Reading SharedPreferences String Value

SharedPreferences is used to store small configurations or settings data in your Android application. For example, as username or user preferences data storage. Just like variables, shared preferences can be identified by “key” string as “variable” name. Shared preferences are relatives to application. So it can not be accessed by other application directly.

In the following example, I would like to store the username of logged in user so in future activities I am able to present contents related to the users’ username. I used username as shared preferences key name. Hence, the Java code to store the value is as follow:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
Editor editor = sp.edit();
editor.putString("username", "aryo");
editor.commit();

Then the shared preferences can be read from other activities by the following code:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
value = sp.getString("username", "guest");

The second argument of getString() method is used as default value that will be returned if the shared preferences key specified in first argument can not be found. Don’t forget that activity is current application Activity. If you read the shared preferences inside an Activity, the activity object can be retrieved by:

Activity activity = this;

As generic implementation from above codes, here is an example of shared preferences utility class which of it’s method can be accessed in static ways.

public class Utils {

    public static void savePreferences(Activity activity, String key, String value){
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
		Editor editor = sp.edit();
		editor.putString(key, value);
		editor.commit();
    }

    public static String readPreferences(Activity activity, String key, String defaultValue){
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
    	return sp.getString(key, defaultValue);
    }

}

How to use it?

Simple, to save a shared preferences value:

Utils.savePreferences("username","aryo");

And to read the value:

username = Utils.readPreferences("username","no one");

That’s it. Hope it will be useful.

15 Replies to “Android: Simple Class For Easy Writing And Reading SharedPreferences String Value”

  1. Most people don’t think of this, but what would happen if your
    car was stolen or the building burned down with your vehicle in it.
    This means that your vehicle is out of service until
    it can be repaired and restored to its original condition. Therefore it’s essential that you simply check it
    and confirm it before applying the paint on your own auto.

  2. The game hit a record number of downloads when it
    hit 2 million downloads the very weekend it released.
    We display innumerable contract Motorola Defy mobile
    phones, compare Motorola Defy mobile phones and a lot more from various leading online merchants.
    Give yourself a good start today by getting more details on how you
    can successfully implement such ideas.

  3. There are actually number of games which have been purely adventurous.
    Players can choose to play single-player, but
    the game is best played with at least two players.
    For some reason, old school pitching coaches believed this was the most effective
    method of cardio for players.

  4. If you are not sure of the item, you could just end up sobbing eventually because your trouble was not settled and that it had end up undesirable.
    Of course, the one step that’s not here and really should be added is patience.
    Moreover, it cannot be stressed enough that these vices
    only harm a person’s body.

  5. There’s not much to do it, just make your short bio statement and connect to your website.
    Instagram followers, being the backbone of this photo sharing site, you
    need to understand that your photos, no doubt how good it is, but are worthless if there is no one to appreciate it.
    Purchasing Instagram Followers is easy and you should get real
    followers makes possible to market your products.

  6. Though the app is mainly used by individuals, more and more business are taking
    lead of it as way of reaching out to customers visually and intimately.
    For this reason, avail Instagram expert services and get additional likes and develop into recognizable in a very small
    amount of time. It really is actually a solid choice to provide a enhance into the webpage and acquire paid Instagram followers for rapidly results.

  7. com website (click on Special Education and look under the Accommodations link).
    The properties over here are seen to give the investors with a lot of profit yielding
    that was never seen before. Renting an apartment is a popular choice for many
    students but there are many hidden costs of monthly rentals including gas, water, and other expenses.

  8. Several groups can be found on these games and programs to ensure that you are able to pick
    one based on your needs. Android tablets are generally soon after all, a good buy IN ADDITION
    TO you have to carry shopping them no matter whether
    you need a tablet the idea lasts long. 0 has an spread potentiality of interpersonal and sharing features which allows
    the application to incorporate contacts, line items, strictness information, and other calendar events from any of the users interpersonal networking profiles.

  9. It is watching Free Movies Online without Downloading which has changed the outlook of web surfers,
    today. To watch Free Movies Online without Downloading all you have to do
    is get on to the website of Free Movies Online and pick out your choicest
    movies. Watching movies online is a relatively new but very popular way to
    watch your favorite movies.

Leave a Reply

Your email address will not be published. Required fields are marked *

*