Issue
I'm sure im missing something about the back stack and how it works here or maybe I just need to add a few lines here but I'm just trying to get my back button functionality working.
Activity A makes an API request using an ID passed via an intent extra to populate it's fields (this is done in onCreate). Activity B is opened from Activity A, but upon going back to Activity A, there is no id in the intent so no request can be made.
How can I setup my navigation so that the intent to create Activity A is preserved when starting Activity B, and resent when pressing the back button? Any functionality close to this, if easier, would probably be fine as well.
As of right now, I'm not doing anything special when i start Activity A. Here is how I setup my back button in Activity B (along with specifying the parent activity as Activity A inside my manifest):
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar5);
setSupportActionBar(toolbar);
// Make sure there is a back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Thanks for any help ahead of time.
Where I attach my ID to the intent and start Activity A:
Intent detailsIntent = new Intent(context, ViewObjActivity.class);
detailsIntent.putExtra("objId", objId);
context.startActivity(detailsIntent);
Where I retrieve my ID from the intent in Activity A's onCreate:
// Get data from extras
Intent detailsIntent = getIntent();
mObjID = detailsIntent.getIntExtra("objId", -1);
THE FIX
After a little digging, I found that the default back button functionality isn't that great. By overriding the handler with the following, I was able to avoid having to store the ID as no call to onCreate is made - The activity's previous state is already stored.
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Solution
You can consider this option instead.
When the intent to change from Activity A to B is activated, the onPause() method will be executed.
As such, the onPause() method will be a good place for you to save the state of your Activity.
public static final String SHARED_PREFERENCE = "";
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(SHARED_PREFERENCE,0);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.putInt("ID", id);
editor.commit();
}
You will have to recover your SharedPreferences onResume() and onCreate().
Answered By - sihao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.