我想将数据存储在ArrayList中并在另一个类中访问它,但是当我访问时arraylist,它arraylist.size()是0。意味着我没有访问相同的arraylist。有人告诉我我做错了。
arraylist
arraylist.size()
这是我的POJO课
public class item { private String name; private String body; private String profileImage; public Item(){ } public Item(String body,String name,String profileImage){ this.body = body; this.name = name; this.profileImage = profileImage; } //Getter and setter
这是我将数据存储在 A类中的方法 , 该类 已经过检查,已成功将其插入到arraylist中。
A级
List<Item> items = new ArrayList<>(); Item item = new Item(); item.setBody(body); item.setName(name); item.setProfileImage(profileImage); items.add(item);
问题出在 B类中, 当我访问item.size()它的返回值0时,意味着我没有访问相同的arraylist。
item.size()
这是我在 B类中* 所做的 *
List<Item>items = new ArrayList<>(); Log.d("ListSize",String.valueOf(items.size()));
我尝试过RecycleView之前做过的事情,但这不起作用,因为我的B类是Fragment活动
RecycleView
public Class B(Context mContext, List<Item> items) { this.mContext = mContext; this.items = items; }
那么,什么是正确的办法,我初始化我数据保存到ArrayList A类 的 B类 ?
像这样更改类:
public class Item implements Parcelable{ private String name; private String body; private String profileImage; public Item(){ } public Item(Parcel in) { name = in.readString(); body = in.readString(); profileImage = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(body); dest.writeString(profileImage); } @SuppressWarnings("unused") public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { @Override public Item createFromParcel(Parcel in) { return new Item(in); } @Override public Item[] newArray(int size) { return new Item[size]; } }; public Item(String body,String name,String profileImage){ this.body = body; this.name = name; this.profileImage = profileImage; }
现在处于A类:
ArrayList<Item> mDATA = new ArrayList<>(); /****** add values in array list ****/ Intent i = new Intent(CLASS_A.this, CLASS_B.class); i.putParcelableArrayListExtra("ARRAY_DATA", mDATA); startActivity(i);
现在在B类中,获取列表:
Intent intent = getIntent(); ArrayList<Item> mDATAFROMA = new ArrayList<>(); try { mDATAFROMA = intent.getParcelableArrayListExtra("ARRAY_DATA"); Log.d("ListSize",String.valueOf(mDATAFROMA.size())); } catch (Exception e) { e.printStackTrace(); }
对于破裂通过:
Bundle args = new Bundle(); args.putParcelableArrayList("GET_LIST", (ArrayList<? extends Parcelable>) mDATA); fragmentDemo.setArguments(args);
并在片段中获取:
ArrayList<Item> mDATAFROMA = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle pb=getArguments(); mDATAFROMA = pb.getParcelableArrayList("GET_LIST"); }