I have tried using Static variable for the ArrayList but in the ListFragment class, while debugging it\'s value is null.
I think the ListFragment gets created before
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;
}
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];
}
};
}