Error with ArrayList<cart> items.add(new_item);

302 views Asked by At

I am having the following activity which is only responsible for adding a new object to a list of arrays of this object, but it crashes when I run it. below is all of the classes involved and part of the error message, because it is long.

First: this is the activity that invokes the second activity and starts it for result. itemDetails.java:

public class itemDetails extends AppCompatActivity implements View.OnClickListener{
    int request_Code = 1;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item);

        Bundle received = getIntent().getExtras();
        int position= received.getInt("position");
        long id=received.getLong("id");
        /*int id=0;getIntent().getIntExtra("id",id);
        int position=0;*/
//        getIntent().getIntExtra("id",id);getIntent().getIntExtra("position", position);
        Toast.makeText( this, "id= " + id + ".  and posistion=  "+ position, Toast.LENGTH_LONG).show();

        Integer[] picsId = {
                R.drawable.pic1,
                R.drawable.pic2,
                R.drawable.pic3,
                R.drawable.pic4,
                R.drawable.pic5,
                R.drawable.pic6,
                R.drawable.pic7
                };

        String[] picsNames={"Rose", "Red Dahlia","Tulip","Red rose","Aloe","Mother-in-Law's tonque","Snake"};
        String[] picCategory= {"Flowers","Flowers","Flowers","Flowers","Indoor plants","Indoor plants","Indoor plants"};
        double[] prices={5.5, 4, 3, 6, 35, 40, 42 };
        ImageView imgview = (ImageView) findViewById(R.id.item_image);
        imgview.setImageResource(picsId[position]);
        TextView nametxt= (TextView) findViewById(R.id.nametxtview);
        TextView categorytxt= (TextView) findViewById(R.id.categorytxtview);
        TextView pricetxt= (TextView) findViewById(R.id.pricetxtview);
        nametxt.setText(picsNames[position]);
        categorytxt.setText("Category:  " + picCategory[position]);

        pricetxt.setText(String.valueOf(prices[position]));


        Button cart_button= (Button)findViewById(R.id.Add2cartbutton);
        cart_button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        TextView name=  (TextView) findViewById(R.id.nametxtview);
        TextView pricetxt = (TextView) findViewById(R.id.pricetxtview);
        // cast the retrieved price to double type:
        double price = Double.parseDouble(pricetxt.getText().toString());
        Intent data= new Intent(this, AddnewItemToCart.class);
        data.putExtra("name",name.getText().toString()); // store the item name in the new intent

        data.putExtra("price", price); //, this saves the whole sentence
        startActivityForResult(data,request_Code);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == request_Code){
            if(resultCode == RESULT_OK) {
                Toast.makeText(this, data.getStringExtra("name") + "is successfully added to your cart", Toast.LENGTH_SHORT).show();
            }
            }

    }
}

Then, here is the activity that my application crashes at. AddnewItemToCart.java: which ,by the way, is not assigned to any layout.

public class AddnewItemToCart extends AppCompatActivity{


    ArrayList<cart> items;
    cart_adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        Bundle receivedData=  getIntent().getExtras();
        String name= receivedData.getString("name");
        double price=receivedData.getDouble("price");

        cart new_item= new cart(name,price); // created new Task object.
//        Toast.makeText(this, new_item.itemName + "   and    "+ new_item.price , Toast.LENGTH_LONG).show();

        items.add(new_item);
        adapter.notifyDataSetChanged();
        Intent data= new Intent();
        data.putExtra("name",name);
        setResult(RESULT_OK,data);
        //---closes the activity---
        finish();
    }
}

And this is the error message found:

FATAL EXCEPTION: main
                  Process: swe.trial, PID: 4054
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{swe.trial/swe.trial.CartActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                      at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
                      at android.widget.ListView.setAdapter(ListView.java:493)
                      at swe.trial.CartActivity.onCreate(CartActivity.java:36)
                      at android.app.Activity.performCreate(Activity.java:6664)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    package swe.trial;

This is the main activity, is it possible to merge it & AddnewItemToCart.java??

public class CartActivity extends AppCompatActivity implements View.OnClickListener {
    ArrayList<cart> items;
    cart_adapter adapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoppingcart);

        ListView cart_list= (ListView) findViewById(R.id.cart_list);
        cart_list.setAdapter(new cart_adapter(this, items));

        Button checkout = (Button) findViewById(R.id.checkout);
    }

    @Override
    public void onClick(View v) {


        Bundle receivedData=  getIntent().getExtras();
        String name= receivedData.getString("name");
        double price=receivedData.getDouble("price");

        cart new_item= new cart(name,price); // created new Task object.
//        Toast.makeText(this, new_item.itemName + "   and    "+ new_item.price , Toast.LENGTH_LONG).show();

        items.add(new_item);
        adapter.notifyDataSetChanged();
        Intent data= new Intent();
        data.putExtra("name",name);
        setResult(RESULT_OK,data);
        //---closes the activity---
        finish();

//        Toast.makeText(CartActivity.this, "Payment is not supported, Try again Later!", Toast.LENGTH_LONG).show();
    }
}


class cart_adapter extends ArrayAdapter<cart> {

    private ArrayList<cart> cart_items;
    private  Context context;

    public cart_adapter(Context context, ArrayList<cart> items) {
        super(context, R.layout.shoppingcart , items);
        this.context = context;
        this.cart_items = items;
    }


    public cart getItem(int position) {
        return cart_items.get(position);}


    public View getView(int position, View convertView, ViewGroup parent) {
        cart item = getItem(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.shoppingcart, parent, false);
        }
        TextView name= (TextView) convertView.findViewById(R.id.c_itemName);
        TextView price= (TextView) convertView.findViewById(R.id.c_itemPrice);
        name.setText(item.itemName);
        price.setText("price:  "+ item.price);

        return convertView;

    }


    public long getItemId(int position) {
        return position;

    }


}
4

There are 4 answers

0
Anil Kanani On BEST ANSWER

Please check list is null or not before use

if(items==null){
  items = new ArrayList<>();
}

now your class looks like

    public class AddnewItemToCart extends AppCompatActivity{


ArrayList<cart> items;
cart_adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle receivedData=  getIntent().getExtras();
    String name= receivedData.getString("name");
    double price=receivedData.getDouble("price");

    //check before use it


     if(items==null){
       items = new ArrayList<>();
     }

    cart new_item= new cart(name,price); // created new Task object

    items.add(new_item);
    adapter.notifyDataSetChanged();
    Intent data= new Intent();
    data.putExtra("name",name);
    setResult(RESULT_OK,data);
    //---closes the activity---
    finish();
}
}
1
Suraj Rao On

In your AddnewItemToCart You are setting items.add(new_item); which is a list in the activity (which also needs to be instantiated as posted in the other answer) and calling adapter.notifyDataSetChanged();

You need to update the items list in the cart_adapter class. For eg:

adapter.addItem(new_item);//have to add method to update arraylist of items in adapter
adapter.notifyDataSetChanged();
2
Salman Shaikh On

You have not initialized the List. Before using a List/ArrayList, you must initialize it like this:

ArrayList<cart> items = new ArrayList<>();

For Example :

public class AddnewItemToCart extends AppCompatActivity{


ArrayList<cart> items;
cart_adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle receivedData=  getIntent().getExtras();
    String name= receivedData.getString("name");
    double price=receivedData.getDouble("price");

    //Initialize like this before using it.
    ArrayList<cart> items = new ArrayList<>();

    cart new_item= new cart(name,price); // created new Task object

    items.add(new_item);
    adapter.notifyDataSetChanged();
    Intent data= new Intent();
    data.putExtra("name",name);
    setResult(RESULT_OK,data);
    //---closes the activity---
    finish();
}
}
0
Shanmugavel GK On

I review your code, you didn't initialize ArrayList items in AddnewItemToCart.java

   items = new ArrayList<>;  // This is initialize your items;