Android开发使用SQLite数据库和Listview实现数据的存储与展示

news/2024/7/6 6:34:40

Android开发使用SQLite数据库和Listview实现数据的存储与展示

实现效果:
在这里插入图片描述
使用了SimpleCursorAdapter方便数据库和listview之间的数据传递。

MainActivity.java:

package com.henu.saveindatabase;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ListView viewById;
    private MyHelper myHelper;
    private SimpleCursorAdapter adapter;
    private Cursor cursor;
    //SimpleCursorAdapter所需要的参数
    String from[] = new String[]{"_id", "name", "age"};
    int[] to = new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHelper = new MyHelper(this);
        viewById = (ListView) findViewById(R.id.lv);
        //进入程序时显示数据库中的数据
        Show();
    }

    public void save(View v) {
        //获得可读写数据库对象
        SQLiteDatabase db = myHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        EditText et_name = (EditText) findViewById(R.id.et_name);
        EditText et_age = (EditText) findViewById(R.id.et_age);
        values.put("name", et_name.getText().toString().trim());
        values.put("age", et_age.getText().toString());
        long q = db.insert("information", "name", values);
        Toast.makeText(this, "数据存入成功", Toast.LENGTH_SHORT).show();
        //数据库发生变化时更新listview
        cursor.requery();
        adapter.notifyDataSetChanged();
        db.close();
    }


    /*
       当SQLite数据库中包含自增列时,会自动建立一个名为 sqlite_sequence 的表。

这个表包含两个列:name和seq。name记录自增列所在的表,seq记录当前序号(下一条记录的编号就是当前序号加1)。

如果想把某个自增列的序号归零,只需要修改 sqlite_sequence表就可以了。
        */
    public void clear(View v) {
        SQLiteDatabase db = myHelper.getWritableDatabase();
        db.delete("information", null, null);
        //使自增的_id归零
        db.delete("sqlite_sequence", null, null);
        Toast.makeText(this, "数据库清除成功", Toast.LENGTH_SHORT).show();
        cursor.requery();
        adapter.notifyDataSetChanged();
        db.close();
    }

    //显示数据
    public void Show() {
        SQLiteDatabase db = myHelper.getWritableDatabase();
        cursor = db.query("information", null, null, null, null, null, null);
        adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        viewById.setAdapter(adapter);
        db.close();
    }
}

MyHelper.java:

package com.henu.saveindatabase;

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

import androidx.annotation.Nullable;

public class MyHelper extends SQLiteOpenHelper {

    public MyHelper(Context context) {
        super(context, "content.db", null, 1);
    }
//数据库第一次创建的时候执行

    @Override
    public void onCreate(SQLiteDatabase db) {
        //注意自增的主键名字必须是:_id
        db.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(20),age varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

activity_main.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="match_parent"

    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:ignore="MissingConstraints">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            tools:ignore="MissingConstraints">

            <TextView
                android:id="@+id/tv_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="姓名:"
                android:textSize="35dp"></TextView>

            <EditText
                android:id="@+id/et_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入姓名"
                android:textSize="25dp"></EditText>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            tools:ignore="MissingConstraints">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年龄:"
                android:textSize="35dp"></TextView>

            <EditText
                android:id="@+id/et_age"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入年龄"
                android:textSize="25dp"></EditText>
        </LinearLayout>

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

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="存入"
                android:onClick="save"
                android:textSize="25dp"></Button>

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="清空数据库"
                android:onClick="clear"
                android:textSize="25dp"></Button>
        </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="35dp"></TextView>

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

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

        <ListView
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            tools:ignore="MissingConstraints"></ListView>
    </LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

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="35dp"
    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="35dp"
        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="35dp"
        android:text="list_item"
        android:gravity="center"
        android:layout_weight="1"></TextView>
</LinearLayout>

需要注意的一点是使用SimpleCursorAdapter适配器必须要有个自增的主键,而且名字必须是“_id”,名字必须是“_id”,名字必须是“_id”


http://www.niftyadmin.cn/n/3649779.html

相关文章

js更改css属性_CSS会更改属性:何时以及何时不使用它

js更改css属性The will-change CSS property is commonly misunderstood or not used correctly, in this short post I will demystify the property so you can make your CSS animations and transitions as performant as possible. will-change CSS属性通常被误解或使用不…

在不断地试错中调整向前

在不断地试错中调整向前郑昀 20060619 几个月前的这两篇文章《Web2.0创业&#xff1a;程序员的创业&#xff1f; - 玩火者的自白 - 邱致中的IT博客》和《Web2.0创业&#xff1a;需要什么样的团队》说的模模糊糊&#xff0c;我们看得也是懵懵懂懂。本来许多事情就是要在不断地…

contentProviderSample实现操作数据库

contentProviderSample实现操作数据库并显示在listview控件中。 实现效果和上个实验相同&#xff1a; 点击进入上个实验 本实验在上个实验基础上完成&#xff0c;与上个实验包名略有不同&#xff0c;并且添加了ContentProvider.java文件、修改了MainActivity.java的代码。 Con…

node.js入门_Node.js中的压缩入门

node.js入门Compression in Node.js and Express decreases the downloadable amount of data that’s served to users. Through the use of this compression, we can improve the performance of our Node.js applications as our payload size is reduced drastically. Nod…

跨域或者Internet访问Remoting[Remoting FAQ]

[Remoting FAQ]跨域或者Internet访问RemotingVersionDateCreatorDescription1.0.0.12006-6-1郑昀Ultrapower草稿继续阅读之前&#xff0c;我们假设您熟悉以下知识&#xff1a;n Remoting[需求]虽然说&#xff0c;Remoting一般都在同一个域内调用&#xff0c;但有时候&a…

Android自定义广播接收

Android自定义广播接收 实现效果&#xff1a; MainActivity.java代码&#xff1a; package com.henu.broadcastsample;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; im…

flutter顶部小部件_使用VoidCallback和Function(x)与Flutter进行小部件通信

flutter顶部小部件In this article we’re going to investigate how we can use callback-style events to communicate between widgets with Flutter. 在本文中&#xff0c;我们将研究如何使用Flutter在回调控件之间使用回调风格的事件进行通信。 Why is this important? …

[MSN谈话]专注、口碑和猎头

[网友]: 我原先做.NET WAP的&#xff0c;你的工作是做哪方面的我: 我什么都作。[网友]: 我觉得我做的算多的了&#xff0c;一看才知道&#xff0c;小巫见大巫了我: 移动增值领域我基本都涉及过。[网友]: 我从网络安全到对日外包&#xff0c;再到asp php网站开发之后.NET wap开发…