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

news2024/10/2 8:32:59

android作业笔记

文章目录

  • 效果展示
  • 一、前言
    • 源码获取
    • 实验功能描述
    • 注意事项
    • 实现步骤
  • 二、代码展示
    • activity_main.xml布局文件
    • MyOpenHelper.java
    • MainActivity.java
    • List_item.xml
  • 三、(补充)ListView实现数据列表显示

效果展示

编写SQLite数据库相关操作的代码,实现下图中的功能

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/7537.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【附源码】Python计算机毕业设计数据时代下的疫情管理系统

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;…

达梦数据库,数据库重置主键id从1开始

一、前言 今天中国国寿XX项目XC环境达梦遇到id主键自增顺序不对的问题&#xff0c;那么如何修改一个表的自增主键顺序呢&#xff1f;下边通过具体测试案例进行深入分析&#xff0c;通过delete/update/truncate/alter观察数据的变换总结出结论&#xff0c;欢迎各位喜欢达梦数据…

值得推荐的小型 C 语言开源项目:Triggerhappy

这几天在知乎上看到了一个好问题&#xff1a; 有哪些值得推荐的小型 C 语言开源项目&#xff1f; 题主很可能是想要一个这样的开源项目&#xff1a;功能小巧、代码质量高&#xff0c;可读性好&#xff0c;以便自己循序渐进地学习 C 语言。 作为一个嵌入式开发人员&#xff0…

趁年轻,大胆闯

趁年轻&#xff0c;大胆闯如果我是20岁&#xff0c;我会拿出未来的十年&#xff0c;全力已赴的赚钱&#xff0c;折腾&#xff0c;不要任何安全感。 出来创业&#xff0c;就是为100倍以上的赔率来的。

HTTPS

一、HTTPS是什么 HTTPS也是一个应用层协议&#xff0c;是在HTTP协议的基础上引入了一个加密层。 由于HTTP协议内容一般都是本文方式明文传输的&#xff0c;这就导致它在传输过程中会出现被篡改的情况。 经典案例就是万恶的“运营商劫持”&#xff01; 除了运营商可以劫持&a…

如何快速从零开始搭建一个前端项目

2022 年了&#xff0c;如何快速从零开始搭建一个合适的前端项目&#xff1f; 准备工作 首先本地需要安装好 node 环境以及包管理工具&#xff0c;推荐直接使用 pnpm&#xff0c;也可以通过 pnpm 来直接管理 nodejs 版本。 pnpm 安装&#xff1a; # Mac or Linux curl -fsSL…

SpringMVC 环境配置

文章目录引入1、MVC的概念2、Spring MVC基本原理一、导入坐标&#xff08;导包&#xff09;导入Spring MVC所需要的jar包二、新建springmvc-config.xml文件三、配置web.xml四、 创建Controller五、配置SpringMVC配置文件六、配置页面其他引入 Spring Web MVC是一种基于Java的实…

cv算法工程师学习教程

前言一&#xff0c;计算机系统 1.1&#xff0c;计算机系统书籍1.2&#xff0c;设计模式教程 二&#xff0c;编程语言 2.1&#xff0c;C 学习资料2.2&#xff0c;Python 学习资料 三&#xff0c;数据结构与算法 3.1&#xff0c;数据结构与算法课程3.2&#xff0c;算法题解 四&am…

数字信号处理及python实现(三)

数字信号处理及python实现三抽样引起的混叠抽样的频域视图样本重建信号拟合正弦波线性与多项式内插理想低通滤波器这是参考知乎的数字信号处理及matlab实现的python实现版本&#xff0c;参考连接 上一期:数字信号处理及python实现(二) 项目文件结构 test为测试文件&#xff…

【Vue】Vue开发实战之我的笔记(ch18-ch27)--20221115

参考https://blog.csdn.net/yfm120750310/article/details/111353963 18 | 为什么需要Vuex 18.1 为什么需要Vuex provide和inject虽然能够实现层层传递的数据管理&#xff0c;但对于一个大的管理系统而言会显得有些繁琐&#xff0c;我们需要一个大型的状态管理系统。 Vuex不…

甘特图是什么?如何快速搭建?

甘特图是什么&#xff1f; 甘特图是一种条状图&#xff0c;直观展示项目进展随时间的走势及联系。其中&#xff0c;项目时间由横轴表示&#xff0c;项目活动由纵轴表示。整体线条表示整个项目期间内&#xff0c;计划和实际的活动完成情况。甘特图起初用于美国胡佛水坝和美国洲…

cpe(通用平台枚举)命名规范及python CPE库实战

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。喜欢通过博客创作的方式对所学的知识进行总结与归纳,不仅形成深入且独到的理…

一文看懂Linux 页表、大页与透明大页

一、 内存映射与页表 1. 内存映射 我们通常所说的内存容量&#xff0c;指的是物理内存&#xff0c;只有内核才可以直接访问物理内存&#xff0c;进程并不可以。 Linux 内核给每个进程都提供了一个独立的虚拟地址空间&#xff0c;并且这个地址空间是连续的。这样&#xff0c;…

如何用Python 快速搭建HTTP服务器

Python具有语法简单、语句清晰的特点,而且Python的兼容性比较好,可以将其他语言制作的模块联结起来,具有强大且丰富的库,封装后可以轻松调用,因此成为编程语言中的“网红“&#xff0c;甚至被称为非计算机从业者的第一语言。 Python在IT就业市场也是最受欢迎、最热门的技术技能…

SpringBoot整合Redis

SpringBoot整合Redis 文章目录SpringBoot整合Redis一 .简介1. redie是什么&#xff1f;2. redie的使用场景&#xff1f;二 . 使用1. 引入依赖2. 配置文件3. 启动redis4. 创建Redis工具类5. 创建测试类6. 查看效果一 .简介 1. redie是什么&#xff1f; Redis是现在最受欢迎的N…

图解计算机的存储器金字塔

本文已收录到 GitHub AndroidFamily&#xff0c;有 Android 进阶知识体系&#xff0c;欢迎 Star。技术和职场问题&#xff0c;请关注公众号 [彭旭锐] 进 Android 面试交流群。 前言 大家好&#xff0c;我是小彭。 在计算机组成原理中的众多概念中&#xff0c;开发者接触得最…

LeetCode-剑指43-1-n整数中出现1的次数

1、逐位统计 我们统计每一位k上面可能出现1的次数&#xff1a;1、对于每一位k上面的出现的1&#xff0c;我们首先统计其出现(n/10k)10k−1(n/10^k)\times10^{k-1}(n/10k)10k−1次的1&#xff1b;2、考虑到存在余数的情况&#xff0c;我们还需要比较剩余余数中出现1的次数&…

浅谈HTTP缓存与CDN缓存的那点事

HTTP缓存与CDN缓存一直是提升web性能的两大利器&#xff0c;合理的缓存配置可以降低带宽成本、减轻服务器压力、提升用户的体验。而不合理的缓存配置会导致资源界面无法及时更新&#xff0c;从而引发一系列的衍生问题。本文将分别将从HTTP缓存与cdn缓存的规则、流程、配置入手&…

XSS挑战之旅1-10关

文章目录前言第1关第2关第3关第4关第5关第6关第7关第8关第9关第10关前言 漏洞介绍&#xff1a;XSS漏洞 参考文章&#xff1a;XSS挑战之旅 游戏规则&#xff1a;触发alert()弹窗&#xff0c;进入下一关 第1关 进入第一关 随便输入一下&#xff0c;观测输出&#xff0c;看源代…

还在为数据库事务一致性检测而苦恼?让Elle帮帮你,以TDSQL为例我们测测 | DB·洞见#7

数据库用户通常依赖隔离级别来确保数据一致性&#xff0c;但很多数据库却并未达到其所表明的级别。主要原因是&#xff1a;一方面&#xff0c;数据库开发者对各个级别的理解有细微差异&#xff1b;另一方面&#xff0c;实现层面没有达到理论上的要求。 用户在使用或开发者在交…