Issue
I have application and when I navigate back using Intent
and startActivity()
, views
are null, onCreate()
is called and activities are re-initialized. Why is that and how to bypass it?
I navigate back to activity like that:
@Override
public void onBackPressed() {
if (this.getClass() == XXX.class) {
Intent i = new Intent(this, YYY.class);
startActivity(i); //<-- activity restarts
return;
}
}
super.onBackPressed();
}
I use ActionbarSherlock, so I have activity with ActionBar initialization and every single activity just extends it. The way I navigate back to activity is described in this activity.
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
initUIComponents();
setListeners();
resetProgress();
}
and initUI() initializes UI.
EDIT
What I mean, how can I go back to previously created activity
(not the one that is called via onBackPressed
) and not recreate it? I use startActivity
(), but apparently it recreates the whole thing
Solution
If you want that when you press back, you want to show the previous screen, then you don't have to do it in your code. Android Runtime internally maintains the stack, and will take care of showing the last-shown-activity when you press back. No need to handle it via onBackPressed()
However, if you want something other than this default action, that is when you should use onBackPressed()
. Else, just let Android handle it.
So, in your application, if Activity 1
calls Activity 2
, and user presses back, then the default action would be to show Activity 1
again. Don't override the onBackPressed()
method
Edit:
For a custom flow of activities, you'll have to build the logic yourself. You need to override onRestart()
in Activity 1
, and onStop()
in Activity 3
. That way, onCreate
won't be called again. By your logic, I mean, flags to keep track of which activity you're in, checking those flags, and calling the desired activity from there.
Edit 2: This previous SO question, answers what you need:
Android Activity management , which suggests setting the flag FLAG_ACTIVITY_REORDER_TO_FRONT on the intent, and then calling startActivity()
Check out Android activity stack management using Intent flags for other stack reordering options: Stack management
Answered By - sanjeev mk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.