Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onBackPressed not calls after recreate()

Problem description:

My App has Main activity and Setting Activity. After each closing Settings Activity, Main Activity recreates.

Main Activity can be closed (App exit) by finish() in two places: Home button in Action Bar and Back Button (hardware or popup bar).

Home button works without problem, the Back button works at the start, but if a user was in Settings Activity, closed it and return to Main Activity, onBackPressed() function not called anymore.

If I delete recreation the Back button works fine, just like Home button.

So if somebody know why recreate() messing up with Back button?

Thanks.

Parts of relevant code:

Main Activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        // Open Settings Activity
        case R.id.menuSettings:

            Intent intent = new Intent(this, SettingsActivity.class);
            startActivityForResult(intent, REQUEST_SETTINGS);

            return true;

        // Close the App
        case android.R.id.home:

            finish();

            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != RESULT_OK) {

        return;
    }

    switch (requestCode) {

        case REQUEST_SETTINGS:

            // Recreate activity
            recreate();

            break;
    }
}

// Close App on Back Button Click
@Override
public void onBackPressed() {
    super.onBackPressed();

    finish();
}

}

like image 430
Slava Avatar asked Nov 08 '22 13:11

Slava


1 Answers

simply replace recreate() method with

finish();
startActivity(getIntent());

& see the magic. You don't need to set any bundle and intent newly.

like image 142
Ahamadullah Saikat Avatar answered Nov 14 '22 22:11

Ahamadullah Saikat