Android SharedPreferences

Introduction

Preferences are generly a little storage and typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application. Or it can be something that needs to be stored specific to an activity.Here you will see the useage of SharedPreferences.

Let we use SharedPreferences as storage of login info i.e username and password.

We store date like below.

public void savePreferences(Context aContext,Bundle bndlData){
        SharedPreferences prefrences=aContext.getSharedPreferences("preferenceName", Context.MODE_PRIVATE);
        Editor editor=prefrences.edit();
        editor.putString("userName",bndlData.getString("user_name"));
        editor.putString("password",bndlData.getString("password"));
        editor.commit();
    }

We will get data from shared preferences using following method.

[sociallocker]

public static Bundle getFromPreferences(Context aContext){
        SharedPreferences prefrences=aContext.getSharedPreferences("preferenceName", Context.MODE_PRIVATE);
        Bundle data=new Bundle();
        data.putString("user_name", prefrences.getString("userName", "Any default value"));
        data.putString("password", prefrences.getString("password", "Any default value"));        
        return data;
    }

[/sociallocker]

Try it very easy and simple technique.

Leave a comment

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