How to initialize arraylist which store in a Pojo class in another activity?

前端 未结 1 1185
夕颜
夕颜 2021-01-27 18:44

I want to store the data in a ArrayList and access it in another class,but when when I access the arraylist,the arraylist.size() is 0.Means I didn\'t a

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 19:21

    change class like this:

    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 CREATOR = new Parcelable.Creator() {
                @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;
    }
    

    Now in Class A:

    ArrayList 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);
    

    Now in Class B, get list:

    Intent intent = getIntent();
        ArrayList mDATAFROMA = new ArrayList<>();
         try {
                        mDATAFROMA = intent.getParcelableArrayListExtra("ARRAY_DATA");
                        Log.d("ListSize",String.valueOf(mDATAFROMA.size()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    

    For fragement pass like:

    Bundle args = new Bundle();
            args.putParcelableArrayList("GET_LIST", (ArrayList) mDATA);
            fragmentDemo.setArguments(args);
    

    And in fragment fetch:

    ArrayList mDATAFROMA = new ArrayList<>(); 
    
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle pb=getArguments();
            mDATAFROMA = pb.getParcelableArrayList("GET_LIST"); 
        }
    

    0 讨论(0)
提交回复
热议问题