0

I'm new and can't seem to find the error even though I've read through similar topics on the site. I understand the gist of my error but cant seem to fix it. I'm making a basic "shopping cart" for a project, and would like to pass items from a custom ArrayList to another custom ArrayList via onClickListener in RecycleView. . I have a feeling that it is with the "position", as it is the only common element between the lines of code in question. I have marked the three lines that came up in the error messages.

        public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MainAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<Inventory> mInventoryList;
    private int position;


    private Button button;
    private ArrayList<Inventory> cartList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Estimate("XXX000","John Smith", "john@gmail.com", cartList);


        InputStream inputStream = getResources().openRawResource(R.raw.data);
        CSVreader csvFile = new CSVreader(inputStream);
        ArrayList<Inventory> inventoryList = (ArrayList<Inventory>) csvFile.read();

        mRecyclerView = findViewById(R.id.recyclerviewMain);
        mRecyclerView.setHasFixedSize(true);   
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new MainAdapter(inventoryList); 
        mInventoryList = inventoryList;

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    Intent intent = new Intent(v.getContext(), EstimateActivity.class);
                    intent.putExtra("cartList", cartList); 
                    v.getContext().startActivity(intent);
            }
        });



        mAdapter.setOnItemClickListener(new MainAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                addToCart(position); //ERROR HERE
            }
        });
    }

    public void addToCart(int position){

        cartList.add(position, new Inventory()); //ERROR HERE
    }


}
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
    private ArrayList<Inventory> mInventoryList;
    private ArrayList<Inventory> mCartList;
    private OnItemClickListener mListener;


    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }


    public static class MainViewHolder extends RecyclerView.ViewHolder {
        private TextView cardCode;
        private TextView cardName;
        private CardView containerView;
        private ArrayList<Inventory> cartList;


        public MainViewHolder(View itemView, final OnItemClickListener listener) {
            super(itemView);

            cardCode = itemView.findViewById(R.id.text_row_code_viewMain);
            cardName = itemView.findViewById(R.id.text_row_name_viewMain);
            itemView = itemView.findViewById(R.id.container_viewMain);



            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null ){
                        int position = getAdapterPosition(); //ERROR HERE
                        if (position != RecyclerView.NO_POSITION){
                            listener.onItemClick(position);  
                        }
                    }
                }
            });

        }
    }

    public MainAdapter(ArrayList<Inventory> inventoryList){   
        mInventoryList = inventoryList;

    }

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

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        Inventory currentItem = mInventoryList.get(position);
        holder.cardName.setText(currentItem.getName());
        holder.cardCode.setText(currentItem.getCode());
        holder.itemView.setTag(currentItem);

    }



    @Override
    public int getItemCount() {
        return mInventoryList.size();
    }
}
    11357/com.jourdon.cartsavetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jourdon.cartsavetest, PID: 11357
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.ArrayList.add(int, java.lang.Object)' on a null object reference
    at com.jourdon.cartsavetest.MainActivity.addToCart(MainActivity.java:76)
    at com.jourdon.cartsavetest.MainActivity$2.onItemClick(MainActivity.java:69)
    at com.jourdon.cartsavetest.MainAdapter$MainViewHolder$1.onClick(MainAdapter.java:49)
    at android.view.View.performClick(View.java:7448)
    at android.view.View.performClickInternal(View.java:7425)
    at android.view.View.access$3600(View.java:810)
    at android.view.View$PerformClick.run(View.java:28305)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

2020-11-04 17:51:47.720 11357-11357/? I/Process: Sending signal. PID: 11357 SIG: 9

DayoJayo
  • 17
  • 7

1 Answers1

1

Just declaring your variable cartList, which you did on this line:

     private ArrayList<Inventory> cartList;

is not enough. You also need to initialize this variable with an actual list that you can add items to.

When you declare a variable, you're telling Java that you plan to use an object of a certain type in your program, and you are telling Java what the name of the variable is along with the type.

But, declaring a variable doesn't give you an actual list. What you need to do is create a list and store it in your variable. You probably want to do this in the MainViewHolder constructor method. The initialization line might look like this:

 cartList = new ArrayList<Inventory>();
Andrew Merrill
  • 1,672
  • 11
  • 14
  • Thanks! I could tell that I needed to initialize something but I was having trouble figuring out what and where. Great lesson learned tonight. Cheers! – DayoJayo Nov 05 '20 at 04:02
  • Glad that helped! And welcome to StackOverflow! By the way, remember that you can upvote any answers that you find helpful, and also mark as "accepted" an answer that solves your problem. Accepting an answer is an indication to other users that they don't need to try to answer the question themselves, or if they have a similar problem, then they might want to start with the accepted answer to see if it helps them. – Andrew Merrill Nov 05 '20 at 05:25