Android SQLite database add, delete, check and modify (SimpleAdapter binds ListView)

Project directory:
Insert picture description here
DbHelper

package com.example.db_1;

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

public class DbHelper extends SQLiteOpenHelper {
    public static final String TB_NAME = "students";

    //构造方法:第1参数为上下文,第2参数库库名,第3参数为游标工厂,第4参数为版本
    public DbHelper(Context context, String dbname, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, dbname, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table if not exists "+TB_NAME+" (id integer primary key autoincrement,name varchar,age integer)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists "+TB_NAME);
        onCreate(db);
    }
}

MainActivity

package com.example.db_1;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private MyDAO myDAO;
    private ListView listView;
    private List<Map<String, Object>> list;
    private Map<String, Object> item;
    private SimpleAdapter listAdapter;

    private EditText et_name;
    private EditText et_age;
    private String selId = null;

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

        findViewById(R.id.button).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
        findViewById(R.id.button3).setOnClickListener(this);

        et_name = (EditText) findViewById(R.id.editText);
        et_age = (EditText) findViewById(R.id.editText2);

        myDAO = new MyDAO(this);
        if (myDAO.getRecordsNumber() == 0) {  //防止重复运行时重复插入记录
            myDAO.insertInfo("test1", 18);
            myDAO.insertInfo("test2", 21);
        }
        displayRecords();
    }

    //显示记录
    public void displayRecords() {
        listView = (ListView) findViewById(R.id.listView);
        list = new ArrayList<Map<String, Object>>();
        Cursor cursor = myDAO.allQuery();

        //list填充所有记录
        while (cursor.moveToNext()) {
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            String name=cursor.getString(cursor.getColumnIndex("name"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            item = new HashMap<String, Object>();
            item.put("id", id);
            item.put("name", name);
            item.put("age", age);
            list.add(item);
        }
        listAdapter = new SimpleAdapter(this,
                list,
                R.layout.list_1,
                new String[]{"_id", "name", "age"},
                new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age});
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> rec = (Map<String, Object>) listAdapter.getItem(position);
                et_name.setText(rec.get("name").toString());
                et_age.setText(rec.get("age").toString());
                selId = rec.get("id").toString();  //赋值当前选中ListView的id
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (selId != null) {//选中条目时
            String s1 = et_name.getText().toString().trim();
            int s2 = Integer.parseInt(et_age.getText().toString());
            switch (v.getId()) {
                case R.id.button:
                    myDAO.insertInfo(s1, s2);
                    break;
                case R.id.button2:
                    myDAO.updateInfo(s1, s2, selId);
                    Toast.makeText(getApplicationContext(), "Update success!", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.button3:
                    myDAO.deleteInfo(selId);
                    Toast.makeText(getApplicationContext(), "Delete success!", Toast.LENGTH_SHORT).show();
                    et_name.setText(null);
                    et_age.setText(null);
                    selId = null; //不可连续删除
                    break;
            }
        } else {//未选中条目时
            if (v.getId() == R.id.button) {//点击增加记录
                String s1 = et_name.getText().toString().trim();
                String s2 = et_age.getText().toString();
                if (s1.equals("") || s2.equals("")) {
                    Toast.makeText(getApplicationContext(), "Name or age is null!", Toast.LENGTH_SHORT).show();
                } else {
                    myDAO.insertInfo(s1, Integer.parseInt(s2));
                }
            } else {//点击修改,删除记录
                Toast.makeText(getApplicationContext(), "Please click the button first!", Toast.LENGTH_SHORT).show();
            }
        }
        displayRecords();
    }
}

MyDAO

package com.example.db_1;

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

public class MyDAO {
    private SQLiteDatabase myDb;
    private DbHelper dbHelper;

    public MyDAO(Context context) {
        dbHelper = new DbHelper(context, "demo.db", null, 1);
    }

    //查询表所有记录
    public Cursor allQuery() {
        myDb = dbHelper.getReadableDatabase();
        return myDb.rawQuery("select * from " + dbHelper.TB_NAME, null);
    }

    //获取表记录数
    public int getRecordsNumber() {
        myDb = dbHelper.getReadableDatabase();
        Cursor cursor = myDb.rawQuery("select * from " + dbHelper.TB_NAME, null);
        return cursor.getCount();
    }

    //插入记录
    public void insertInfo(String name, int age) {
        myDb = dbHelper.getWritableDatabase();
        int id = getRecordsNumber() + 1;
        myDb.execSQL("insert into " + dbHelper.TB_NAME + " values(?,?,?)", new Object[]{id, name, age});
    }

    //删除记录
    public void deleteInfo(String selId) {
        myDb = dbHelper.getReadableDatabase();
        myDb.delete(dbHelper.TB_NAME,"id="+selId,null);
    }

    //修改记录
    public void updateInfo(String name, int age, String selId) {
        myDb = dbHelper.getReadableDatabase();
        myDb.execSQL("update "+dbHelper.TB_NAME+" set name = ? ,age = ? where id = ?", new Object[]{name, age, selId});
    }
}

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="match_parent"
        android:orientation="vertical">

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

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name:" />

            <EditText
                android:id="@+id/editText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="textPersonName"
                android:text="" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="  Age:  " />

            <EditText
                android:id="@+id/editText2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="textPersonName"
                android:text="" />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textAllCaps="false"
                android:text="Add" />

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textAllCaps="false"
                android:text="Modify" />

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textAllCaps="false"
                android:text="Delete" />

        </LinearLayout>
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

list_1.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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="" />

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="" />
    </LinearLayout>
</LinearLayout>

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43873198/article/details/108894045