Android数据库—SQLite


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

Android数据库—SQLite

  • 不适合存储大规模数据
  • 用来存储每一个用户各自的信息

在线查看数据库方法

Android Studio查看SQLite数据库方法大全

从前我使用的是stetho方法来查看数据库,因为是外国网站,所以需要翻墙,比较麻烦。

如今最新版的Android Studio可以直接在里面查看数据库,无需别的了。

  • stetho使用

    • build.gradle文件中引入依赖
      implementation 'com.facebook.stetho:stetho:1.5.1'
    
    • 在需要操作数据库的Activity中加入以下语句
    Stetho.initializeWithDefaults(this);
    
    • 谷歌调试

继承SQLiteOpenHelper的类,加载驱动

继承SQLiteOpenHelper类,实现三个方法。

  • 构造函数
  • 建表方法:onCreate方法
  • 更新表方法:onUpgrade方法
  • 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) {
        //建表语句   自增长  主键
        sqLiteDatabase.execSQL("create table products(id integer primary key autoincrement,name varchar(20),singleprice double,restnum integer) ");
    }

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

    }
}

在Activity中进行增删改查

整个Activity都是用数据库,所以声明驱动和数据库为全局变量,方便使用。

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

布局文件中设置四个按钮,进行增删改查操作。

  • 布局-------activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="增加一条商品信息"
        android:textSize="25sp"
        />

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除一条商品信息"
        android:textSize="25sp"
        />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改一条商品信息"
        android:textSize="25sp"
        />

    <Button
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询一条商品信息"
        android:textSize="25sp"
        />

</LinearLayout>
  • 总体逻辑代码-------MainActivity
package com.hnucm.androiddatabase;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //声明增删改查四个按钮
    Button addBtn;
    Button delBtn;
    Button updateBtn;
    Button selectBtn;
    //声明驱动
    MySQLiteOpenHelper mySQLiteOpenHelper;
    //声明数据库
    SQLiteDatabase sqLiteDatabase;
    //数据对象
    ContentValues contentValues;
    //增删改查条件变量
    String id;
    String name;

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

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

        //初始化四个按钮
        addBtn = findViewById(R.id.insert);
        delBtn = findViewById(R.id.delete);
        updateBtn = findViewById(R.id.update);
        selectBtn = findViewById(R.id.select);

        //点击四个按钮
        addBtn.setOnClickListener(this);
        delBtn.setOnClickListener(this);
        updateBtn.setOnClickListener(this);
        selectBtn.setOnClickListener(this);
    }

    //四个按钮的点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //增加数据
            case R.id.insert:
                //创建数据,使用ContentValues -> HashMap
                contentValues = new ContentValues();
                //自增长  主键  增加无需加入id
                //contentValues.put("id",1);
                contentValues.put("name","辣条");
                contentValues.put("singleprice",3.50);
                contentValues.put("restnum",12);
                //将创建好的数据对象加入数据库中的哪一个表
                sqLiteDatabase.insert("products",null,contentValues);
                break;
            //删除数据
            case R.id.delete:
                //删除条件
                id = "1";
                name = "辣条";
                //在哪张表里,根据条件删除
                sqLiteDatabase.delete("products","id = ? and name = ?",
                        new String[]{id,name});
                break;
            //修改数据
            case R.id.update:
                //修改条件
                id = "2";
                //将满足条件的数据修改
                contentValues = new ContentValues();
                contentValues.put("name","薯片");
                //在数据库中修改
                sqLiteDatabase.update("products",contentValues,"id=?",
                        new String[]{id});
                break;
            //查询所有数据
            case R.id.select:
                //采用cursor游标查询
                Cursor cursor = sqLiteDatabase.query("products",null,null,
                        null,null,null,null);
                //游标下一个存在,即没有到最后
                while(cursor.moveToNext()){
                    //每一条数据取出每一列
                    int id = cursor.getInt(cursor.getColumnIndex("id"));
                    name = cursor.getString(cursor.getColumnIndex("name"));
                    double singleprice = cursor.getDouble(cursor.getColumnIndex("singleprice"));
                    int restnum = cursor.getInt(cursor.getColumnIndex("restnum"));
                    //打印数据
                    Log.i("products","id:" + id + ",name:" + name + ",singleprice:"
                            + singleprice + ",restnum:" + restnum);
                }
                break;
        }
    }
}

增加数据

//创建数据,使用ContentValues -> HashMap
                contentValues = new ContentValues();
                //自增长  主键  增加无需加入id
                //contentValues.put("id",1);
                contentValues.put("name","辣条");
                contentValues.put("singleprice",3.50);
                contentValues.put("restnum",12);
                //将创建好的数据对象加入数据库中的哪一个表
                sqLiteDatabase.insert("products",null,contentValues);

删除数据

//删除条件
                id = "1";
                name = "辣条";
                //在哪张表里,根据条件删除
                sqLiteDatabase.delete("products","id = ? and name = ?",
                        new String[]{id,name});

修改数据

//修改条件
                id = "2";
                //将满足条件的数据修改
                contentValues = new ContentValues();
                contentValues.put("name","薯片");
                //在数据库中修改
                sqLiteDatabase.update("products",contentValues,"id=?",
                        new String[]{id});

查询数据

//采用cursor游标查询
                //没有查询条件,所以查询表中所有信息
                Cursor cursor = sqLiteDatabase.query("products",null,null,
                        null,null,null,null);
                //游标下一个存在,即没有到最后
                while(cursor.moveToNext()){
                    //每一条数据取出每一列
                    int id = cursor.getInt(cursor.getColumnIndex("id"));
                    name = cursor.getString(cursor.getColumnIndex("name"));
                    double singleprice = cursor.getDouble(cursor.getColumnIndex("singleprice"));
                    int restnum = cursor.getInt(cursor.getColumnIndex("restnum"));
                    //打印数据
                    Log.i("products","id:" + id + ",name:" + name + ",singleprice:"
                            + singleprice + ",restnum:" + restnum);
         }

在界面上进行增删改查

增加数据

  • 采用RecyclerView来显示数据

     <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" />
    
  • 采用三个输入框输入新增数据的信息(由于id自增长,无需输入)

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

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

    <EditText
        android:id="@+id/restnum"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:background="#ffffff"
        android:textSize="23sp"
        android:hint="请输入物品剩余库存量"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/singleprice" />
  • RecyclerView里面每条数据的显示样式
    • item_list.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="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/deleteBtn"
        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/deleteBtn"
        tools:layout_editor_absoluteX="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • 创建需要显示的数据对象

    • Product.class
    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 +
                    '}';
        }
    }
    
  • 使用控件缓存,缓存适配器每条数据中需要的控件

//控件缓存器
    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.deleteBtn);
        }
    }
  • 使用适配器,使每条数据格式一样,显示在RecyclerView中
/适配器
    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());
        }

        @Override
        public int getItemCount() {
            //返回总的数据数量
            return mProductList.size();
        }
    }
  • 声明增加按钮,三个输入框
//声明增加数据需要的三个输入框
    EditText mEditName;
    EditText mEditPrice;
    EditText mEditNum;
    //声明增删改查的按钮
    Button mAddBtn;
  • 声明显示数据的控件RecyclerView,显示的数据类型Product以及适配器
//声明并且初始化显示在界面上的数据对象
    ArrayList<Product> mProductList = new ArrayList<>();
    //在界面上显示数据的控件
    RecyclerView recyclerView;
    //声明适配器
    MyAdapter myAdapter;
  • 初始化控件(适配器不是控件,是一个类)
//初始化控件
        mAddBtn = findViewById(R.id.insert);
        mEditName = findViewById(R.id.name);
        mEditPrice = findViewById(R.id.singleprice);
        mEditNum = findViewById(R.id.restnum);
        recyclerView = findViewById(R.id.recyclerView);
  • 新建适配器,将适配器加入到显示控件RecyclerView中并且设置控件的显示样式
  //适配器设置,加入到recyclerview中
        myAdapter = new MyAdapter();
        recyclerView.setAdapter(myAdapter);
        //设置显示样式
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
  • 点击增加按钮,先在数据库中增加数据,后在界面显示出来。
 //增加数据
            case R.id.insert:
                //数据库中增加
                //创建数据,使用ContentValues -> HashMap
                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;

删除数据

  • 首先在界面上显示数据库中存在的数据
//构造数据,从数据库中查找已存在的信息
        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);
        }
  • 删除数据按钮存在于每条数据的显示样式的布局文件中
  • 所以在缓存器中初始化
  • 在适配器中设置点击事件监听器
//删除按钮监听事件
            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();
                }
            });

查询数据

根据id查询
  • 修改布局,增加查询按钮,增加查询输入框
<?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">

    <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="输入要查询商品的id"
        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>
  • 声明控件并且初始化
  //声明查询条件输入框
    EditText mEditSearch;
    //声明增删改查的按钮
    Button mSelectBtn;
 //初始化控件
        mSelectBtn = findViewById(R.id.select);
        mEditSearch = findViewById(R.id.search);
  • 设置点击事件监听器
 //点击按钮
mSelectBtn.setOnClickListener(this);
  • 设置点击事件逻辑实现
//查询数据
            case R.id.select:
                //先清空界面上已存在的数据
                //界面清空,数据库中内容不变
                mProductList.clear();
                //得到查询条件
                String flag = mEditSearch.getText().toString();
                //从数据库中查找数据,可能不止一条,id为条件必定只有一条,id主键
                //可能不止一条,使用游标遍历逐条加入list显示
                //表名   null   查询条件   条件参数    null    null    null
                if (flag.equals("")) {
                    SelectAllInfo();
                    myAdapter.notifyDataSetChanged();
                } else {
                    Cursor cursor = sqLiteDatabase.query("products", null,
                            "id=?", 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;
根据商品名称查询
  • 布局中根据id查询,改为根据商品名查询

  • 都不改,只更改查询条件

//得到查询条件,%实现模糊查询
String flag = "%" + mEditSearch.getText().toString() + "%";

Cursor cursor = sqLiteDatabase.query("products", null,
                            "name like ?", new String[]{flag}, null, null, null);
根据商品单价查询
  • 修改查询条件即可
String flag = mEditSearch.getText().toString();

Cursor cursor = sqLiteDatabase.query("products", null,
                            "singleprice=?", new String[]{flag}, null, null, null);
根据商品库存查询
  • 修改查询条件即可
Cursor cursor = sqLiteDatabase.query("products", null,
                            "restnum=?", new String[]{flag}, null, null, null);

修改数据

  • 在适配器布局中加入修改按钮
 <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" />
  • 创建自定义弹出框布局
<?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">

    <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>
  • 在自定义的适配器类中的onBindViewHolder方法中设置修改按钮点击事件
//修改按钮监听事件
            holder.updateBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //显示弹出框
                    showDialog(product);
                }
            });
  • 总弹出框显示方法
 //显示弹框,并且修改数据
    public void showDialog(Product product){
        //创建弹出框实例
        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) {
                //不需要逻辑,取消按钮自带取消逻辑
            }
        });
        //显示弹出框
        builder.show();
    }
  • 弹出框的初始化
//创建弹出框实例
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 + "");
  • 保存按钮的点击逻辑
//将修改后的数据构造为数据对象
                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){
                        //更新数据,更新的是list里面的数据
                        //更新控件,使用SetText方法无效,无法修改界面上数据
                        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.show();
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值