Back to previous activity in android

Back to previous activity in android

This is the sample coding for back to the previous activity. Sometimes we have to go to one activity from many activity’s . that time we don’t know which activity we have to go when press back button. This example will help you to do that.
 
Steps
1. Add the current activity to the shared preference when starting the activity.
SharedPreferences prefs = getSharedPreferences("X",
MODE_PRIVATE);

Editor editor = prefs.edit();

editor.putString("lastActivity",
context.getClass().getName());

editor.commit();

Intent
i=new
Intent(getApplicationContext(),Activity3.class);
startActivity(i);
finish();

2. get the previous running activity from shared preference and start the previous activity.

Class<?> activityClass;
 
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(
prefs.getString("lastActivity", Activity3.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = Activity3.class;
}
 
startActivity(new Intent(this, activityClass));
finish();
 Download

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top