Ivan Panchenko Ivan Panchenko - 8 months ago 23
Android Question

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.


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;