• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Kepala Suku

Web & Mobile Developer
Staff member
#1
I configured out how to create session (save user data generated from server temporally) using Sharedpreferences. I saved all data as string using a class called Sessions. Here is the class i created for saving and calling the data in android application:
Java:
public class Sessions {
    SharedPreferences settings;
    Context context;

    public Sessions(Context context) {
        this.context=context;
        settings = context.getSharedPreferences(Variables.SESSION_NAME, 0); //we have to define session name here
    }

    public void createSession(String key, String value) {
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public String getSession(String key) {
        SharedPreferences settings = context.getSharedPreferences(Variables.SESSION_NAME, 0);
        return settings.getString(key,"");
    }
}
Change Variables.SESSION_NAME above with session name we want.

Here is the way could we use that class for saving and calling the data:
Java:
Sessions session = new Sessions(this);
sessions.createSession("session-key", "session-value"); //create session
sessions.getSession("session-key"); //call session data we stored before