繁体   English   中英

如何在 android studio 中使用 recyclerview 显示我的数据库?

[英]How do i display my database using recyclerview in android studio?

我不知道我做错了什么。 我准备好从 listview 迁移到 recyclerview 并遵循语法然后它给了我一个错误

我的构建输出中的“element == null”

这是我的 Databasehelper 文件:

package com.revise;

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  NAME_TABLE = "NAME_TABLE";
    public static final String  COL_ID = "COLUMN_ID";
    public static final String  COLUMN_NAME = "COLUMN_NAME";
    public static final String  COLUMN_PRICE = "COLUMN_PRICE";
    public static final String  COLUMN_QUANTITY = "COLUMN_QUANTITY";
    public static final String  COLUMN_TOTAL = "COLUMN_TOTAL";
    //private static final int DATABASE_VERSION = 2;


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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableStatement = "CREATE TABLE " + NAME_TABLE + "("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_NAME + " TEXT, "
                + COLUMN_PRICE + " FLOAT, "
                + COLUMN_QUANTITY + " INT, "
                + COLUMN_TOTAL + " FLOAT)";
        db.execSQL(createTableStatement);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+NAME_TABLE);
        onCreate(db);
    }

    public boolean addOne(Product product){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_NAME, product.getName());
        cv.put(COLUMN_PRICE, product.getPrice());
        cv.put(COLUMN_QUANTITY, product.getQuantity());
        cv.put(COLUMN_TOTAL, product.getTotal());

        long insert = db.insert(NAME_TABLE, null, cv);
        if(insert==-1){
            return false;
        }
        else{ return true; }
    }

    public boolean deleteOne(Product product){
        SQLiteDatabase db = this.getWritableDatabase();
        String queryString = "DELETE FROM "+NAME_TABLE+" WHERE " +COLUMN_NAME+ "=" +product.getName();
        Cursor cursor = db.rawQuery(queryString, null);
        if(cursor.moveToFirst()){
            return true;
        }else { return false; }
    }

    public List<Product> getEveryone(){
        List<Product> returnList = new ArrayList<>();
        String queryString = "SELECT * FROM " + NAME_TABLE;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(queryString, null);
        if(cursor.moveToFirst()){
            do{
                String name = cursor.getString(1);
                float price = cursor.getFloat(2);
                int quantity = cursor.getInt(3);
                Product newProduct = new Product(name, price, quantity);
                returnList.add(newProduct);

            }while(cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return returnList;
    }
}

这是我的 RecyclerViewAdapter:

package com.revise;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{

    List<Product> productList;
    Context context;

    public RecyclerViewAdapter(List<Product> productList, Context context) {
        this.productList = productList;
        this.context = context;
    }

    @NonNull

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //itemlayout is the name of the layout that we are gonna be using
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemlayout,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        holder.tv_name.setText(productList.get(position).getName());//tv_name
        holder.tv_price.setText(String.valueOf(productList.get(position).getPrice()));
        holder.tv_qty.setText(String.valueOf(productList.get(position).getQuantity()));
        holder.tv_total.setText(String.valueOf(productList.get(position).getTotal()));
    }

    @Override
    public int getItemCount() {
        return productList.size();
    }

    public class ViewHolder extends  RecyclerView.ViewHolder{
        //variables from my itemlayout
        TextView tv_name, tv_price, tv_qty, tv_total;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_price = itemView.findViewById(R.id.tv_price);
            tv_qty = itemView.findViewById(R.id.tv_qty);
            tv_total = itemView.findViewById(R.id.tv_total);
        }
    }
}

正在配置按钮的活动:

package com.revise;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

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

public class DataActivity extends AppCompatActivity {
    Button bt_add;
    EditText et_name, et_price, et_qty;
    DataBaseHelper myDb;
    List<Product> productList = new ArrayList<Product>();
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        bt_add = findViewById(R.id.bt_add);
        et_name = findViewById(R.id.et_name);
        et_price = findViewById(R.id.et_price);
        et_qty = findViewById(R.id.et_qty);
        //lv_itemlist = findViewById(R.id.lv_itemlist);
        
        myDb = new DataBaseHelper(DataActivity.this);
        fillProductList(myDb);
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Product p = new Product();
                try {
                    p.setName(et_name.getText().toString());
                    p.setPrice(Float.parseFloat(et_price.getText().toString()));
                    p.setQuantity(Integer.parseInt(et_qty.getText().toString()));
                } catch (Exception e){
                    Toast.makeText(DataActivity.this,"Exception:"+e,Toast.LENGTH_SHORT).show();
                }
                DataBaseHelper dataBaseHelper = new DataBaseHelper(DataActivity.this);
                dataBaseHelper.addOne(p);

            }
        });
        recyclerView = findViewById(R.id.lv_itemlist);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(DataActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new RecyclerViewAdapter(productList, DataActivity.this);
        recyclerView.setAdapter(mAdapter);


    }
    private void fillProductList(DataBaseHelper myDb) {
        productList.addAll(myDb.getEveryone());
    }
}

它是相应的xml文件:

<?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=".DataActivity">

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="numberDecimal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_name" />

    <EditText
        android:id="@+id/et_qty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_price" />

    <Button
        android:id="@+id/bt_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.189"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_qty" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/lv_itemlist"
        android:layout_width="384dp"
        android:layout_height="456dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/bt_add" />

</androidx.constraintlayout.widget.ConstraintLayout>

我注意到的一件事是你的 mAdapter 是 RecyclerView.Adapter 类型而不是 RecyclerViewAdapter。 我建议您观看大量关于使用回收站视图的视频和文章。 也开始使用 Androids Room 库。 这是使用 SQLite 的推荐方式。 有一个代码实验室,我相信它叫做带视图的房间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM