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与数据库的结合

### 回答1: Android Studio使用SQLite数据库进行增删改查的步骤如下: 1. 创建数据库Android Studio,可以使用SQLiteOpenHelper类来创建和管理数据库。首先,需要创建一个继承自SQLiteOpenHelper的类,并实现onCreate()和onUpgrade()方法。在onCreate()方法,可以创建数据库表和初始化数据。 2. 插入数据 使用ContentValues类来存储要插入的数据,然后使用insert()方法将数据插入到数据库。 3. 查询数据 使用query()方法查询数据库数据,可以指定查询条件、排序方式等参数。查询结果会返回一个Cursor对象,可以通过Cursor对象遍历查询结果。 4. 更新数据 使用ContentValues类来存储要更新的数据,然后使用update()方法将数据更新到数据库。 5. 删除数据 使用delete()方法删除数据库数据,可以指定删除条件。 以上就是Android Studio使用SQLite数据库进行增删改查的基本步骤。 ### 回答2: SQLiteAndroid Studio内置的轻量级关系型数据库。 它在应用程序被广泛使用,可以轻松地进行数据位置的插入、更新、删除和查询。下面将对如何在Android Studio增删改查SQLite数据库进行详细介绍。 1. 创建数据库Android Studio,打开新的“Android项目”并在后台打开SQLite数据库。 首先需要在该项目的build.gradle文件添加以下代码: ```java implementation 'com.android.support:support-sqlite:28.0.0' ``` 随后,我们建立一个新类,并在该类创建由SQLiteOpenHelper扩展而来的helper类。 这可以通过从SQLiteOpenHelper创建一个适当的构造函数,并覆盖其onCreate()和onUpgrade()方法来完成。完成后,在主要应用程序实例化helper。 2. 增加数据 要添加新数据,请创建一个行对象,然后可以使用该表的insert()方法将其插入到数据库。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", “John Smith”); contentValues.put("age", 23); db.insert(“mytable”, null, contentValues); ``` 其mytable是表名,name和age是表列名。 3. 更新数据 要更新数据,请使用Table的update()方法。要更新给定行的具体数据,请使用ContentValues对象,该对象可以使用put()方法来指定一个新值。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("age", 25); db.update(“tablename”, contentValues, “id=4”, null); ``` 这将会把id值为4的行的年龄值更新为25。 4. 删除数据 要删除数据,请使用Table的delete()方法。这个方法需要一个SQL语句作为参数。例如,如果要删除表的一个特定行,请使用以下代码: ```java SQLiteDatabase db = this.getWritableDatabase(); db.delete(“mytable”, “id=2”, null); ``` 这将删除表mytableid为2的行。 5. 查询数据 要查询数据,请使用query()方法。该方法需要传入一个表名、要返回的列和一些可选的where、group by和having语句的参数。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.query(“mytable”, new String[]{“id”, “name”, “age”}, null, null, null, null, null); ``` 这会查询mytable表的id、name和age列,并将结果存储在Cursor对象cursor。 以上是关于如何在Android Studio增删改查SQLite数据库的简要介绍,这个过程还可以通过使用ORM类库等其他方法来简化。 但是,以上方法是SQLite基础部分较为重要的部分。如有不懂之处,可以查看Android Studio SQLite官方文档进行更全面的了解。 ### 回答3: 在 Android Studio ,开发者可以使用 SQLite 数据库来存储和管理应用程序数据SQLite 是一种轻量级的关系型数据库,它非常适合于移动应用程序的存储需求。在本文,我们将介绍如何使用 Android Studio 来完成 SQLite 数据库增删改查操作。 首先,我们需要在 Android Studio 创建一个新的 Android 项目。在项目创建的过程,需要设置应用程序的名称、包名和所支持的最低 API 级别等信息。之后,我们需要创建一个新的数据库表,表包含应用程序需要存储的数据。 我们可以使用 SQLiteOpenHelper 类来创建和管理数据库SQLiteOpenHelper 类提供了一些方法来帮助我们处理 SQLite 数据库的创建和更新。在创建一个 SQLiteOpenHelper 对象时,我们需要提供数据库名称、版本号和表的结构。 接下来,我们将介绍如何使用 SQLiteDatabase 类来完成增删改查操作。SQLiteDatabase 类提供了一些方法来帮助我们对数据库进行操作。 1. 增加数据 使用 insert() 方法可以向数据库插入一行数据。insert() 方法需要传入表名、要插入的数据和一个选项参数。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "Tom"); values.put("age", 18); db.insert("students", null, values); 2. 删除数据 使用 delete() 方法可以从数据库删除一行或多行数据。delete() 方法需要传入表名和一个选择字符串来限制删除范围。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete("students", "name=?", new String[]{"Tom"}); 3. 修改数据 使用 update() 方法可以修改数据库的一行或多行数据。update() 方法需要传入表名、要修改的数据和一个选择字符串来限制修改范围。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("age", 20); db.update("students", values, "name=?", new String[]{"Tom"}); 4. 查询数据 使用 query() 方法可以从数据库查询一行或多行数据。query() 方法需要传入表名、要查询的列、一个选择字符串和一个排序字符串。以下是一个示例: SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query("students", new String[]{"name", "age"}, "age=?", new String[]{"20"}, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d(TAG, "name:" + name + ", age:" + age); } cursor.close(); } 在使用 SQLite 数据库过程,我们需要注意一些事项。比如,我们需要保证数据库的打开和关闭操作是成对出现的,以避免资源的浪费;我们还需要注意表名、列名和选择字符串等信息的正确性,否则会导致数据操作失败。此外,还应该使用事务来保证数据库操作的正确性和一致性。 总之,使用 Android Studio 的 SQLite 数据库功能可以帮助我们方便地管理应用程序数据。通过学习 SQLite 数据库增删改查操作,我们可以更好地开发出高质量、稳定性的移动应用程序。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值