当前位置:   article > 正文

kotlin实现简单的数据库操作_android kotlin查询数据库并显示

android kotlin查询数据库并显示


使用kotlin操作数据库并且将数据显示在listview上面

XML部分

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="1200px"
        android:layout_height="600px"
        android:layout_gravity="center"/>

    <LinearLayout
        android:layout_width="1600px"
        android:layout_height="match_parent"
        android:layout_gravity="center">

        <Button
            android:id="@+id/addData"
            android:layout_margin="60px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="添加数据"/>

        <Button
            android:id="@+id/selectData"
            android:layout_margin="60px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="查询数据"/>

        <Button
            android:id="@+id/deleteData"
            android:layout_margin="60px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="删除数据"/>

    </LinearLayout>

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

ListView子项布局部分

<?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/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="tom"
        android:gravity="center"
        android:background="#ff0000"
        android:textColor="#ffffff"/>

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Kotlin部分

数据类

package com.example.yyr2_9

/**
 *@创建者:      yuyiran
 *@创建日期:    2020-6-5 15:33
 *@描述:
 */
class Data(val name:String) {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

ListView适配器部分

package com.example.yyr2_9

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

/**
 *@创建者:      yuyiran
 *@创建日期:    2020-6-5 15:31
 *@描述:
 */
class MyAdapter(val content : Context,val datas:ArrayList<Data>):BaseAdapter() {

    inner class MyHolder(){
        lateinit var name:TextView
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var view:View ?= null
        var myHolder : MyHolder ?= null
        if(convertView == null){
            myHolder = MyHolder()
            view = LayoutInflater.from(content).inflate(R.layout.listview,null)
            myHolder.name = view.findViewById(R.id.name)
            view.tag = myHolder
        }else{
            view = convertView
            myHolder = view.tag as MyHolder
        }

        myHolder.name.text = datas.get(position).name
        return view!!
    }

    override fun getItem(position: Int): Any {
        //获取指定位置(position)上的item对象,通常不需要修改
        return datas.get(position)
    }

    override fun getItemId(position: Int): Long {
        // 获取指定位置(position)上的item的id,通常不需要修改
        return position.toLong()
    }

    override fun getCount(): Int {
        //返回一个整数,就是要在listview中现实的数据的条数
        return datas.size
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

SQLiteOpenHelper

注意:SQLiteOpenHelper是一个抽象类,我们需要自己创建一个类来继承他
SQLiteOpenHelper需要重写两个方法onCreate和onUpgrade

package com.example.yyr2_9

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

/**
 *@创建者:      yuyiran
 *@创建日期:    2020-6-5 15:46
 *@描述:
 */
class MyDatabaseHelper(val context: Context,name:String,version:Int) : SQLiteOpenHelper(context,name,null,version) {

    private val CraeteDatbase = "create table t1(id integer primary key,name text) "

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(CraeteDatbase)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

MainActivity部分

package com.example.yyr2_9

import android.content.ContentValues
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var list:ArrayList<Data> ?= ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val dbHelper = MyDatabaseHelper(this,"name.db",1)
        addData.setOnClickListener {
            list?.clear()
            val db = dbHelper.writableDatabase
            val values = ContentValues().apply {
                put("name",RandomName())
            }
            db.insert("t1",null,values)
            val cursor = db.query("t1",null,null,null,null,null,null)
            if(cursor.moveToFirst()){
                do {
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    list?.add(Data(name))
                }while (cursor.moveToNext())
            }
            listview.adapter = MyAdapter(this,list!!)
            cursor.close()
        }
        deleteData.setOnClickListener {
            list?.clear()
            val db = dbHelper.writableDatabase
            db.delete("t1","id>?", arrayOf("2"))
            val cursor = db.query("t1",null,null,null,null,null,null)
            if(cursor.moveToFirst()){
                do {
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    list?.add(Data(name))
                }while (cursor.moveToNext())
            }
            listview.adapter = MyAdapter(this,list!!)
            cursor.close()
        }
        selectData.setOnClickListener {
            list?.clear()
            val db = dbHelper.writableDatabase
            val cursor = db.query("t1",null,null,null,null,null,null)
            if(cursor.moveToFirst()){
                do {
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    list?.add(Data(name))
                }while (cursor.moveToNext())
            }
            listview.adapter = MyAdapter(this,list!!)
            cursor.close()
        }
    }

    private fun RandomName():String{
        var number = (1..9).random().toString()
        return "姓名${number}"
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

效果图

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/1009200
推荐阅读
相关标签
  

闽ICP备14008679号