How to use Shared Preferences in Android


 

Download APK Download Source Code Contact Us

Create a new project in Android Studio

File – New Android Project

How to use Shared Preferences in Android
How to use Shared Preferences in Android

Shared Preferences

Shared Preferences is allow you to save and retrive data in the form of key, value pair.You can use sharedpreferences to save any primitive data,booleans,floats,ints,longs and string.

Use Shared Preferences

getSharedPreferences()- Return sharedPreferences instance poiting to the file that contains the values of preferences. 
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);  

You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object.

public static final String USER_DETAILS_PREFS = "user_details_prefs";
    private static final String NAME = "name";
public static String getName(Context context) {
        SharedPreferences sp = context.getSharedPreferences(
                USER_DETAILS_PREFS, Activity.MODE_PRIVATE);
        return sp.getString(NAME, "");
    }
public static void setUserDetail(Context context, String name) {
SharedPreferences sf = context.getSharedPreferences(
                    USER_DETAILS_PREFS, Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sf.edit();
            editor.putString(NAME, name);
        editor.commit();
}
getPreferences()- Use this from an Activity if you need to use only one shared preference file for the activity.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Deleting key value from sharedpreferences

SharedPreferences sf = context.getSharedPreferences(
                My_PREFS, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sf.edit();
editor.remove(“key_name1”);
editor.remove(“key_name2”);
editor.commit(); 

Clear all data from sharedPreferences

editor.clear();
editor.commit();
How to use Shared Preferences in Android
How to use Shared Preferences in Android
How to use Shared Preferences in Android

Download APK Download Source Code Contact Us

Posted in All Tutorials, Android Tutorials | Tagged | Leave a comment

Leave a Reply

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

Powered By: wpnova.com