dimanche 17 juillet 2016

Trying to make an Array list of objects but app crashes with a null pointer exeption

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.

Aucun commentaire:

Enregistrer un commentaire