简体   繁体   中英

How to pass ArrayList using Intent?

I want to pass model ArrayList using Intent. My case is like I am in Activity and wants to pass Arraylist from Activity to Fragment. How can achieve this?

Add this code in Activity:

Bundle bundle=new Bundle();
bundle.putSerializable("key",mainList);
YourFragment chatFragment=new YourFragment ();
chatFragment.setArguments(bundle);

Add this code in Fragment:

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=getArguments();
        if(bundle!=null){
            ArrayList<Object> list=(ArrayList<Object>)bundle.get("key");
        }
    }
public <T extends Object>T getObjectFromJson(String responseBody, Class<T> classType) {
        new Gson().fromJson(responseBody, classType);
    }

    public String getJsonString(Object object) {
        new Gson().toJson(object).toString();
    }

Add a dependency for gson in your build.gradle and then use teh function getJsonString() to convert your arraylist into string and pass it in the intent and in the other activity use the function getObjectFromJson() to convert the string back to the arraylist object

You can go for Gson

to send in intent

intent.putExtra("myList", Gson().toJson(mylist))

to retrive

val mylist = Gson().fromJson<ArrayList<Object>>(listJson, object : TypeToken<HashMap<Object>>() {}.type)

Use standard way to pass arraylist between two activities. Use Parcelable. Refer this link https://developer.android.com/reference/android/os/Parcelable.html for more details.

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