Skip to content
Advertisement

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

I want to pass the list of itemselected or ItemsInCart to another activity. My Items Model implements parcelable. The problem is am getting error below in my 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)

Below is the code

Model Item;

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

}

First Activity; The list that i want to pass to second activity is ‘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);

        }
    });

Second Activity (in OnCreate method):

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

I have found similar questions and tried their solutions but all is not working. Please advise on what i have to change.

Second Activity Adapter.

public class SecondActivity_Adapter extends RecyclerView.Adapter<SecondActivity_Adapter.MyViewHolder> { private 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);
    }
}

}

Advertisement

Answer

Check whether you have added RecyclerView in xml i.e, activity_second.xml

If you have added Recyclerview in xml check whether you have referenced it using findViewById in SecondActivity

RecyclerView CartItemsInRecyclerView = findViewById(R.id.recyclerview_id)

You are getting error for Layout Manager i.e referencing it using null object reference , that means CartItemsInRecyclerView is null

Edit :

In First 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())

 }
        
 

In Second Activity:-

Instead of bundle.getgetParcelableArrayList try 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")
 }

Then check the result in Logcat

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement