Passing arraylist of custom object to another activity

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 18:14:24

You can't have DoctorObject#writeToParcel() empty, that is what actually copies the object data.

@Override
public void writeToParcel(Parcel dest, int flags) {
    // the order you write to the Parcel has to be the same order you read from the Parcel
    dest.writeInt(DocPic);
    dest.writeString(Docname);
    dest.writeString(Docspecialty);
    dest.writeString(DocLocation);
}

And to read back your data in the other activity, use getParcelableArrayListExtra

ArrayList<DoctorObject> list = b.getParcelableArrayListExtra("NAME");

You can use Gson Library to Pass an ArrayList to another Activity in case if you T object is not a Parcelable Object. Where is Generic Type. In your case, it is ArrayList

Step 1: First Import Gson Library using Gradle Script

Add this line in your Gradle dependency

dependencies {
    compile 'com.google.code.gson:gson:2.7'
}

Step 2: Convert ArrayList into JSON String and pass the JSON String from Activity 1 to Activity 2

        ArrayList<DoctorObject> doctors = new ArrayList<Location>();
        doctors.add(new DoctorObject(params));
        doctors.add(new DoctorObject(params));

        Gson gson = new Gson();
        String jsonString = gson.toJson(doctors);
        Intent intent = new Intent(MainActivity.this,MapsActivity.class);
        intent.putExtra("KEY",jsonString);
        startActivity(intent);

Step 3: Get the JSON String from Bundle and convert it to ArrayList back

    import java.lang.reflect.Type;


    Bundle bundle = getIntent().getExtras();
    String jsonString = bundle.getString("KEY");

    Gson gson = new Gson();
    Type listOfdoctorType = new TypeToken<List<DoctorObject>>() {}.getType();
    ArrayList<DoctorObject> doctors = gson.fromJson(jsonString,listOfdoctorType );

Use getParcelableArrayListExtra instead of getSerializableExtra because sending ArrayList object from previous Activity using putParcelableArrayListExtra:

 ArrayList<DoctorObject> list = b.getParcelableArrayListExtra("NAME");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!