Android中SQLite数据库增删改查/使用ListView显示数据库内容(有完整源码)

android作业笔记

效果展示

编写SQLite数据库相关操作的代码,实现下图中的功能(第一排按钮布局没有调整屏幕大小适配…不过下面那一排加了 android:layout_weight=“1”)

SQLite展示

一、前言

源码获取

先上源码:https://gitee.com/meng-fanyang/SQLiteWork
在这里插入图片描述
里边有三个分支,对应这不同的写法:

  1. master主分支是写的可以说是最完善的了
  2. nogood_branch分支把该有的功能都实现了,但是代码冗余度较大
  3. AddListView是存有刚能点击全部显示在ListView显示数据
    在这里插入图片描述

实验功能描述

  1. 使用安卓自带的SQLite数据库实现数据的增删改查
  2. 点击添加数据只显示新添加的和连续点击添加的
  3. 全部删除时数据不再显示
  4. 使用ListView控件显示数据

注意事项

  1. 表的主键必须是 == _id == (_id_id_id重要的事情说三遍),具体解释下次更新(我的源码中建表第一次写错了,没有换,请读者自己建立对的表)
  2. 使用了SimpleCursorAdapter来方便数据库和listView之间的数据传递
  3. 代码中很多是注释掉的,有一部分是用来在控制台的Logcat输出的,可以在调试时查看具体情况

实现步骤

创建数据库和数据表的步骤

  1. 新建类继承SQLiteOpenHelper
  2. 实现构造方法
  3. 重写onCreate方法
  4. 重写onUpgrade方法
  5. 实例化SQLiteOpenHelper 的子类对象- MyOpenHelper;
  6. 实现点击事件

二、代码展示

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"

    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名:"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/name"
            android:hint="请输入姓名"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="年龄:"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/age"
            android:hint="请输入年龄"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="身高:"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/height"
            android:hint="请输入身高"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:text="添加数据"
            android:onClick="addData"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:text="全部显示"
            android:onClick="showAll"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:text="清除显示"
            android:onClick="cleanShow"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全部删除"
            android:onClick="deleteAll"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ID:"
            />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18dp"
            android:hint="输入ID"
            android:id="@+id/et_id"
            android:layout_weight="1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:layout_weight="1"
            android:text="ID删除"
            android:onClick="IDDelete"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:layout_weight="1"
            android:text="ID查询"
            android:onClick="IDSearch"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:layout_weight="1"
            android:text="ID更新"
            android:onClick="IDUpdate"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="ID"
            android:textSize="25dp"></TextView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="姓名"
            android:textSize="25dp"></TextView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="年龄"
            android:textSize="25dp"></TextView>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="身高"
            android:textSize="25dp"></TextView>
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/LV">
    </ListView>

</LinearLayout>

MyOpenHelper.java

package com.example.sqlitework;

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

public class MyOpenHelper extends SQLiteOpenHelper {
    //上面的建表建错了,要有下面的这建表,必须主键为_id,_id,_id重要的事情说三遍。这里设置主键_id自增
    private final static String SQL_PERSON_id="create table person_id" +
            "(_id integer primary key autoincrement,name text,age text,height text)";
    //通过调用父类的构造方法完成数据库的创建
    MyOpenHelper(Context context){
        super(context,"Allperson.db",null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //在本方法中完成数据库对象的创建
        sqLiteDatabase.execSQL(SQL_PERSON);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //在本方法中进行数据库的升级操作
    }
}

MainActivity.java

这一步部分太长了,就先不贴全部了,全部的在上边gitee仓库中可以查看

public class MainActivity extends AppCompatActivity {

    //先定义一些全局的,每次都要用的
    private ListView viewById;
    private SimpleCursorAdapter adapter;
//    private Cursor cursor;
    //SimpleCursorAdapter所需要的参数
    String from[] = new String[]{"_id", "name", "age", "height"};
    int[] to = new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age, R.id.tv_height};

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

        MyOpenHelper myOpenHelper = new MyOpenHelper(this);
        //打开数据库
        SQLiteDatabase sqLiteDatabase = myOpenHelper.getReadableDatabase();
        //关闭数据库
        sqLiteDatabase.close();

        viewById = (ListView) findViewById(R.id.LV);
    }

	/**
     * 插入数据
     * @param view
     */
    public void addData(View view){
        Log.d(MainActivity.class.getSimpleName(),"=============接收到插入数据点击==============");
        count = count+1;
        nameText = (EditText) findViewById(R.id.name);
        ageText = (EditText) findViewById(R.id.age);
        heightText = (EditText) findViewById(R.id.height);


        String Name = nameText.getText().toString();
        String Age = ageText.getText().toString();
        String Height = heightText.getText().toString();

        MyOpenHelper myOpenHelper = new MyOpenHelper(this);
        SQLiteDatabase sqLiteDatabase = null;

        try {
            //打开数据库
            sqLiteDatabase = myOpenHelper.getReadableDatabase();
            //开启事务
            sqLiteDatabase.beginTransaction();
            //执行插入操作
            ContentValues contentValues = new ContentValues();
            contentValues.put("name", Name);
            contentValues.put("age", Age);
            contentValues.put("height", Height);
            sqLiteDatabase.insert("person_id",null,contentValues);
            Toast.makeText(this, "Successful insert data", Toast.LENGTH_SHORT).show();

            sqLiteDatabase.setTransactionSuccessful();//提交
            sqLiteDatabase.endTransaction();//关闭事务
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            String limit = String.valueOf(count);
            Cursor cursor = sqLiteDatabase.query("person_id", new String[]{"_id","name","age","height"},null,
                    null,null,null,"_id desc" , limit);
//        db.execSQL("select * from person_id order by _id desc limit 0,i;");  //此处是直接执行SQL语句
            adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
            viewById.setAdapter(adapter);

            if(sqLiteDatabase != null){
                //关闭数据库
                sqLiteDatabase.close();
            }
        }
    }
    

List_item.xml

这是用来分列展示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="list_item"
        android:gravity="center"
        android:layout_weight="1"></TextView>
    <TextView
        android:id="@+id/tv_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="list_item"
        android:gravity="center"
        android:layout_weight="1"></TextView>
    <TextView
        android:id="@+id/tv_age"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="list_item"
        android:gravity="center"
        android:layout_weight="1"></TextView>
    <TextView
        android:id="@+id/tv_height"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="list_item"
        android:gravity="center"
        android:layout_weight="1"></TextView>
</LinearLayout>

三、(补充)ListView实现数据列表显示

要将数据库中的数据列表显示在屏幕上,我们要使用ListView这个控件,当用户从数据库中取出数据时,要将数据绑定到显示控件上,如何绑定呢,我们需要创建适配器进行绑定,创建适配器有两种方式:
第一种是用SimpleAdapter创建(要求绑定的数据是List<HashMap<String, Object>>数据类型)
第二种是用SimpleCursorAdapter创建(要求绑定的数据是Cursor数据类型)
注意:使用第二种方式在获取数据集合时必须指定主键"_id"
Android采用ListView实现数据列表显示

参考文章:
Android开发使用SQLite数据库和Listview实现数据的存储与展示
Android创建SQLite数据库和表
android中sqlite数据库的基本使用和添加多张表
Android——ListView与数据库的结合

  • 9
    点赞
  • 96
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值