如何使用 parcelable 将对象列表从一个 activity 传递到另一个

How to pass a list of objects from one activity to another using parcelable

我想将 itemselected 或 ItemsInCart 列表传递给另一个 activity。我的项目模型实现了 parcelable。问题是在我的 SecondActivity class.

中出现以下错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference at com.example.Project1.SecondActivity.onCreate(SecondActivity.java:59)

下面是代码

模型项目;

public class Item implements Parcelable {
private int iid;
private String itenname;
private String itemprice;
private String itemstock;
private int totalInCart;
private List<Item> items;

public Item(int iid, String itenname, String itemprice, String itemstock, int totalInCart,List<Item> items) {
    this.iid = iid;
    this.itenname = itenname;
    this.itemprice = itemprice;
    this.itemstock = itemstock;
    this.totalInCart = totalInCart;
    this.items = items;
}

protected Item(Parcel in) {
    iid = in.readInt();
    itenname = in.readString();
    itemprice = in.readString();
    itemstock = in.readString();
    totalInCart = in.readInt();
    items = in.createTypedArrayList(Item.CREATOR);
}

public static final Creator<Item> CREATOR = new Creator<Item>() {
    @Override
    public Item createFromParcel(Parcel in) {
        return new Item(in);
    }

    @Override
    public Item[] newArray(int size) {
        return new Item[size];
    }
};

public List<Item> getItems() {
    return items;
}

public void setItems(List<Item> items) {
    this.items = items;
}

public int getIid() {
    return iid;
}

public void setIid(int iid) {
    this.iid = iid;
}

public String getItenname() {
    return itenname;
}

public void setItenname(String itenname) {
    this.itenname = itenname;
}

public String getItemprice() {
    return itemprice;
}

public void setItemprice(String itemprice) {
    this.itemprice = itemprice;
}

public String getItemstock() {
    return itemstock;
}

public void setItemstock(String itemstock) {
    this.itemstock = itemstock;
}

public int getTotalInCart() {
    return totalInCart;
}

public void setTotalInCart(int totalInCart) {
    this.totalInCart = totalInCart;
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(iid);
    dest.writeString(itenname);
    dest.writeString(itemprice);
    dest.writeString(itemstock);
    dest.writeInt(totalInCart);
    dest.writeTypedList(items);
}

}

第一个Activity; 我想传递给第二个 activity 的列表是 'itemsInCart'

buttonCheckout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (itemsInCart==null||itemsInCart.size()<=0){
                Toast.makeText(List_Items.this, "Please add some items to the cart.", Toast.LENGTH_SHORT).show();
                return;
            }

           ArrayList<Item> additems = new ArrayList<Item>();
            for (int i = 0; i < itemsInCart.size(); i++){
                additems.add(itemsInCart.get(i));
            }

            Intent intent = new Intent(MainActivity.this,DisplaySelectedItems.class);
            intent.putParcelableArrayListExtra ("Itemselected", additems);
            startActivity(intent);

        }
    });

第二个Activity(在 OnCreate 方法中):

Bundle bundle = getIntent().getExtras();
    ArrayList<Item> selecteditems = bundle.getParcelableArrayList("Itemselected");

    CartItemsInRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 
    placeOrderAdapter = new PlaceOrder_Adapter((ArrayList<Item>) items); <- This is line 59 of the error
    CartItemsInRecyclerView.setAdapter(placeOrderAdapter);

我发现了类似的问题并尝试了他们的解决方案,但都没有用。 请告知我必须更改的内容。

第二个 Activity 适配器。

public class SecondActivity_Adapter 扩展 RecyclerView.Adapter { 私有 ArrayList itemList;

public SecondActivity_Adapter(ArrayList<Item> itemList){
    this.itemList = itemList;
}

public void updateData(ArrayList<Item> itemList){
    this.itemList = itemList;
    notifyDataSetChanged();
}

@NonNull
@Override
public SecondActivity_Adapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_of_place_order,parent,false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SecondActivity_Adapter.MyViewHolder holder, int position) {
    holder.name.setText(itemList.get(position).getItenname());
    holder.price.setText("Unit Price: "+String.format("%.0f",itemList.get(position).getItemprice())+"/=");
    holder.QTY.setText("Qty: "+itemList.get(position).getTotalInCart());
}

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

static class MyViewHolder extends RecyclerView.ViewHolder {
    TextView menuName,menuPrice,menuQTY,tvCount;

    public MyViewHolder(View view){
        super(view);

        name = view.findViewById(R.id.menuName);
        price = view.findViewById(R.id.menuPrice);
        QTY = view.findViewById(R.id.menuQTY);
        tvCount = view.findViewById(R.id.tvCount);
    }
}

}

检查是否在xml中添加了RecyclerView即activity_second.xml

如果您在xml中添加了Recyclerview,请检查您是否在SecondActivity

中使用findViewById引用了它

RecyclerView CartItemsInRecyclerView = findViewById(R.id.recyclerview_id)

布局管理器出现错误,即使用空对象引用引用它,这意味着 CartItemsInRecyclerView 为空

编辑:

首先activity:-

 for (int i = 0; i < itemsInCart.size(); i++){

            additems.add(itemsInCart.get(i));

        }

//log statement 

 for (int i = 0; i < additems.size(); i++){

  Log.d("firstActivity",i.getItenname())

 }
        
 

秒Activity:-

而不是 bundle.getgetParcelableArrayList 尝试 getIntent().getgetParcelableArrayList

  ArrayList<Item> selecteditems = 
  getIntent().getParcelableArrayList("Itemselected");

//log statement

 if(selecteditems.size()!=0){

   for (int i = 0; i < selecteditems.size(); i++){

       Log.d("secondActivity",i.getItenname())
  }

 }else{

    Log.d("secondActivity","empty data")
 }

然后在Logcat

中查看结果