Skip to content Skip to sidebar Skip to footer

How Do I Store The User Details As Session

Hello i am using dynamodb and i want to know how do i maintain a session when the user logs in. Following is my login code Runnable runnable = new Runnable() { public voi

Solution 1:

V1

you can use SharedPreferences like below

publicclassPrefs {

publicstaticvoidputPref(String key, String value, Context context){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

publicstaticStringgetPref(String key, Context context) {
    SharedPreferences preferences =   PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
 }
}

after you have to store

 Prefs.putPref("the key","the value",your context);

after to get your stored data

StringuserId= Prefs.getPref("the key",your context);

you can use that where you want in your App .

V2

use Gson add this to your build.gradle

compile'com.google.code.gson:gson:1.7.2'

and convert your user object to json like this

Gsongson=newGson();

 Useruser= ...; 
 Stringjson= gson.toJson(user);

after store your user

 Prefs.putPref("user",json,your context);

to get your user

 String json == Prefs.getPref("user",your context);

 Useruser=null;
 if(json !=null)
 user= gson.fromJson(json,User.class);

thats all

Post a Comment for "How Do I Store The User Details As Session"