Asesha George Asesha George - 1 month ago 7
JSON Question

Store json response array in to session

My LoginActivity is sending username and password to URL and getting success status. I want to store json response like userid, name, email information in a session and retrieve it in MainActivity. I am using below code for json response.

JSONObject jObj = new JSONObject(response);
String userId = jObj.getString("user_id");


and my response is

{"tag":"login",
"error":false,
"user_id":"5",
"user":{"name":"Chandra shankar",
"email":"chandra@gmail.com"
}
}


below is my SharedPreferences in Session.java

public class Session {
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;


public Session(Context context) {
sp = PreferenceManager.getDefaultSharedPreferences(context);

}


public boolean setLogin(boolean status) {
spEditor = sp.edit();
spEditor.putBoolean("is_logged_in", status);
spEditor.commit();
return true;
}

public boolean getLoggedIn() {
return sp.getBoolean("is_logged_in", false);
}

}

Answer

use SharedPreferences.

SharedPreferences preferences = this.getSharedPreferences("APP_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();

editor.putString("ID", userId).apply();

if you want to get the value back.

String id = preferences.getString("ID");
Comments