0

I have class Product:

public class Product {
     private String name;
     public Product(String name) {
         this.name = name;
     }
     public String getName() {
         return name;
     }
 }

Then in MainActivity:

ArrayList<Product> products;
....
protected void onCreate(Bundle savedInstanceState) {
    ..... 
    for (int i = 1; i < 15; i++){
        products.add(new Product(Integer.toString(i)));
    }
}

After compiling and building App crashes and give such error code:

java.lang.RuntimeException: Unable to start activity ComponentInfo{panchenko.ivan.canteen_application/panchenko.ivan.canteen_application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

I don't have any ideas what goes wrong.

Sreehari
  • 5,621
  • 2
  • 25
  • 59

2 Answers2

2

A NullPointerException means you are referencing a variable in your code that you haven't assigned - i.e. it is null. There is a great Stack Overflow answer on it here that I would recommend you read through if you are new to this.

In your case, you are getting the NullPointerException because your ArrayList<Product> products is null:

You need to assign it before you can use it, so do this:

ArrayList<Product> products = new ArrayList<>();

instead of:

ArrayList<Product> products;
Community
  • 1
  • 1
Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125
0

ArrayList products = new ArrayList();

please see this its useful for starting https://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/