目录

  • Android数据库—SQLite
    • 在线查看数据库方法
    • 继承SQLiteOpenHelper的类,加载驱动
    • 在Activity中进行增删改查
      • 增加数据
      • 删除数据
      • 修改数据
      • 查询数据
    • 在界面上进行增删改查
      • 增加数据
      • 删除数据
      • 查询数据
        • 根据id查询
        • 根据商品名称查询
        • 根据商品单价查询
        • 根据商品库存查询
      • 修改数据

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

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);}//建表@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {//建表语句   自增长  主键sqLiteDatabase.execSQL("create table products(id integer primary key autoincrement,name varchar(20),singleprice double,restnum integer) ");}//更新表@Overridepublic 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"><Buttonandroid:id="@+id/insert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="增加一条商品信息"android:textSize="25sp"/><Buttonandroid:id="@+id/delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="删除一条商品信息"android:textSize="25sp"/><Buttonandroid:id="@+id/update"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="修改一条商品信息"android:textSize="25sp"/><Buttonandroid: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;@Overrideprotected 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);}//四个按钮的点击事件@Overridepublic void onClick(View view) {switch (view.getId()){//增加数据case R.id.insert://创建数据,使用ContentValues -> HashMapcontentValues = 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 -> HashMapcontentValues = 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.RecyclerViewandroid: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自增长,无需输入)

<EditTextandroid: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" /><EditTextandroid: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" /><EditTextandroid: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.ConstraintLayoutxmlns: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"><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><Buttonandroid: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" /><Viewandroid: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;}@Overridepublic 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@Overridepublic 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;}@Overridepublic 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());}@Overridepublic 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 -> HashMapcontentValues = 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());//将创建好的数据对象加入数据库中的哪一个表//返回新建数据的idlong id = sqLiteDatabase.insert("products", null, contentValues);//界面上增加Product product = new Product();//id为返回的idproduct.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() {@Overridepublic void onClick(View view) {//数据库中删除数据//表名  删除条件id  当前这条信息的id  int型加""转为String类型sqLiteDatabase.delete("products","id=?",new String[]{product.id + ""});//界面上删除//list中的每一条数据类型为Product,遍历,命名为pfor(Product p : mProductList){//如果遍历到的数据的id等于要删除的数据idif(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"><EditTextandroid: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" /><EditTextandroid: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" /><EditTextandroid: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" /><EditTextandroid: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" /><Buttonandroid: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" /><Buttonandroid: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.RecyclerViewandroid: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    nullif (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);

修改数据

  • 在适配器布局中加入修改按钮
 <Buttonandroid: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.ConstraintLayoutxmlns: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"><TextViewandroid: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" /><EditTextandroid: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" /><TextViewandroid: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" /><EditTextandroid: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" /><TextViewandroid: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" /><EditTextandroid: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" /><TextViewandroid: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" /><EditTextandroid: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() {@Overridepublic 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() {@Overridepublic 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){//找到idif(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() {@Overridepublic 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){//找到idif(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();

Android数据库—SQLite相关推荐

  1. 《一》Android 数据库 SQlite SQLiteOpenHelper

    /* 大家都知道写博客会很累的,大热天的. 希望=转载请注明出处:http://blog.csdn.net/ta893115871 请不要可怜你的鼠标,(*^__^*) 嘻嘻-- */ 众所周知,数据 ...

  2. Android 数据库Sqlite的使用(1)

    在Android中,我们使用的数据库是一个轻量级的数据库 sqlite 下面我们来学习一下它的CURD操作 首先 我们需要创建一个类 继承自android自带的一个数据库帮助类SQLiteOpenHe ...

  3. Android 数据库(SQLite)【简介、创建、使用(增删改查、事务、实战演练)、数据显示控件(ListView、Adapter、实战演练-绿豆通讯录)】

    目   录 (壹)SQLite数据库简介 (贰)数据库的创建 (叁)数据库的使用 3.1.SQlite的基本操作 3.1.1.添加数据 3.1.2.修改数据 3.1.3.查询数据 3.1.4.删除数据 ...

  4. Android 数据库 SQLite

    首先关于SQLite的介绍百度上看看就大致了解的差不多了. Android 操作数据库的关键步骤就在于实现API SQLiteOpenHelper,通常这个库辅助类来创建或打开数据库. 废话不多说直接 ...

  5. 《二》Android 数据库 SQlite SQLiteOpenHelper

    /**************************************************** 大家都知道写博客会很累的,大热天的. 希望=转载请注明出处:http://blog.csdn ...

  6. android绿豆通讯录xml,Android 数据库(SQLite)【简介、创建、使用(增删改查、事务、实战演练)、数据显示控件(ListView、Adapter、实战演练)】...

    目   录 (壹)SQLite数据库简介 (贰)数据库的创建 (叁)数据库的使用 3.1.SQlite的基本操作 3.1.1.添加数据 3.1.2.修改数据 3.1.3.查询数据 3.1.4.删除数据 ...

  7. android realm 简书,android 数据库SQLite realm

    一.SQLite android内置了数据库SQLite,这是一款轻量级的关系型数据库,通常只需要几百K的内存.数据库文件存放在/data/data//databases/目录下. 为了方便管理数据库 ...

  8. android 数据库sqlite的使用

    android开发的过程中,不可避免的有需要存储数据的时候. android的数据存取机制有很多,其中最重要的大概就是sqlite数据库了 sqlite 数据库是android自带的数据库.不需要任何 ...

  9. 一篇好文之Android数据库 SQLite全解析

    项目效果地址: SQlite 1. 创建数据库 Android中使用SQlite,需要自己创建库,建表,添加数据!好在Android中提供了SQLiteOpenHelper类来帮助创建使用数据库,我们 ...

最新文章

  1. python实现ssh登录send_Python实现ssh批量登录并执行命令
  2. Discrete Logarithm is a Joke __int128 浮点数e
  3. 移植YAFFS2文件系统到linux3.18.4内核(原)
  4. Django中celery配置总结
  5. Java DataOutputStream writeInt()方法及示例
  6. setInterval
  7. linux通过yum安装vim,linux/centos系统如何使用yum安装vi/vim?
  8. QT中如何实现Thread与GUI的主线程连通
  9. pycharm的debug
  10. 海康威视监控使用html播放
  11. 树莓派安装ros教程
  12. 如何在 Windows 10 上完全禁用 UAC
  13. CCCF“CNCC2017特邀报告”丘成桐:现代几何学与计算机科学
  14. [实战]制作简单的公众号二维码关注图
  15. Druid配置——Ingestion Spec(摄取规范)
  16. MYSQL (关系型数据库管理系统)的基础知识详解
  17. 云骞开源即时通讯软件
  18. java什么算垃圾代码,[把代码写成诗]Java美好的承诺,自动回收垃圾
  19. 3.神经网络-深度学习入门
  20. 桌面上计算机删除后怎么复原,电脑桌面上出现一个图标,删掉后重启桌面又恢复了?怎么才能彻底删除?...

热门文章

  1. RadioGroup和RadioButton,单选框(Android)
  2. 小晶粒zsm分子筛合成表征实验报告_ZSM-5分子筛的合成与表征
  3. 检查 Linux 服务器性能的几个命令
  4. 【后端开发】Reactor 模型详解
  5. Typescript玩转设计模式 之 对象行为型模式(上)
  6. 关于数学计算机手抄报简单的,非常简单的数学手抄报
  7. 我与GPT关于音乐的对话1
  8. 问题一:使用foreach遍历字符串
  9. Kubernetes 实现 Guestbook 留言板
  10. 祖玛游戏(记忆搜索+A*算法)