Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing back button calls onCreate (Android)

Activity A starts Activity B. In Activity B, I have this method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpTo(this, new Intent(this,
                ArticleListActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

When I press that home button, it takes me to Activity A as it should. However, onCreate is being called again. I do not want this behavior.

I'm guessing its because this implementation uses new Intent to previous item in the navigation stack. This is just code I got from Eclipse when creating the double pane project though. I looked around on stack overflow, and though it seems that using an Intent to go back is causing this behavior, I do not understand why Google would provide this in a default template.

How should I make this call differently so that onCreate is not called again when going back to Activity A?

like image 489
Beebunny Avatar asked Aug 05 '14 06:08

Beebunny


2 Answers

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
       finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

just finish current activity it will take you on previous activity if your previous activity is activity A then just use finish(); method instead of creating object of intent

like image 134
Android is everything for me Avatar answered Oct 18 '22 04:10

Android is everything for me


As pointed out by @Rajesh you need to call onBackPressed().

Your code detects the home button press and creates a new ArticleListActivity class.However, you don't want to create a new class you only want to go back to your already created class/activity. so use onBackPressed() instead.

like image 29
Deepak Negi Avatar answered Oct 18 '22 04:10

Deepak Negi