[英]Store json response array in to session
我的LoginActivity正在将用户名和密码发送到URL并获得成功状态。 我想在会话中存储json响应,如用户ID,名称,电子邮件信息,并在MainActivity中检索它。 我正在使用以下代码进行json响应。
JSONObject jObj = new JSONObject(response);
String userId = jObj.getString("user_id");
我的回应是
{"tag":"login",
"error":false,
"user_id":"5",
"user":{"name":"Chandra shankar",
"email":"chandra@gmail.com"
}
}
下面是我在Session.java中的SharedPreferences
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);
}
}
SharedPreferences preferences = this.getSharedPreferences("APP_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ID", userId).apply();
如果您想找回价值。
String id = preferences.getString("ID");
编辑
public class Session {
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;
private String ISLOGIN = "is_logged_in";
private String USER_ID = "user_id";
public Session(Context context) {
sp = PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean setLogin(boolean status) {
spEditor = sp.edit();
spEditor.putBoolean(ISLOGIN, status);
//use apply for async process
spEditor.apply();
return status;
}
public boolean getLoggedIn() {
return sp.getBoolean(ISLOGIN, false);
}
public void setUserId(String userid){
sp.edit().putString(USER_ID,userid).apply();
}
//get user id
public String getUserId(){
return sp.getString(USER_ID);
}
}
//活动中
Session session = new Session(this);
String id = session.getUserId();
p / s:我建议您使用此TinyDB SharedPreferences
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.