0

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

}

creg
  • 13
  • 4

1 Answers1

0

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

Shobhith
  • 505
  • 4
  • 12
  • Thank you @Shobhith. You are right i hadn't referenced RecyclerView CartItemsInRecyclerView. I have referenced it and now able to start the second Activity. However the RecyclerView is empty, meaning either the first activity is not sending the data or the second activity is not extracting it from the intent. Kindly help again. How can i display in the recycler of second activity, the list of items selected in first activity? – creg May 26 '21 at 13:31
  • Check whether your first activity is sending data and Second activity is receiving it using Log statements – Shobhith May 26 '21 at 13:34
  • Kindly provide me an example on this. – creg May 26 '21 at 13:41
  • i have logged the data being sent from first activity . below is what is what being sent. [com.example.Project1.Models.Item@6ddbfc4, com.example.Project1.Models.Item@2708ead, com.example.Project1.Models.Item@c33a5e2] I selected 3 items in First activity. Please help on how to correctly send the list from First activity to second Activity. and how to retrieve it in Second activity. – creg May 26 '21 at 14:27
  • `Log.d("secondActivity",i.getItenname());` is marked red in the for loop, with error cannot resolve method getItenname() – creg May 26 '21 at 15:00
  • getItenname() you have this method in your model class right? – Shobhith May 26 '21 at 15:06
  • Then you should be to access it inside LogCat because we are looping through list of Item class – Shobhith May 26 '21 at 15:15
  • But if i use getItenname() in the Activities, how will the Adapter get the elements in the onBindViewHolder. I have added the Adapter in the code above. – creg May 26 '21 at 15:17
  • In getItemCount() of adapter don't return 0 instead return itemList.size().....getItemname() was used just to check whether data is coming to second activity – Shobhith May 26 '21 at 15:22
  • you are the best. Second Activity is now displaying whatever was selected in first activity. My other question is, am picking the items from sqlite database. when the user confirms the order, how can i update the db with the qty ordered for each item? Also, how can i calculate the total amount of all the selected items on the second activity? i want to put the total below the list of items selected. – creg May 26 '21 at 15:40
  • Can you explain your app behavior in brief? – Shobhith May 26 '21 at 15:46
  • The App is kind of a big shop POS. when a customer comes to the shop, the shop keeper selected on the app, the items that the customer wants. then confirms the order. am using sqlite database. so after the order, i want to reduce the stock of each of the ordered items in the db by the qty taken. such that the user is able to keep track of how much stock is left. – creg May 26 '21 at 15:55