Let’s talk about the topic which is no more a buzzword for the market and that is Mobile apps Development. It isn’t as complicated as people and companies think it is. However, there are times when the developers have a hard time finding easy answers to technical questions. I have something to share about the SharedPreference Session management. Well, most Android apps need to save data about the application so that user’s progress will not be lost. SharedPreferences is a component which will help us to save data in key-value sets. When there is a need to store a small collection of key-values we should go for SharedPreferences in Android.

A SharedPreferences containing key-value pairs and provides simple methods to read and write objects. Every SharedPreferences file will be managed by the framework and can be private or shared.

android-1

Now let’s see how to implement SharedPreferences in android with a simple example and beautiful tutorial.

For developing an Android app, sometimes we have to store variable like String, Boolean Or Array List Component and we have to use that variable in other activity of screen or simply we have to maintain session that i.e. user login-logout functionality in Android application. So, here is the solution just add this below mention class file in our android project.

import android.content.Context;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.util.Log;

 public class SessionData

{

    private Editor editor;

    private SharedPreferences pref;

    public static String EMPTY_STRING = “Empty”;

    public static int EMPTY_INT = 0;

    /**

     * This is constructor

     *

     * @param context

     */

    public SessionData(Context context)

    {

        pref = context.getSharedPreferences(“MyPoshPets”, 0);

        editor = pref.edit();

    }

    /**

     * This is used to add Object as JSON String into shared preferences

     *

     * @param key

     * @param value

     */

    public void setObjectAsString(String key, String value)

    {

        Log.d(key, value);

        editor.putString(key, value);

        editor.commit();

    }

    /**

     * This is used to get Object as JSON String from preferences

     *

     * @param key

     * @return

     */

    public String getObjectAsString(String key)

    {

        return pref.getString(key, EMPTY_STRING);

    }

    /**

     * This is used to add Object as JSON String into shared preferences

     *

     * @param key

     * @param position

     */

    public void setObjectAsInt(String key, int position)

    {

        Log.d(key, position + “”);

        editor.putInt(key, position);

        editor.commit();

    }

    public int getObjectAsInt(String key)

    {

        return pref.getInt(key, EMPTY_INT);

    }

}

After Adding this class creates an object of this class.

  • Create Object

SessionData sessionData = new SessionData(context);

  • Stored Value

Add Key & Value to store String value in an app. Using setObjectAsString() method you can Store String in Key & Value format so you must have to pass Key & Value to this method so it will store Value against that particular Key.

sessionData.setObjectAsString(“USER_ID”, “11”);

  • Get Value

Use Key to get Value of String. Using getObjectAsString() method you will get Value Stored against particular Key so you have to pass Key to this method to get a value of that Key.

String userId = sessionData.getObjectAsString(“USER_ID”);

Output: – String userId will return 11

  • Store Custom Java Objects

SessionData Class allows you to store custom Java objects (object, arrays or lists) in String & Retrieve it very easily. For this you need GSON Library to convert Java object from /to JSON (JavaScript Object Notation) converting to JSON object, you can store it as a string using SessionData class. Gson has methods

  • toJson() – Convert Java object to JSON format
  • fromJson() – Convert JSON into Java object

Download Gson library file from https://www.java2s.com/Code/Jar/g/Downloadgson22jar.htm

  • Create ArrayList

public class AppMenus

{

                  public String menu_name, order;

}

ArrayList<AppMenus> appMenus = new ArrayList<>();

2)  Add Data in ArrayList

3) Stored ArrayList in Session Data Object Using Key

sessionData.setObjectAsString(“appMenus”, new Gson().toJson(appMenus));

4) Retrive Stored Data in Arraylists

String dataString = sessionData.getObjectAsString(“appMenus”);

TypeToken<ArrayList<AppMenus>> TokenAppMenu = new

TypeToken<ArrayList<AppMenus>>() {};

appMenus = new Gson().fromJson(dataString, TokenAppMenu.getType());

Using this Session Data, class store data will be persistent even though user has closed the application. Isn’t this information worth your 5 mins? If you like this tutorial or if you want to add anything to this, you may feel free to drop me a line in the comments section.

Happy Coding. 🙂

POSTED IN: October 14, 2016 Yogesh Jadhav