При нажатии на кнопку "Добавить" введенное название должно появляться в listView, но этого не происходит. В чем Ошибка?

Пытаюсь написать программу "список товаров", где через кнопку вызывается диалоговое окно ( alertdialog) в диалоговом окне нужно ввести название и количество товара и нажать на кнопку добавить, эти значения должны появится в listView. Ошибка происходит после нажатия на кнопку добавить.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/productListView"
        android:layout_width="310dp"
        android:layout_height="605dp"
        android:drawSelectorOnTop="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.674" />

    <Button
        android:id="@+id/addproductbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Plus"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.914"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.04" />
</androidx.constraintlayout.widget.ConstraintLayout>

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;
import java.util.ArrayList;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayAdapter<Product> adapter;
    private List<Product> productList = new ArrayList<>();


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



        listView = findViewById(R.id.productListView);
        adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1,
                ProductCategoryManager.getInstance(getApplicationContext()).productList);

        listView.setAdapter(adapter);

        // добавляем товары в список
        productList.add(new Product("Product 1", 10));
        productList.add(new Product("Product 2", 5));
        productList.add(new Product("Product 3", 3));
        // обновляем список товаров в адаптере
        adapter.notifyDataSetChanged();

        Button addButton = findViewById(R.id.addproductbutton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // открыть диалоговое окно для добавления товара
                showDialogForAddingProduct();
            }
        });

        // код для работы с продуктами и категориями

    }

    public void showDialogForAddingProduct() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Добавить продукт");
        builder.setMessage("Ввести имя продукта:");
        // создаем макет для диалогового окна
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        // добавляем поля для ввода названия и количества товара
        final EditText inputEditText = new EditText(this);
        inputEditText.setHint("Название товара");
        layout.addView(inputEditText);
        final EditText quantityEditText = new EditText(this);
        quantityEditText.setHint("Количество товара");
        quantityEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        layout.addView(quantityEditText);

        builder.setView(layout);

// добавляем кнопки "Добавить" и "Отмена"

        builder.setPositiveButton("Добавить", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // обработчик нажатия на кнопку "Добавить"
                String productName = inputEditText.getText().toString();
                String quantityString = quantityEditText.getText().toString();
                if (TextUtils.isEmpty(productName) || TextUtils.isEmpty(quantityString)) {
                    Toast.makeText(MainActivity.this,
                            "Введите название и количество товара", Toast.LENGTH_SHORT).show();
                    return;
                }
                int quantity = Integer.parseInt(quantityString);
                if (quantity <= 0) {
                    Toast.makeText(MainActivity.this, 
                            "Количество товара должно быть больше 0", Toast.LENGTH_SHORT).show();
                    return;
                }
                // Добавляем продукт в список и обновляем адаптер
                Product newProduct = new Product(productName,quantity);
                ProductCategoryManager.getInstance(getApplicationContext()).addProduct(newProduct);
                adapter.notifyDataSetChanged();
            }
        });

        builder.setNegativeButton("Отмена ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }



    public static class ProductCategoryManager {
        private List<Product> productList;
        private static ProductCategoryManager instance;

        private Context context;

        private ProductCategoryManager(Context context) {
            this.context = context;
            productList = new ArrayList<>();
        }

        public static ProductCategoryManager getInstance(Context context) {
            if (instance == null) {
                instance = new ProductCategoryManager(context);
            }
            return instance;
        }



        public void addProduct(Product product) {
            ListView listView = ((MainActivity) context).findViewById(R.id.productListView);
            // получаем адаптер списка
            ArrayAdapter<Product> adapter = (ArrayAdapter<Product>) listView.getAdapter();
            // обновляем список товаров в адаптере
            adapter.notifyDataSetChanged();

            productList.add(product);

            adapter.notifyDataSetChanged();
        }

        public void removeProduct(Product product) {
            ListView listView = ((MainActivity) context).findViewById(R.id.productListView);
            // получаем адаптер списка
            ArrayAdapter<Product> adapter = (ArrayAdapter<Product>) listView.getAdapter();
            // обновляем список товаров в адаптере
            adapter.notifyDataSetChanged();

            productList.remove(product);

            adapter.notifyDataSetChanged();
        }
    }
    // создаем класс для товара


    public static class Product {

        private String name;
        private int quantity;

        public Product(String name, int quantity) {
            this.name = name;
            this.quantity = quantity;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getQuantity() {
            return quantity;
        }

        public void setQuantity(int quantity) {
            this.quantity = quantity;
        }

        @Override
        public String toString() {
            return name + " (" + quantity + ")";
        }
    }

}

Ответы (0 шт):