Home > Blockchain >  setAdapter() crashes android app in android studio
setAdapter() crashes android app in android studio

Time:11-12

I'm following this tutorial (https://www.youtube.com/watch?v=hDSVInZ2JCs&t=3615s&ab_channel=SoftwareandProgrammingwithProfessorSluiter)

Everything works great, until I try this line of code :

lv_productList.setAdapter(productArrayAdapter);

then the app crashes. I've looked online and tried a bunch of stuff but I'm super stuck

Here's the problem area

        btn_viewAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
            List<ProductModel> all = dataBaseHelper.getAll();

            ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
            lv_productList.setAdapter(productArrayAdapter);

            Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
        }
    });

here's my full code

MainActivity.java

package com.example.sqldemo;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;


public class MainActivity extends AppCompatActivity {

    //reference to all buttons and controls on the layout
    Button btn_add, btn_viewAll;
    EditText et_name, et_number;
    ListView lv_productList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_add = findViewById(R.id.btn_add);
        btn_viewAll = findViewById(R.id.btn_viewAll);
        et_name = findViewById(R.id.et_name);
        et_number = findViewById(R.id.et_number);

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ProductModel productModel;

                try {
                   productModel = new ProductModel(-1, et_name.getText().toString(), Integer.parseInt(et_number.getText().toString()));
                   Toast.makeText(MainActivity.this, productModel.toString(), Toast.LENGTH_SHORT).show();
                }
                catch(Exception err) {
                    Toast.makeText(MainActivity.this, "Error creating product", Toast.LENGTH_SHORT).show();
                    productModel = new ProductModel(-1, "error", 0);
                }

                DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);

                boolean success = dataBaseHelper.addOne(productModel);

                Toast.makeText(MainActivity.this, "Success! Product has been added to the database :)", Toast.LENGTH_SHORT).show();


            }
        });

        btn_viewAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
                List<ProductModel> all = dataBaseHelper.getAll();

                ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
                lv_productList.setAdapter(productArrayAdapter);

                Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
            }
        });

    }
}

DataBaseHelper.java

package com.example.sqldemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

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

public class DataBaseHelper extends SQLiteOpenHelper {

    public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
    public static final String COLUMN_PRODUCT_NAME = "PRODUCT_NAME";
    public static final String COLUMN_PRODUCT_NUMBER = "PRODUCT_AGE";
    public static final String COLUMN_ID = "ID";

    public DataBaseHelper(@Nullable Context context) {
        super(context, "Products.db", null, 1);
    }

    //this is called the first item a database is accessed. used to create a new database
    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableStatement = "CREATE TABLE "   PRODUCT_TABLE   " ("   COLUMN_ID   " INTEGER PRIMARY KEY AUTOINCREMENT, "   COLUMN_PRODUCT_NAME   " TEXT, "   COLUMN_PRODUCT_NUMBER   " INT)";

        db.execSQL(createTableStatement);
    }
    //this is called if the database version number changes. It prevents previous users apps from breaking when the database is updated
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public boolean addOne(ProductModel productModel) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_PRODUCT_NAME, productModel.getName());
        cv.put(COLUMN_PRODUCT_NUMBER, productModel.getNumber());

        //long insert returns positive in data insertion was successful, and negative if it was not
        long insert = db.insert(PRODUCT_TABLE, null, cv);
        if (insert == -1) {
            return false;
        }
        else {
            return true;
        }
    }

    public List<ProductModel> getAll() {
        List<ProductModel> returnList = new ArrayList<>();

        // get data from the database
        String queryString = "SELECT * FROM "   PRODUCT_TABLE;

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(queryString, null);
        //move the cursor to the first set of data and check if anything was returned
        if (cursor.moveToFirst()) {
            // loop through the cursor (result set) and create new product objects. Put them into the return list (defined above)
            do {
                int productID = cursor.getInt(0);
                String productName = cursor.getString(1);
                int productNumber = cursor.getInt(2);

                ProductModel newProduct = new ProductModel(productID, productName, productNumber);
                returnList.add(newProduct);

            } while (cursor.moveToNext());


        }
        else {
            //if no results from database, don't add anything to the list.
        }
        cursor.close();
        db.close();
        return returnList;

    }


}

ProductModel.java

package com.example.sqldemo;

//declare a new public class/object with 3 variables
public class ProductModel {
    private int id;
    private String name;
    private int number;

    //constructor

    public ProductModel(int id, String name, int number) {
        this.id = id;
        this.name = name;
        this.number = number;
    }

    public ProductModel() {
    }


    // toString is necessary for printing the contents of a class object


    @Override
    public String toString() {
        return "ProductModel{"  
                "id="   id  
                ", name='"   name   '\''  
                ", number="   number  
                '}';
    }

    //getters and setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

}

> Blockquote

CodePudding user response:

You can simply change RecyclerView to ListView.

Or

if you want to use RecyclerView, you have to create a custom Recyclerview Adapter. Here a Beginner friendly Guide: https://medium.com/@suhanshupatel/recyclerview-in-android-for-beginner-cfbc132a0dec

  • Related