Pass ArrayList from fragment to another fragment(extends ListFragment) using bundle, seListAdapter runtime error

吃可爱长大的小学妹 提交于 2019-12-01 11:04:24

You can only pass custom object or ArrayList of custom object via Bundle(or Intent) when the object is either Parcelable or Serializable. One more thing if your fragments are in same activity then why you are passing array. you just create getter and setter for list in your Activity and access them like ((Activity)getActivity).getArraylist() in your listFragment. For creating object Parcelable do something like below.

import android.os.Parcel;
import android.os.Parcelable;

public class Address implements Parcelable {

private String name, address, city, state, phone, zip;

@Override
public int describeContents() {
    return 0;
}

/*
        THE ORDER YOU READ OBJECT FROM AND WRITE OBJECTS TO YOUR PARCEL MUST BE THE SAME
 */

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(name);
    parcel.writeString(address);
    parcel.writeString(city);
    parcel.writeString(state);
    parcel.writeString(phone);
    parcel.writeString(zip);
}


public Address(Parcel p){
    name = p.readString();
    address = p.readString();
    city = p.readString();
    state = p.readString();
    phone = p.readString();
    zip = p.readString();
}

// THIS IS ALSO NECESSARY
public static final Creator<Address> CREATOR = new Creator<Address>() {
    @Override
    public Address createFromParcel(Parcel parcel) {
        return new Address(parcel);
    }

    @Override
    public Address[] newArray(int i) {
        return new Address[0];
    }
};
}

I have seen your code for your given link and thats why I am posting a new Ans. One thing if you read your code carefully, you have declared ArrayAdapter<String> in Monday_fragment, so this list initialize every time when you replace this fragment with other. So just create a ArrayAdapter<String> in MainActivity and getter, setter for the same and change your methode ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs) in the Monday_fragment like below

public ArrayList<String> toStringList(Collection<DiaryLogs> entryLogs) {
    ArrayList<String> stringList =  ((MainActivity)getActivity()).getMyStringList();

    for (DiaryLogs myobj : entryLogs) {
        String objctString = myobj.toString();

        stringList.add(objctString);
    }
    ((MainActivity)getActivity()).setMyStringList(stringList); 
    return stringList;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!