0

I would like to send a list from Activity A to Activity B. When I receive the data inside Activity B, I would like to make changes to the received list items. When I go back to Activity A, I would like to see the changes that I just made. So far, I have tried sending a list of data using intent but when I try to edit it the changes are not being made. Here's my code sample:

Activity A

 private var items : Lists<Items> 

  context.startActivity(
                Intent(context, B::class.java).apply {
                    putExtra("itemList", items as ArrayList)
                }
            )

Activity B

 val itemList = intent?.extras?.getSerializable("itemList") as? ArrayList<Items>

  // trying to edit the list
  itemList.forEachIndexed { index, t ->
            run {
                if (t.id == tweet.id) {
                    items[index].name = "hello"
                }
            }
        }
David Wasser
  • 89,914
  • 16
  • 195
  • 259
user7062312
  • 117
  • 2
  • 9
  • Removed `android-studio` tag as that tag is for problems/issues about the Android Studio product. Your question is a generic Android question. – David Wasser Sep 15 '21 at 08:55

1 Answers1

0

Basically you can use startActivityForResult in this case

Let me explain with an example

From your FirstActivity call the SecondActivity using the startActivityForResult() method

For example:

int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY

In your SecondActivity, set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In SecondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

Now in your FirstActivity class, write the following code for the onActivityResult() method.

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

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            // Write your code if there's no result
        }
    }
} //onActivityResult

Thanks to this answer. You can look it up for more details

gtxtreme
  • 1,219
  • 1
  • 7
  • 20