Kotlin 使用 viewBinding 和 Kotlin objectbox 增删改查

11 篇文章 1 订阅
8 篇文章 0 订阅

1、Kotlin viewBinding 基础使用

2、Kotlin objectbox 增删改查(java写法:https://blog.csdn.net/weixin_41454168/article/details/126320529

界面展示

正文代码 

一、build.gradle配置: ObjectBox 相关

        1、项目 build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 33
    buildToolsVersion "33.0.0"

    defaultConfig {
        applicationId "com.xolo.testone"
        minSdkVersion 19
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //RecyclerView 列表
    implementation 'androidx.recyclerview:recyclerview:1.2.0-beta01'

    //SmartRefreshLayout 下拉刷新 上拉加载
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.4-7'

}

//ObjectBox 相关
apply plugin: "io.objectbox" // Add after other plugins.

        2、app build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    //ObjectBox 相关
    ext.objectboxVersion = '2.9.1'

    ext.kotlin_version = "1.4.21"
    repositories {
        google()
        jcenter()
        //ObjectBox 相关
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

二、增、删、查相关代码

        1、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="vertical">

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="名称"
            android:textColor="#000000"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/etAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="年龄"
            android:inputType="number"
            android:textColor="#000000"
            android:textSize="18sp" />

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

            <Button
                android:id="@+id/btnAdd"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="添加" />
            <Button
                android:id="@+id/btnQuery"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="查询" />


        </LinearLayout>


    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#D9F8F5"
        android:gravity="center|left"
        android:paddingLeft="20dp"
        android:text="数据列表-点击可删、下拉刷新、上拉加载"
        android:textColor="#000000"
        android:textSize="18sp" />

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/srlControl"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        app:srlAccentColor="#00000000"
        app:srlEnablePreviewInEditMode="true"
        app:srlPrimaryColor="#00000000">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvData"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

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

        <Button
            android:id="@+id/btnRandomFill"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="随机填充 100 条" />
        <Button
            android:id="@+id/btnDel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="删除全部" />


    </LinearLayout>


</LinearLayout>

         2、MainActivity 

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.scwang.smartrefresh.layout.header.BezierRadarHeader
import com.xolo.testone.databinding.ActivityMainBinding
import io.objectbox.Box
import io.objectbox.query.QueryBuilder
import java.util.*

class MainActivity : AppCompatActivity() {

    private lateinit var mainBinding: ActivityMainBinding
    private lateinit var studentModelBox: Box<StudentModel>

    private lateinit var studentAdapter:StudentAdapter
    var list = ArrayList<StudentModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        //加载界面
        mainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainBinding.root)

        //获取数据表对象
        studentModelBox = ObjectBox.boxStore.boxFor(StudentModel::class.java)

        //添加StudentAdapter适配器
       // list = ArrayList<StudentModel>()
        studentAdapter = StudentAdapter(this, list, object : ClickInterface {
            override fun ClickOnThe(o: Any?) {
                studentModelBox.remove(list[o as Int])
                list.remove(list[o as Int])
                studentAdapter.notifyDataSetChanged()
                Toasts("删除成功")
            }
        })
        mainBinding.rvData.layoutManager = GridLayoutManager(this, 1)
        mainBinding.rvData.isNestedScrollingEnabled = true
        mainBinding.rvData.adapter = studentAdapter

        //添加点击事件
        mainBinding.btnAdd.setOnClickListener { v ->
            val name = mainBinding.etName.text.toString()
            val age = mainBinding.etAge.text.toString()
            val studentModel = StudentModel()
            studentModel.name = name
            studentModel.age = age
            //添加进入数据库
            studentModelBox.put(studentModel)
            list.add(0, studentModel)
            studentAdapter.notifyDataSetChanged()
            Toasts("添加成功")
            //清空输入框
            mainBinding.etName.setText("")
            mainBinding.etAge.setText("")
        }

        //点击查询
        mainBinding.btnQuery.setOnClickListener { v ->
            val name = mainBinding.etName.text.toString()
            val age = mainBinding.etAge.text.toString()

            //模糊查询
            list.clear()
            val query = studentModelBox.query()
                //匹配查询用 equal
                //.equal(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                //.equal(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                //模糊查询用 contains
                .contains(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                .contains(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                .build()
            list.addAll(query.find(list.size.toLong(), 10))

            //查询全部数据
            //list.addAll(studentModelBox.getAll());
            studentAdapter.notifyDataSetChanged()
            Toasts("查询成功")
        }

        //删除全部
        mainBinding.btnDel.setOnClickListener { v ->
            //清空界面
            list.clear()
            studentAdapter.notifyDataSetChanged()
            //删除全部条码
            studentModelBox.removeAll()
            Toasts("删除成功")
        }

        //随机填充 100 条数据
        mainBinding.btnRandomFill.setOnClickListener { v ->
            for (i in 0..99) {
                //添加进入数据库-随机生成姓名和年龄
                val studentModel = StudentModel()
                studentModel.name = RandomWordUtils.getChineseWord()
                studentModel.age = (Math.random() * 100 + 1).toString()
                studentModelBox.put(studentModel)
            }
            Toasts("添加成功")
        }

        //下拉刷新
        mainBinding.srlControl.refreshHeader =
            BezierRadarHeader(applicationContext).setEnableHorizontalDrag(true)
        mainBinding.srlControl.setOnRefreshListener {
            //启用刷新动画
            mainBinding.srlControl.isEnableRefresh = true

            //查询第一条-从第 list.size() 条开始查,一次查10条,这里经过  list.clear() ,所以 list.size() 为 0
            list.clear()
            val query = studentModelBox.query().build()
            list.addAll(query.find(list.size.toLong(), 10))
            studentAdapter.notifyDataSetChanged()

            //结束刷新动画
            mainBinding.srlControl.finishRefresh()
        }
        //上拉加载
        //上拉加载
        mainBinding.srlControl.setOnLoadmoreListener {
            //启用加载动画
            mainBinding.srlControl.isEnableLoadmore = true

            //分页查询-从第 list.size() 条开始查,一次查10条
            val query = studentModelBox.query().build()
            list.addAll(query.find(list.size.toLong(), 10))
            studentAdapter.notifyDataSetChanged()

            //结束加载动画
            mainBinding.srlControl.finishLoadmore()
        }

    }

    //Toast
    private fun Toasts(content: String?) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
    }
}

三、adapter代码

        1、adapter_student.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="wrap_content"
    android:orientation="vertical"
    android:padding="5dp"
    android:background="#FFFFFF"
    android:layout_marginBottom="1dp"
    android:id="@+id/llClick">

    <TextView
        android:id="@+id/tvId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ID:"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name:"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="age:"
        android:textColor="#000000"
        android:textSize="18sp" />


</LinearLayout>

        2、StudentAdapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.xolo.testone.databinding.AdapterStudentBinding

class StudentAdapter(private var context:Context, private var list: List<StudentModel>, private var clickInterface:ClickInterface):
    RecyclerView.Adapter<StudentAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentAdapter.ViewHolder {
        //界面设置
        val studentBinding:AdapterStudentBinding = AdapterStudentBinding.inflate(LayoutInflater.from(context), parent, false)
        return ViewHolder(studentBinding, studentBinding.root)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: StudentAdapter.ViewHolder, position: Int) {
        holder.studentBinding.tvId.text = "ID:" + list[position].id
        holder.studentBinding.tvName.text = "姓名:" + list[position].name
        holder.studentBinding.tvAge.text = "年龄:" + list[position].age
        holder.studentBinding.llClick.setOnClickListener { v -> clickInterface.ClickOnThe(position) }
    }

    override fun getItemCount(): Int {
        return list.size
    }

    class ViewHolder(item: AdapterStudentBinding, itemView: View):RecyclerView.ViewHolder(itemView){
        var studentBinding:AdapterStudentBinding = item
    }
}

四、ObjectBox 代码

import android.content.Context
import io.objectbox.BoxStore

object ObjectBox {
    lateinit var boxStore: BoxStore
    //private set
    fun init(context: Context) {
        boxStore = MyObjectBox.builder()
                .androidContext(context.applicationContext)
                .build()
    }
}

五、RandomWordUtils 随机生成姓名代码

import java.util.*

object RandomWordUtils {

    //随机生成一个汉字
    fun getChineseWord(): String {
        val encodelist = arrayOf(
            "GB2312",
            "ISO-8859-1",
            "UTF-8",
            "GBK",
            "Big5",
            "UTF-16LE",
            "Shift_JIS",
            "EUC-JP"
        )
        var str = ""
        val hightPos: Int
        val lowPos: Int
        val random = Random()
        hightPos = (176 + Math.abs(random.nextInt(39)))
        lowPos = (161 + Math.abs(random.nextInt(93)))
        val b = ByteArray(2)
        b[0] = (Integer.valueOf(hightPos)).toByte()
        b[1] = (Integer.valueOf(lowPos)).toByte()
        try {
            str = String(b, charset(encodelist[3]))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }

}

六、StudentModel 代码

注意事项ObjectBox 需要创建任意一个 @Entity class 否则会一直提示找不到MyObjectBox
需要rebuild project 项目,此时就可以在Application下使用MyObjectBox了

import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
@Entity
class StudentModel {
    @Id
    var id:Long = 0
    lateinit var name:String
    lateinit var age:String
    
}

七、MyObjectBoxApplication 代码:需要在 AndroidManifest.xml 引入

import android.app.Application

class MyObjectBoxApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        //初始化 ObjectBox
        ObjectBox.init(this)
    }
}

八、AndroidManifest.xml 代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xolo.testone">

    <application
        android:name=".MyObjectBoxApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

九、ClickInterface 代码

interface ClickInterface {
    fun ClickOnThe(o: Any?)
}

十、代码界面展示

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Kotlin是一种基于JVM的静态类型的编程语言,它提供了丰富的库和工具,用于与SQLite数据库进行增删改查操作。 首先,我们需要导入SQLite库。在Kotlin中,可以使用`import`语句导入相应的库,例如`import org.sqlite.SQLiteConnection`。 然后,我们可以使用SQLite连接API来建立与数据库的连接。使用`SQLiteConnection`类的`create`方法可以创建一个新的数据库连接对象。 接下来,我们可以使用SQL语句执行所有的增删改查操作。例如,要执行插入操作,我们可以使用`SQLiteConnection`对象的`executeUpdate`方法,将INSERT语句作为参数传递给该方法。 要执行查询操作,可以使用`SQLiteConnection`对象的`executeQuery`方法,将SELECT语句作为参数传递给该方法。该方法将返回一个`ResultSet`对象,其中包含查询结果。 要执行更新操作,可以使用`SQLiteConnection`对象的`executeUpdate`方法,将UPDATE语句作为参数传递给该方法。 要执行删除操作,可以使用`SQLiteConnection`对象的`executeUpdate`方法,将DELETE语句作为参数传递给该方法。 最后,还需要注意在完成数据库操作后及时关闭连接,以释放资源。可以使用`SQLiteConnection`对象的`close`方法来关闭数据库连接。 综上所述, Kotlin提供了与SQLite数据库进行增删改查的一系列API和工具,可以方便地进行数据库操作。以上只是一个简单的示例,实际应用中可能需要更复杂的SQL语句和数据模型,但基本原理是相同的。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值