我正在使用Volley发出HTTP Post请求。
这工作正常,但是在onResponse方法中,我尝试设置SharedPreference值,但是似乎未设置该值。
凌空代码:
public void sendPostRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progress.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (obj.has("success")){
SharedPreferences sharedPref = LoginActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("loggedIn", true);
editor.commit();
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
startActivity(intent);
}else{
error.setText(obj.getString("error"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("volley Error .................");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", emailTxt.getText().toString());
params.put("password", passwordTxt.getText().toString());
return params;
}
};
queue.add(stringRequest);
}
该Intent被解雇了,所以我知道我们在成功if语句中取得了成功。
如果用户已经登录,则以下代码在启动器活动中运行以通过登录
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
boolean loggedIn = sharedPref.getBoolean("loggedIn", false);
if (loggedIn){
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivity(intent);
}else{
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
}
但是,loginIn始终为false。
如此处所示:
检索SharedPreferences对象以访问此活动专用的首选项
两者LoginActivity
和MainActivity
Activity都不相同,因此总是获得false
。
在两个活动中同时使用getSharedPreferences
而不是getPreferences
使它正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句