Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use SharedPreferences in Android to store, fetch and edit values

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 614
    Comment on it

    SharedPreferences are used to store primitive data types in Android such as int, long, float, string. SharedPreferences have an added advantage over storing data in singleton class as Singleton class can store data and available throughout the app but if you exit the application all the data will lost. But in SharedPreferences if you exit out of your application or even if you switch off your Android device even then the data persists.

    How to store data in SharedPreferences

    Suppose to store the user id in SharedPreferences create a class SharedPrefernceManager and define the below methods in it. "setUserId" method will be used to store data and "getUserId" will be used to get data.

    private static final String LOGIN_INFO = "login_info";
    
    public void setUserId(Context context, String userId){
    SharedPreferences preferences = (SharedPreferences)context.getSharedPreferences(LOGIN_INFO,0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("userId",userId);
        editor.commit();
    }
    
    public String getUserId(Context context){
    
        SharedPreferences preferences = (SharedPreferences)context.getSharedPreferences(LOGIN_INFO,0);
        return preferences.getString("userId","");
    }
    

    After defining the above two methods, call "setUserId" from your Activity to store the data.

    Store Data:

    SharedPreferenceManager preferenceManager = SharedPreferenceManager.getInstance();
    preferenceManager.setUserId(mContext,"5"); // hard coded user id (5) is used here

    Fetch Data:

    To get the store user id in any Activity, you can use the below code:

    SharedPreferenceManager preferenceManager = SharedPreferenceManager.getInstance();
    preferenceManager.getUserId(mContext);

    How to clear data stored in SharedPreferences

    Define the below method in SharedPrefernceManager class and call it from any class to clear the stored data.

    public static void clearCredentials(Context context){
            SharedPreferences preferences = (SharedPreferences)context.getSharedPreferences(LOGIN_INFO,0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.commit();
        }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: