Android 备忘录,记事本程序设计

android备忘录实现,使用ObjectBox数据库框架进行数据存储,增删改查等操作。代码使用kotlin编写。

1、下面看看ObjectBox数据库封装

需要注意的是:

/**

* 你只有配置好之后, 点击 Make Model '你的model名字', 才会创建 MyObjectBox对象

* 对于MyObjectBox的包名, 目前我发现的是找到第一个Entity的包名

* 如果项目使用了Kotlin, 必须添加插件apply plugin: 'kotlin-kapt'

* 实体Entity是不能继承的哦.继承的字段不会被解析

*/

java 复制代码
package com.mmsx.note.app

import android.content.Context
import android.util.Log
import com.elvishew.xlog.XLog
import com.mmsx.note.entity.MyObjectBox
import com.mmsx.note.entity.NoteEntity
import com.mmsx.note.entity.NoteEntity_
import io.objectbox.Box
import io.objectbox.BoxStore
import io.objectbox.android.AndroidObjectBrowser
import io.objectbox.android.BuildConfig

object ObjectBox {
    lateinit var boxStore: BoxStore
        private set

    /**
     * 你只有配置好之后, 点击 Make Model '你的model名字', 才会创建 MyObjectBox对象
     * 对于MyObjectBox的包名, 目前我发现的是找到第一个Entity的包名
     * 如果项目使用了Kotlin, 必须添加插件apply plugin: 'kotlin-kapt'
     * 实体Entity是不能继承的哦.继承的字段不会被解析
     */
    fun init() : BoxStore{
        boxStore = MyObjectBox.builder()
            .androidContext(NoteApplication.instance.applicationContext)
            .build()
        if (BuildConfig.DEBUG) {
            val started = AndroidObjectBrowser(boxStore).start(NoteApplication.instance)
            XLog.d("ObjectBrowser", "Started: $started")
        }
        return boxStore
    }


    /**
     * 重启数据库
     * 删除本地数据库后,需要重新创建
     */
    fun  restartBoxStore(){
        boxStore = MyObjectBox.builder().androidContext(NoteApplication.instance).build()
    }

    /**
     * 添加数据
     */
    fun  addData(o: NoteEntity): Long {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                boxStore.boxFor(NoteEntity::class.java).put(o)
            }
        } catch (e: Throwable) {
            Log.d("lyy", "error:${e.printStackTrace()}")
        }
        return 0
    }

    /**
     * 更新数据(如果直接插入更新的对象,有些字段没有值会覆盖掉)
     * 1、先查询到数据
     * 2、对查询到的数据字段进行更新
     * 3、查询不到,直接插入
     */
    fun updateData(o: NoteEntity) {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                //1、先查询到数据
                val box: Box<NoteEntity> = boxStore.boxFor(NoteEntity::class.java)
                val list: MutableList<NoteEntity> = box.query().equal(NoteEntity_.id, o.id).build().find()
                var localBean = list.getOrNull(0)
                //2、对查询到的数据字段进行更新
                localBean?.let {
                    localBean.title = o.title
                    localBean.content = o.content
                    localBean.updatedAt = o.updatedAt
                    boxStore.boxFor(NoteEntity::class.java).put(localBean)
                }?: kotlin.run {
                    //3、查询不到,直接插入
                    ObjectBox.boxStore.boxFor(NoteEntity::class.java).put(o)
                }
            }
        } catch (e: Throwable) {
            Log.d("lyy", "error:${e.printStackTrace()}")
        }

    }


    /**
     * 获取全部对象数据
     */
    fun  getNoteEntityAllData(): MutableList<NoteEntity>? {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                val box: Box<NoteEntity> = boxStore.boxFor(NoteEntity::class.java)
                return box.all
            }
        } catch (e: java.lang.Exception) {
        }
        return ArrayList()
    }

    /**
     * 条件查询
     */
    fun getNoteEntityData(title : String): List<NoteEntity>? {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                val box: Box<NoteEntity> = boxStore.boxFor(NoteEntity::class.java)
                return box.query().equal(NoteEntity_.title, title).build().find()
            }
        } catch (e: java.lang.Exception) {
        }
        return ArrayList<NoteEntity>()
    }

    /**
     * 查询单个数据
     */
    fun getNoteEntity(id: Long): NoteEntity? {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                val box: Box<NoteEntity> = boxStore.boxFor(NoteEntity::class.java)
                return box[id]
            }
        } catch (e: java.lang.Exception) {
        }
        return null
    }

    /**
     * 删除数据单个数据1
     */
    fun deleteNoteEntityData(id: Long): Boolean {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                val box: Box<NoteEntity> = boxStore.boxFor(NoteEntity::class.java)
                return box.remove(id)
            }
        } catch (e: java.lang.Exception) {
        }
        return false
    }


    /**
     * 删除数据单个数据2
     */
    fun <Any> deleteData(o: Any, clazz: Class<Any>?) {
        try {
            if (boxStore != null && !boxStore.isClosed) {
                val box: Box<Any> = boxStore.boxFor<Any>(clazz)
                box.remove(o)
            }
        } catch (e: java.lang.Exception) {
        }
    }

    
}

2、主页面数据展示代码

使用kotlin代码编写,加上其他框架就是简洁啊

java 复制代码
class MainActivity : ScopedAppActivity(){
    private var adapter : NoteAdapter ? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        initView()
    }

    private fun initView() {
        adapter = NoteAdapter()
        main_note_recycler_view.layoutManager = LinearLayoutManager(this)
        main_note_recycler_view.adapter = adapter

        adapter?.setOnItemChildClickListener { adapter, view, position ->
            var intent = Intent(this, ShowNoteActivity::class.java).apply {
                putExtra("entity", adapter?.data?.get(position) as NoteEntity)
            }
            startActivity(intent)
        }
        main_add_view.setOnClickListener {
            startActivity(Intent(this, NoteActivity::class.java))
        }
        main_menu_view.setOnClickListener {
            startActivity(Intent(this, SettingActivity::class.java))
        }

    }

    override fun onResume() {
        super.onResume()
        val data = getNoteEntityAllData()
        adapter?.setNewData(data)
        if (data?.size == 0) {
            main_empty_view.visibility = View.VISIBLE
        }else{
            main_empty_view.visibility = View.GONE
        }
    }

    class NoteAdapter  : BaseQuickAdapter<NoteEntity, BaseViewHolder>(R.layout.item_main_note) {
        override fun convert(helper: BaseViewHolder, item: NoteEntity?) {
            helper.setText(R.id.item_main_note_title_view, item?.title)
                .setText(R.id.item_main_note_content_view, item?.content)
                .setText(R.id.item_main_time_content_view, TimeUtils.date2String(item?.createdAt?.let {
                    Date(
                        it
                    )
                },"yyyy/MM/dd HH:mm"))
                .addOnClickListener(R.id.item_main_note)

        }

    }
}

2、数据添加和更新页面

java 复制代码
class NoteActivity : ScopedAppActivity(){
    private var entity : NoteEntity ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_note)

        entity = this.intent.extras?.getSerializable("entity") as NoteEntity?
        initView()
    }

    private fun initView() {
        if (entity != null) {
            note_title_view.text = "编辑"
            note_title_edit_view?.setText(entity?.title)
            note_content_edit_view.setText(entity?.content)
        }

        note_done_view.setOnClickListener {
            if (entity == null) {
                entity = NoteEntity()
                entity?.title = note_title_edit_view.text.toString()
                entity?.content = note_content_edit_view.text.toString()
                entity?.createdAt = System.currentTimeMillis()
                entity?.updatedAt = System.currentTimeMillis()
                ObjectBox.addData(entity!!)
            }else{
                entity?.title = note_title_edit_view.text.toString()
                entity?.content = note_content_edit_view.text.toString()
                entity?.updatedAt = System.currentTimeMillis()
                ObjectBox.updateData(entity!!)
            }
            finish()
        }
        note_back_view.setOnClickListener {
            finish()
        }
    }
}

3、部分界面展示

相关推荐
莞凰6 小时前
昇腾CANN的“灵脉根基“:Runtime仓库探秘
android·人工智能·transformer
NiceCloud喜云7 小时前
Claude Files API 深入:从上传、复用到配额管理的工程化指南
android·java·数据库·人工智能·python·json·飞书
ujainu7 小时前
CANN pto-isa:虚拟指令集如何连接编译与执行
android·ascend
赏金术士8 小时前
第六章:UI组件与Material3主题
android·ui·kotlin·compose
~黄夫人~8 小时前
零基础速通|Windows&Linux 常用命令行对照表大全
linux·运维·windows·笔记·备忘录·整理表格
TechMerger9 小时前
Android 17 重磅重构!服役 20 年的 MessageQueue 迎来无锁改造,卡顿大幅优化!
android·性能优化
yuhuofei202112 小时前
【Python入门】Python中字符串相关拓展
android·java·python
dalancon12 小时前
Android Input Spy Window
android
dalancon13 小时前
InputDispatcher派发事件,查找目标窗口
android
我命由我1234513 小时前
Android Framework P3 - MediaServer 进程、认识 ServiceManager 进程
android·c语言·开发语言·c++·visualstudio·visual studio·android runtime