Reputation: 3685
I am using Volley to make an HTTP Post request.
This is working fine, however within the onResponse method I am trying to set a SharedPreference value, this value does not seem to be being set however.
The Volley code:
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);
}
The Intent gets fired so I know we are hitting the success if statement.
The below code is run in the launcher activity to by pass login if the user has already logged in
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);
}
}
However loggedIn is always false.
Upvotes: 0
Views: 1150
Reputation: 132992
As see here:
Retrieve a SharedPreferences object for accessing preferences that are private to this activity
Both LoginActivity
and MainActivity
Activity is different, so getting always false
.
Use getSharedPreferences
instead of getPreferences
in both Activities to get it work.
Upvotes: 3