美文网首页ObjectBox
ObjectBox数据库使用说明

ObjectBox数据库使用说明

作者: 人鱼小姐没有腿 | 来源:发表于2020-07-23 19:02 被阅读0次

如何使用ObjectBox

一、搭建ObjectBox环境
1.在根目录的build文件中添加

buildscript {
    ext.kotlin_version = "1.3.72"
    ext.objectboxVersion = '2.6.0'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"
        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 {
        maven { url 'https://jitpack.io' }
        google()
        jcenter()
    }
}

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

在app.build文件中添加

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

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.xxx.xxxx"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
   
    // 添加objectbox 查看依赖
    debugImplementation "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"
    releaseImplementation "io.objectbox:objectbox-android:$objectboxVersion"
}
// 将这句话放在末尾,不然会出问题
apply plugin: 'io.objectbox'

2.新建实体类

package com.zhiqingwei.cargame

import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id

/**
 * create by Se7en
 * on 2020/7/23
 */
@Entity
data class UserBean(
    //id为自增
    @Id var id: Long = 0,
    var userName: String? = null,
    var userAge: Int = 0
)

然后Rebuild Project 让ObjectBox生成需要的东西

3.新建类Objectbox

package com.zhiqingwei.cargame

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

/**
 * create by Se7en
 * on 2020/7/23
 */
object ObjectBox {
    lateinit var boxStore: BoxStore
        private set
    fun init(context: Context) {
        boxStore = MyObjectBox.builder()
            .androidContext(context.applicationContext)
            .build()
    }
}

如果找不到MyObjectBox 则是因为在第二步中创建完实体类的时候没有重新rebuild项目

二、使用ObjectBox数据库之增删改查
1.在application中初始化

package com.zhiqingwei.cargame

import android.app.Application
import android.content.Context

/**
 * create by Se7en
 * on 2020/7/23
 */
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        initObjectBox(this)
    }
}

private fun initObjectBox( context: Context){
    ObjectBox.init(context)
}

创建好自己的application别忘了在AndroidManifest中加上

 android:name=".MyApplication"

2.如何新增数据?

 /**
     * 新增数据
     */
    private fun insertUser() {
        //建立一个链接
        val userBox = ObjectBox.boxStore.boxFor(UserBean::class.java)
        //单条插入
        val user = UserBean(0.toLong(), "用户1", 18)
        userBox.put(user)
        //list插入
        val userList: MutableList<UserBean> = ArrayList()
        userList.add((UserBean(0.toLong(), "用户2", 19)))
        userList.add((UserBean(0.toLong(), "用户3", 20)))
        userList.add((UserBean(0.toLong(), "用户4", 21)))
        userBox.put(userList)
    }

3.如何查询数据

   /**
     * 查询
     */
    private fun queryUser() {
        //建立一个链接
        val userBox = ObjectBox.boxStore.boxFor(UserBean::class.java)
        //查询用户3的信息 返回一个object
        var user = userBox.query().equal(UserBean_.userName, "用户3").build().findFirst()
        // 查询所有
        val users = userBox.all
    }

4.如何更新数据

 /**
     * 更新数据
     * 更新于新增都是用put方法,区别是id存在的话更新,如果不存在则新增
     */
    private fun updateUser() {
        //建立一个链接
        val userBox = ObjectBox.boxStore.boxFor(UserBean::class.java)
        //查询用户3的信息 返回一个object
        val user = userBox.query().equal(UserBean_.userName, "用户3").build().findFirst()
        if (user != null) {
            user.userName = "用户33"
            userBox.put(user)
        }
    }

5.如何删除数据

 /**
     * 删除数据
     */
    private fun deleteUser() {
        //建立一个链接
        val userBox = ObjectBox.boxStore.boxFor(UserBean::class.java)
        //查询用户3的信息 返回一个object
        val user = userBox.query().equal(UserBean_.userName, "用户3").build().findFirst()
        if (user != null) {
            userBox.remove(user)
        } else {
            Toast.makeText(this, "查无此人", Toast.LENGTH_SHORT).show()
        }
    }

三、ObjectBox的可视化操作
1.app.build文件中添加

    debugImplementation "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"

2.在上文ObjectBox中添加在debug状态下开启浏览服务

/**
 * create by Se7en
 * on 2020/7/23
 */
object ObjectBox {
    lateinit var boxStore: BoxStore
        private set
    fun init(context: Context) {
        boxStore = MyObjectBox.builder()
            .androidContext(context.applicationContext)
            .build()
        if (BuildConfig.DEBUG) {
            // 开启一个浏览服务
            val started = AndroidObjectBrowser(boxStore).start(context)
            Log.i("ObjectBrowser", "Started: $started")
        }
    }
}

3.在AndroidManifest.xml中添加权限

<!-- Required to provide the web interface -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Required to run keep-alive service when targeting API 28 or higher -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

4.运行项目 过滤一下log 点击通知栏里的地址可以在手机浏览器中打开数据库

2020-07-23 18:41:47.615 18853-18853/? I/ObjectBrowser: ObjectBrowser started: http://localhost:8091/index.html
2020-07-23 18:41:47.615 18853-18853/? I/ObjectBrowser: Command to forward ObjectBrowser to connected host: adb forward tcp:8091 tcp:8091
2020-07-23 18:41:47.633 18853-18853/? I/ObjectBrowser: Started: true
WechatIMG47309.png

5.查看手机浏览器中数据库的数据


WechatIMG47310.png

6.由于手机查看数据库很不方便,所以我们这里用adb命令来使用pc端的浏览器来查看

adb forward tcp:8091 tcp:8091
//这里的8091是上边log打印出来的,上面的端口是多少 这边就是多少 不然无法显示

四、如何内置数据库
1.在你用上述方法将数据填进数据库中的时候,就会在安卓机本地生成了db文件。我们要做的就是将db文件烤入到assets文件中,使得开始进入App的时候,就有内置数据了。

2.db文件的路径 WechatIMG243.png

db的文件路径为
/data/data/packagename/files/objectbox/objectbox/data.mdb
如上图所示

3.将导出的数据库文件放入assets文件夹中 如图 WechatIMG47314.png

4.将导入的db文件在ObjectBox中初始化

object ObjectBox {
    lateinit var boxStore: BoxStore
        private set
    fun init(context: Context) {
        boxStore = MyObjectBox.builder()
            .androidContext(context.applicationContext)
            .initialDbFile{
                 //初始化db文件
                context.assets.open("data.mdb")
            }
            .build()
        if (BuildConfig.DEBUG) {
            // 开启一个浏览服务
            val started = AndroidObjectBrowser(boxStore).start(context)
            Log.i("ObjectBrowser", "Started: $started")
        }
    }
}

5.大功告成,同学们可将App卸载了 测试一下 是否内置成功。

相关文章

网友评论

    本文标题:ObjectBox数据库使用说明

    本文链接:https://www.haomeiwen.com/subject/mwehlktx.html