简体   繁体   中英

Pass array of custom objects to another Activity in android

I am new to android programming, and I am trying to send an array of custom objects to a different activity. In the first activity I have a function that creates an intent and adds the array of objects to it:

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    nextScreen.putExtra("array", tasks);
    startActivity(nextScreen);
}

However, I'm not sure how to get that data at the next screen.

Is there any way to get that array in the code for the next activity even though "tasks" is an array of custom objects?

Did you try it with Gson ?

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    String arrayAsString = new Gson().toJson(tasks);
    nextScreen.putExtra("array", arrayAsString);
    startActivity(nextScreen);
}

In your second activity, parse the extra data back into the List<T>

public void parseBack(){
    String arrayAsString = getIntent().getExtras().getString("array");
    List<YourType> list = Arrays.asList(new Gson().fromJson(arrayAsString, YourType[].class));
}

让你的自定义对象实现Parcelable ,为了利用putParcelableArrayListExtraIntent类。

You didn't search a lot...

Check this for Parcelable interface : How to send an object from one Android Activity to another using Intents?

edit : This too, https://guides.codepath.com/android/Using-Parcelable

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