Android: Clear old activity instance from history stack

wawanopoulos :

I have the following simple scenario:

  • One Activity called ListCarsActivity.kt where list of cars are displayed. When the user click on the FloatingActionButton, it opens another activity called AddCarActivity.kt
  • When the user click on the Add Car button, I start a new intent to go to the initial activity ListCarsActivity.kt where the added car is now displayed.

Problem: From now, when I click on the Back button, the ListCarsActivity is displayed a second time.

How to clear the old entry of ListCarsActivity from the History stack?

enter image description here

Rakshit Nawani :

Call your AddCarActivity.kt Activity like below inside your ListCarsActivity.kt

val intent = Intent(mContext, AddCarActivity.class);
startActivityForResult(intent, 1); //Use any request code

Now for the above code what startActivityForResult do is that it is an intent to receive data back from some other activity or source(like camera, contacts, etc)

Now when all the work is done in your AddCarActivity.kt you can all the below intent to get the result back

                Intent intent = getIntent();
                intent.putExtra("key", data); // if you wanted to get data 
                setResult(RESULT_OK, intent);
                finish();

And inside your ListCarsActivity.kt you need to add onActivityResult which will get the data from AddCarActivity.kt

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

        if (resultCode == RESULT_OK) {
            if (requestCode == 1) { //Your request code here
                Object obj = data.getParcelableExtra("key");
                 //Do as per your needs

            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

With this, if you wanted to return the newly added data back in the first activity it can be fetched without the usage of any third-party libs.

Try it and do let me know if it worked for you.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7281&siteId=1