简体   繁体   中英

Pass ArrayList of custom objects from child activity back to parent

I'm making a basic habit tracking app. I have a fragment class called HabitFragment (it's a fragment because it is just one part of a multi-tabbed app) that displays a list of Habits (which are objects of a custom Habit class and contain name, frequency, etc), each of which has a "log" button. This log button takes the user to another activity called HabitLog, where they say at which date and time they performed said habit. In this Activity I have an ArrayList of custom objects which store the date and time of a habit recorded by the user, aptly called HabitDateAndTime. I want to be able to send this ArrayList back to the HabitFragment class on the press of a button. I can't get it to work.

I have tried this in the onCreate method of my HabitLog activity. It is based on what I could find on old posts on this site:

    doneButton.setOnClickListener(v -> {
        Gson gson = new Gson();
        Intent data = new Intent();
        data.putExtra("dateTimes", gson.toJson(datesAndTimes));
        setResult(RESULT_OK, data);
        finish();
    });

and this in the onResume of HabitFragment:

public void onResume() {
    super.onResume();
    Gson gson = new Gson();
    Intent intent = this.getActivity().getIntent();
    String str = intent.getStringExtra("datesTimes");
    List<HabitDateAndTime> datesTimes = gson.fromJson(str, List.class);
}

But when I check the value of datesTimes, it says null even if I add things to it in the child activity.

How do I properly send an ArrayList of custom objects from a child activity to a parent?

Start your child Activity for result using startActivityForResult() and then in your child Activity set the result, after you have collected your data from the user, using setResult() and manually finish your child Activity using finish() . Then in the HabitLogFragment class again, override onActivityResult() to receive the data set in your child Activity .

Refer to this guide for more in depth information: https://developer.android.com/training/basics/intents/result .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM