Mark Mark - 2 months ago 16
Android Question

Starting a new activity and closing the current one with clear top flag in not working

Am inside an activity which uses a StringRequest for Volley

when I receive a response from the server inside the onResponse method

I want to close the current activity and start a new one

the problem is after I receive the response , the new activity starts

but if I hit the back button I go back to the previous activity that should be closed

here is what I'm doing

StringRequest stringRequest=new StringRequest(Request.Method.POST,url,new Response.Listener<String>(){
@Override
public void onResponse(String response) {
loading.dismiss();

Log.e("spool",response);

try {
JSONObject json=new JSONObject(response);

if(json.getInt(LoginActivity.TAG_SUCCESS)==1)
{
Toast.makeText(RegisterActivity.this,json.getString("message"),Toast.LENGTH_SHORT).show();
Intent intent=new Intent(RegisterActivity.this,LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
else
Toast.makeText(RegisterActivity.this,json.getString("message"),Toast.LENGTH_SHORT).show();
}
catch (JSONException e)
{
e.printStackTrace();
}

}
},....


thanks for your time

Answer

You are missing the finish() call after startActivity(intent);

Also, not a good idea to display a Toast message if you are starting a new activity right after. The Toast message would be visible only for a few milliseconds.