1.首先是添加依赖;
build.gradle(Module:app)
buildscript { ext.objectboxVersion = '2.6.0' repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.2' //添加objectBox依赖 classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion" } }
build.gradle(Prohect:包名)
apply plugin: 'kotlin-kapt' // objectBox批注处理所必需 apply plugin: 'io.objectbox' // 应用objectBox
然后点击同步,第一步完成;
2.实体类注解
- 必须具有@Id,否则编译不通过
- 必须为var
- 建议给所有的变量赋值
- @Transient表明为非数据库字段
- @NameInDb表示该表中字段的名称
import io.objectbox.annotation.Entity import io.objectbox.annotation.Id import io.objectbox.annotation.NameInDb import io.objectbox.annotation.Transient @Entity data class History( @Id @NameInDb("S_ID") var id: Long = 0, @NameInDb("S_picture") var picture: String = "", @NameInDb("S_name") var name: String = "", @NameInDb("S_surplusLength") var surplusLength: Long = 0, @Transient var isSelect: Boolean = false ) : BaseModel(){ override fun checkCreate() : Boolean{ return true }
3.初始化ObjectBox,建议在Application中直接初始化它
- 创建object类
import android.content.Context import com.bass.noVipVideo.Model.MyObjectBox import io.objectbox.BoxStore object ObjectBox { lateinit var boxStore: BoxStore fun init(context: Context) { boxStore = MyObjectBox.builder().androidContext(context).build() } }
- 在application中初始化
class BassApplication : Application() { override fun onCreate() { super.onCreate() //初始化objectBox ObjectBox.init(this) } }
4.使用objectBox
import com.bass.noVipVideo.Model.BaseModel import com.bass.noVipVideo.Model.History import com.bass.noVipVideo.Util.ObjectBox class HistoryPresenter : BasePresenter() { override fun createAsync(model: BaseModel) { super.createAsync(model) //向数据库创建一条数据 //如果传进来的mdel的id不为0,则为更新指定id的数据 ObjectBox.boxStore.boxFor(History::class.java).put(model as History) } override fun retrieveAsync() : List<BaseModel>?{ super.retrieveAsync() //向数据库查询返回所有数据 return ObjectBox.boxStore.boxFor(History::class.java).query().build().find() } override fun deleteNAsync(historyList: List<BaseModel>) { for (model in historyList) { //删除指定id的数据的从表 ObjectBox.boxStore.boxFor(VideoSurface::class.java).remove((model as History).videoSurface.targetId) //删除指定id的数据 ObjectBox.boxStore.boxFor(History::class.java).remove((model as History).id) } } }
5.使用浏览器查看存储数据
- 添加依赖
dependencies { debugImplementation "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion" releaseImplementation "io.objectbox:objectbox-android:$objectboxVersion" } // 应用io.objectbox 一定要放在dependencies之后 apply plugin: 'io.objectbox'
- 添加权限
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
- 使用
在模拟器中使用浏览器输入:https://localhost:8090/index.html,界面如下:
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/895977.html