用 ObjectBox 做一个记事本

简介

ObjectBox和GreenDao是同一家公司的产品,用来做数据的持久化存储,使用的NoSQL数据库。
ObjectBox的官网地址为:https://objectbox.io/
本文结合 ObjectBox 官网上的视频教程讲解,如果可以访问外网的话,也可以直接跟着视频学习:https://youtu.be/flmAeYY-u9I

效果图

使用

1.添加 classpath

在根目录的 build.gradle 文件中添加 classpath:

buildscript {
    ext.objectboxVersion = '2.3.4'
    ...
    dependencies {
        ...
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}

2.添加 apply plugin

apply plugin: 'kotlin-kapt'
apply plugin: 'io.objectbox'

使用 kotlin 时,必须添加 kotlin-kapt,才能使用注解。

3.新建实体类,添加 @Entity 注解

新建实体类 Note:

@Entity
data class Note(
    // id 必须为var(因为id会自增),Long类型,初始化为0。不妨记作固定写法
    @Id var id: Long = 0,
    var text: String,
    var createAt: Date
)

建立好之后,编译项目,目的是在 generatedJava 中自动生成 ObjectBox 相关代码。

4.新建 ObjectBox 工具类

新建 ObjectBox 工具类,添加静态变量 boxStore 和静态初始化方法:

class ObjectBox {
    companion object {
        lateinit var boxStore: BoxStore
        @JvmStatic
        fun init(context: Context) {
            boxStore = MyObjectBox.builder()
                .androidContext(context.applicationContext)
                .build()
        }
    }
}

5.在 Application 中初始化 ObjectBox

在 Application 中的 onCreate 中初始化 ObjectBox:

class MyApplication : Application(){
    override fun onCreate() {
        super.onCreate()
        ObjectBox.init(this)
    }
}

如果是新建的 Application, 记得在 AndroidManifest 中配置此 Application:

<application  
	android:name=".MyApplication"
    ...>
...
</application>

6.编辑 activity_main 布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etNote"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:hint="@string/enter_new_note"
        app:layout_constraintEnd_toStartOf="@id/btnAdd"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        app:layout_constraintBottom_toBottomOf="@id/etNote"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/etNote" />

    <TextView
        android:id="@+id/tvRemoveHint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/click_a_note_to_remove_it"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/etNote" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvNotes"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tvRemoveHint" />
</androidx.constraintlayout.widget.ConstraintLayout>

其中的 strings.xml 如下:

<resources>
    ...
    <string name="enter_new_note">Enter new note</string>
    <string name="add">Add</string>
    <string name="click_a_note_to_remove_it">Click a note to remove it</string>
</resources>

7.编辑 MainActivity

package com.example.studyobjectbox

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import io.objectbox.Box
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    private val noteBox by lazy { ObjectBox.boxStore.boxFor(Note::class.java) }
    private var notes = mutableListOf<Note>()
    private val adapter by lazy { NoteAdapter(notes) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        btnAdd.setOnClickListener {
            addNote()
        }
        rvNotes.layoutManager = LinearLayoutManager(this)
        rvNotes.adapter = adapter
        adapter.onItemClickListener = object:NoteAdapter.OnItemClickListener{
            override fun onItemClick(position: Int) {
                removeNote(notes[position])
            }
        }
        updateNotes()
    }

    private fun addNote() {
        val etNoteContent = etNote.text.toString()
        if (etNoteContent.isEmpty()) return
        val note = Note(text = etNoteContent, createAt = Date())
        noteBox.put(note)
        etNote.text.clear()
        updateNotes()
    }

    private fun updateNotes() {
//        notes = noteBox.all
        notes = noteBox.query()
                .order(Note_.text)
                .build()
                .find()
        adapter.setNotes(notes)
    }

    private fun removeNote(note: Note) {
        noteBox.remove(note)
        updateNotes()
    }
}

可以看到,我们先使用 ObjectBox.boxStore.boxFor(Note::class.java) 获取到 noteBox 对象,添加数据时,调用:

noteBox.put(note)

删除数据时,调用:

noteBox.remove(note)

查询数据时,可以直接使用以下代码获取所有数据:

notes = noteBox.all

或者加入查询条件,例如使用 Note 类的 text 字段排序,代码如下:

notes = noteBox.query()
        .order(Note_.text)
        .build()
        .find()

其中 NoteAdapter 代码如下:

package com.example.studyobjectbox

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_note.view.*

class NoteAdapter(private val notes: MutableList<Note>) : RecyclerView.Adapter<NoteAdapter.NoteViewHolder>() {

    var onItemClickListener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false)
        return NoteViewHolder(view)
    }

    override fun getItemCount(): Int = notes.size

    override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
        holder.itemView.tvNote.text = notes[position].text
        holder.itemView.setOnClickListener {
            onItemClickListener?.onItemClick(position)
        }
    }

    fun setNotes(notes: List<Note>) {
        this.notes.clear()
        this.notes.addAll(notes)
        notifyDataSetChanged()
    }

    class NoteViewHolder(view: View) : RecyclerView.ViewHolder(view)

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }
}

用到的 item_note 布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content">

    <TextView
        android:id="@+id/tvNote"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Today is Friday." />
</androidx.constraintlayout.widget.ConstraintLayout>

这样就完成了上面的效果图。

原创文章 67 获赞 68 访问量 6万+

猜你喜欢

转载自blog.csdn.net/AlpinistWang/article/details/96973809