用 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,才能使用註解。注意這裏的順序很重要,kotlin-kapt 必須在 objectbox 之前,否則你會看到這個錯誤:

No ObjectBox annotation processor configuration found. Please check your build scripts.

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>

這樣就完成了上面的效果圖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章