Demo——SQLite数据库

Demo——SQLite数据库,第1张

目录
  • Product
  • MainActivity
  • MySQLiteOpenHelper
  • activity_main.xml
  • item_list.xml
  • update_dialog.xml

不积跬步,无以至千里;不积小流,无以成江海。要沉下心来,诗和远方的路费真的很贵!

Product
package com.hnucm.androiddatabase.model;


public class Product {
    public int id;
    public String name;
    public double singleprice;
    public int restnum;

    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 double getSingleprice() {
        return singleprice;
    }

    public void setSingleprice(double singleprice) {
        this.singleprice = singleprice;
    }

    public int getRestnum() {
        return restnum;
    }

    public void setRestnum(int restnum) {
        this.restnum = restnum;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", singleprice=" + singleprice +
                ", restnum=" + restnum +
                '}';
    }
}
MainActivity
package com.hnucm.androiddatabase;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.hnucm.androiddatabase.model.Product;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //声明增加数据需要的三个输入框
    EditText mEditName;
    EditText mEditPrice;
    EditText mEditNum;
    //声明查询条件输入框
    EditText mEditSearch;
    //声明增查的按钮
    Button mAddBtn;
    Button mSelectBtn;
    //声明驱动
    MySQLiteOpenHelper mySQLiteOpenHelper;
    //声明数据库
    SQLiteDatabase sqLiteDatabase;
    //声明并且初始化显示在界面上的数据对象
    ArrayList<Product> mProductList = new ArrayList<>();
    //在界面上显示数据的控件
    RecyclerView recyclerView;
    //声明适配器
    MyAdapter myAdapter;


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

        //加载驱动,product数据库,products表
        mySQLiteOpenHelper = new MySQLiteOpenHelper(MainActivity.this,
                "product", null, 1);
        //得到数据库
        sqLiteDatabase = mySQLiteOpenHelper.getWritableDatabase();

        //初始化控件
        mSelectBtn = findViewById(R.id.select);
        mAddBtn = findViewById(R.id.insert);
        mEditName = findViewById(R.id.name);
        mEditPrice = findViewById(R.id.singleprice);
        mEditNum = findViewById(R.id.restnum);
        mEditSearch = findViewById(R.id.search);
        recyclerView = findViewById(R.id.recyclerView);

        //点击按钮
        mAddBtn.setOnClickListener(this);
        mSelectBtn.setOnClickListener(this);

        //构造数据
        SelectAllInfo();
        //适配器设置,加入到recyclerview中
        myAdapter = new MyAdapter();
        recyclerView.setAdapter(myAdapter);
        //设置显示样式
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
    }

    //四个按钮的点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //增加数据
            case R.id.insert:
                //数据库中增加
                //创建数据,使用ContentValues -> HashMap  构造数据对象
                ContentValues contentValues = new ContentValues();
                //自增长  主键  增加无需加入id
                //contentValues.put("id",1);
                contentValues.put("name", mEditName.getText().toString());
                contentValues.put("singleprice", mEditPrice.getText().toString());
                contentValues.put("restnum", mEditNum.getText().toString());
                //将创建好的数据对象加入数据库中的哪一个表
                //返回新建数据的id
                long id = sqLiteDatabase.insert("products", null, contentValues);
                //界面上增加
                Product product = new Product();
                //id为返回的id
                product.id = (int) id;
                product.name = mEditName.getText().toString();
                product.singleprice = Double.parseDouble(mEditPrice.getText().toString());
                product.restnum = Integer.parseInt(mEditNum.getText().toString());
                //链表中加入新增数据
                mProductList.add(product);
                //显示在界面上,刷新
                myAdapter.notifyDataSetChanged();
                break;
            //查询数据
            case R.id.select:
                //先清空界面上已存在的数据
                //界面清空,数据库中内容不变
                mProductList.clear();
                //得到查询条件,%实现模糊查询
                String flag = "%" + mEditSearch.getText().toString() + "%";
                //从数据库中查找数据
                //可能不止一条,使用游标遍历逐条加入list显示
                //表名   null   查询条件   条件参数    null    null    null
                if (flag.equals("")) {
                    SelectAllInfo();
                    myAdapter.notifyDataSetChanged();
                } else {
                    Cursor cursor = sqLiteDatabase.query("products", null,
                            "name like ?", new String[]{flag}, null, null, null);
                    while (cursor.moveToNext()) {
                        Product product1 = new Product();
                        //根据索引,幅值
                        product1.id = cursor.getInt(0);
                        product1.name = cursor.getString(1);
                        product1.singleprice = cursor.getDouble(2);
                        product1.restnum = cursor.getInt(3);
                        //显示查询到的数据
                        mProductList.add(product1);
                    }
                    //显示界面
                    myAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    //适配器
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //绑定view,在view中加入适配器
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_list, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            //控件中绑定数据
            //得到当前position的数据对象
            Product product = mProductList.get(position);
            //对象值传入,显示在文本控件上
            holder.showId.setText("商品编号:" + product.getId());
            holder.showName.setText("商品名称:" + product.getName());
            holder.showPrice.setText("商品价格:" + product.getSingleprice());
            holder.showNum.setText("商品数量:" + product.getRestnum());
            //删除按钮监听事件
            holder.delBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //数据库中删除数据
                    //表名  删除条件id  当前这条信息的id  int型加""转为String类型
                    sqLiteDatabase.delete("products", "id=?", new String[]{product.id + ""});
                    //界面上删除
                    //list中的每一条数据类型为Product,遍历,命名为p
                    for (Product p : mProductList) {
                        //如果遍历到的数据的id等于要删除的数据id
                        if (p.id == product.id) {
                            //将这条数据从list中移除
                            mProductList.remove(p);
                            //跳出循环
                            break;
                        }
                    }
                    //更新适配器
                    myAdapter.notifyDataSetChanged();
                }
            });
            //修改按钮监听事件
            holder.updateBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //显示d出框
                    showDialog(product);
                }
            });
        }

        @Override
        public int getItemCount() {
            //返回总的数据数量
            return mProductList.size();
        }
    }

    //控件缓存器
    public class MyViewHolder extends RecyclerView.ViewHolder {
        //声明四个显示文本
        TextView showId;
        TextView showName;
        TextView showPrice;
        TextView showNum;
        //定义删除,修改按钮
        Button delBtn;
        Button updateBtn;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            //缓存控件
            showId = itemView.findViewById(R.id.ProductId);
            showName = itemView.findViewById(R.id.ProductName);
            showPrice = itemView.findViewById(R.id.ProductPrice);
            showNum = itemView.findViewById(R.id.ProductNum);
            delBtn = itemView.findViewById(R.id.delete);
            updateBtn = itemView.findViewById(R.id.update);
        }
    }

    //查询所有数据并显示在界面上
    public void SelectAllInfo() {
        //构造数据,从数据库中查找已存在的信息
        Cursor cursor = sqLiteDatabase.query("products", null, null, null,
                null, null, null);
        //游标遍历查询
        while (cursor.moveToNext()) {
            Product product = new Product();
            product.id = cursor.getInt(0);
            product.name = cursor.getString(1);
            product.singleprice = cursor.getDouble(2);
            product.restnum = cursor.getInt(3);
            mProductList.add(product);
        }
    }

    //显示d框,并且修改数据
    public void showDialog(Product product){
        //创建d出框实例
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //设置图标
        builder.setIcon(R.drawable.update);
        //设置标题
        builder.setTitle("修改商品信息");
        //通过LayoutInflater来加载一个xml的自定义布局
        View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.update_dialog,null);
        //加入自定义布局
        builder.setView(view1);
        //获得四个输入框对象,方便修改
        EditText dialogEdit_id = view1.findViewById(R.id.dialogEdit_id);
        EditText dialogEdit_name = view1.findViewById(R.id.dialogEdit_name);
        EditText dialogEdit_price = view1.findViewById(R.id.dialogEdit_price);
        EditText dialogEdit_num = view1.findViewById(R.id.dialogEdit_num);
        //实现点击带过来数据
        dialogEdit_id.setText(product.id + "");
        dialogEdit_name.setText(product.name);
        dialogEdit_price.setText(product.singleprice + "");
        dialogEdit_num.setText(product.restnum + "");
        //设置保存按钮并加入点击事件
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //将修改后的数据构造为数据对象
                ContentValues contentValues = new ContentValues();
                //放入修改后的数据
                contentValues.put("name",dialogEdit_name.getText().toString());
                contentValues.put("singleprice",dialogEdit_price.getText().toString());
                contentValues.put("restnum",dialogEdit_num.getText().toString());
                //数据库中修改,编号固定不变,编号作为修改索引
                sqLiteDatabase.update("products",contentValues,
                        "id=?",new String[]{dialogEdit_id.getText().toString()});
                //点击保存会自动返回,数据库已修改,界面修改
                //直接刷新适配器,没用,已尝试
                for(Product p:mProductList){
                    //找到id
                    if(p.id == product.id){
                        //更新数据
                        p.name = dialogEdit_name.getText().toString();
                        p.singleprice = Double.parseDouble(dialogEdit_price.getText().toString());
                        p.restnum = Integer.parseInt(dialogEdit_num.getText().toString());
                        //必定只有一条,找到就跳出循环
                        break;
                    }
                }
                //更新界面
                myAdapter.notifyDataSetChanged();
            }
        });
        //设置取消按钮并加入点击事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //不需要逻辑,取消按钮自带取消逻辑
            }
        });
        //显示d出框
        builder.show();
    }
}
MySQLiteOpenHelper
package com.hnucm.androiddatabase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

//加载数据库驱动
//建立连接
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    //构造方法
    //name -> 数据库名字
    public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //建表
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //建表语句   自增长  主键
        String sql = "create table products(id integer primary key autoincrement," +
                "name varchar(20),singleprice double,restnum integer) ";
        sqLiteDatabase.execSQL(sql);
    }

    //更新表
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
activity_main.xml

<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">

    <EditText
        android:id="@+id/name"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:background="#ffffff"
        android:hint="请输入物品名字"
        android:textSize="23sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/singleprice"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:background="#ffffff"
        android:hint="请输入物品单价"
        android:textSize="23sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <EditText
        android:id="@+id/restnum"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:background="#ffffff"
        android:hint="请输入物品剩余库存量"
        android:textSize="23sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/singleprice" />

    <EditText
        android:id="@+id/search"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:background="#ffffff"
        android:hint="输入要查询商品的名称"
        android:textSize="23sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/restnum" />

    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="44dp"
        android:layout_marginLeft="44dp"
        android:layout_marginTop="16dp"
        android:text="增加商品"
        android:textSize="25sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/search" />

    <Button
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:text="查询商品"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="@+id/insert"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/insert"
        app:layout_constraintTop_toTopOf="@+id/insert" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/insert" />

androidx.constraintlayout.widget.ConstraintLayout>
item_list.xml

<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="wrap_content">

    <TextView
        android:id="@+id/ProductId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:text="商品编号:"
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/ProductName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="商品名称:"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="@+id/ProductId"
        app:layout_constraintStart_toStartOf="@+id/ProductId"
        app:layout_constraintTop_toBottomOf="@+id/ProductId" />

    <TextView
        android:id="@+id/ProductPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="商品价格:"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="@+id/ProductName"
        app:layout_constraintStart_toStartOf="@+id/ProductName"
        app:layout_constraintTop_toBottomOf="@+id/ProductName" />

    <TextView
        android:id="@+id/ProductNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="商品数量:"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="@+id/ProductPrice"
        app:layout_constraintStart_toStartOf="@+id/ProductPrice"
        app:layout_constraintTop_toBottomOf="@+id/ProductPrice" />

    <Button
        android:id="@+id/update"
        android:layout_width="80dp"
        android:layout_height="45dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="修改数据"
        app:layout_constraintBottom_toBottomOf="@+id/ProductId"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/ProductId" />

    <Button
        android:id="@+id/delete"
        android:layout_width="80dp"
        android:layout_height="45dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="删除数据"
        app:layout_constraintBottom_toBottomOf="@+id/ProductNum"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/ProductNum" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000000"
        app:layout_constraintTop_toBottomOf="@+id/delete"
        tools:layout_editor_absoluteX="0dp" />

androidx.constraintlayout.widget.ConstraintLayout>
update_dialog.xml

<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">

    <TextView
        android:id="@+id/dialog_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="商品编号:"
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/dialogEdit_id"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:hint="输入要修改的id"
        android:enabled="false"
        android:background="#ffffff"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="@+id/dialog_id"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/dialog_id"
        app:layout_constraintTop_toTopOf="@+id/dialog_id" />

    <TextView
        android:id="@+id/dialog_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="商品名称:"
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_id" />

    <EditText
        android:id="@+id/dialogEdit_name"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:hint="输入要修改的名称"
        android:background="#ffffff"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="@+id/dialog_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/dialog_name"
        app:layout_constraintTop_toTopOf="@+id/dialog_name" />

    <TextView
        android:id="@+id/dialog_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="商品价格:"
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_name" />

    <EditText
        android:id="@+id/dialogEdit_price"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:hint="输入要修改的价格"
        android:background="#ffffff"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="@+id/dialog_price"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/dialog_price"
        app:layout_constraintTop_toTopOf="@+id/dialog_price" />

    <TextView
        android:id="@+id/dialog_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:text="商品数量:"
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_price" />

    <EditText
        android:id="@+id/dialogEdit_num"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:hint="输入要修改的库存"
        android:background="#ffffff"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="@+id/dialog_num"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/dialog_num"
        app:layout_constraintTop_toTopOf="@+id/dialog_num" />
androidx.constraintlayout.widget.ConstraintLayout>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/877028.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存