androidandroid-intentactivity-lifecycleback-stackup-navigation

Android: Data passed with intent disappears when coming back from deeper hierarchy


I have an OverviewActivity that contains a listview. When an item is selected, an intent is created to move to the DetailActivity and I pass an int with it.

This int is assigned to a private variable and is used to query the database.

DetailActivity code:

private int mIssueId;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_issue_detail);

    mIssueId = getIntent().getIntExtra(IssueOverviewFragment.INTENT_ISSUE_ID, -1);
    ...
}

In the DetailActivity I can go to a GraphActivity. But when I press the upButton in the GraphActivity, the application crashes because the variable became -1 in the DetailActivity (and the database can thus not be queried properly).

The hierarchy is: OverviewActivity -> DetailActivity -> GraphActivity

GraphActivity code:

protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_graph );

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ...
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_detail, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_logout: {
            Utility.redirectToLogin(this);
            break;
        }
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

How do I retain the values of my mIssueId attribute in the DetailActivity?


Solution

  • The Intent intends to pass information between activities. When Activity1 pass control to Activity2 mostly related to the behavior of the activity.

    If you have information you need to share across a complex hierarchy or to be available for your entire app, you can choice between Shared Preferences if you need persistence or use a Singleton class if the data only will be needed while the app is running.

    This is a sample for a Singleton class keeping information to available to the entire app:

    public class AppData {
      private static AppData ourInstance = new AppData ();
    
      public int score;
    
      public static AppData getInstance () {
        return ourInstance;
      }
    }
    

    And how to access it:

    AppData.getInstance().score = 100;
    

    Hope it helps.