ObjectBox数据库(Android使用)

开始

这是一个移动数据库,使对象持久性变得简单和快速。
项目浮渣Demo参考:https://github.com/objectbox/objectbox-examples

基本配置

  1. 在 Project 级别的 build.gradle 文件里脚本如下:
ext {//统一管理app项目的版本
    compileSdkVersion = 28
    buildToolsVersion = "28.0.1"
    minSdkVersion = 15
    targetSdkVersion = 28
    butterknifeVersion = '9.0.0-rc1'
    supportVersion = '28.0.0'
    versionCode = 102
    versionName = "1.0.2"
}

buildscript {
    ext.objectboxVersion = '1.5.0'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}

allprojects {
    buildscript {
        repositories {
            jcenter()
            mavenCentral()
            google()
        }
    }

    repositories {
        jcenter()
        mavenCentral()
        google()
    }
}

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

  1. 在 Module 级别的 build.gradle 文件里脚本如下:
    注意这里的 apply plugin: ‘io.objectbox’ 一定要添加到 dependencies 模块后面(已经踩过这个坑了,直接按照官网的 Get Started 的集成方式有点问题),否则编译不成功。
apply plugin: 'com.android.application'

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

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    defaultConfig {
        applicationId "com.example.objectboxdemo"
        minSdkVersion  rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode rootProject.ext.versionCode
        versionName   rootProject.ext.versionName
        //testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"//用于测试
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "com.android.support:appcompat-v7:$rootProject.ext.supportVersion"
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    /* 下面这两句是 ObjectBox 很骚气的一个功能——DataBrowser, 通过浏览器来调试和浏览数据库的数据*/
    debugImplementation "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"
    releaseImplementation "io.objectbox:objectbox-android:$objectboxVersion"
}
apply plugin: 'io.objectbox'
/*'io.objectbox'的配置必须放在dependencies之后*/

创建一个实体类Note

其中:
@Entity 注解表明 Note 是一个写入数据库的实体 (数据表)
@id 表明 long id 作为Key (主键)

一般来说,一个ObjectBox实体是一个带有属性的有注解标记的类。你可以按照这种方法创建新的实体到数据库中。
接下来编译工程,ObjectBox会生成一些类,如 MyObjectBox 。还有一些ObjectBox在内部使用的其他一些类。

import java.util.Date;

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


@Entity
public class Note {
    
    @Id
    long id;
    String text;//内容
    String comment;//评论
    Date date;

    public Note(long id, String text, String comment, Date date) {
        this.id = id;
        this.text = text;
        this.comment = comment;
        this.date = date;
    }

    public Note() {
    }

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getText() {
        return this.text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getComment() {
        return this.comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

定义ObjectBox

初始化boxStore,以及获取boxStore的方法
在ObjectBox.java中:

import android.content.Context;
import android.util.Log;
import io.objectbox.BoxStore;

public class ObjectBox {

    private static BoxStore boxStore;

    static void init(Context context) {
        boxStore = MyObjectBox.builder()
                .androidContext(context.getApplicationContext())
                .build();
/*
        if (BuildConfig.DEBUG) {
            new AndroidObjectBrowser(boxStore).start(this);
            Log.d(App.TAG, String.format("Using ObjectBox %s (%s)",
                    BoxStore.getVersion(), BoxStore.getVersionNative()));
        }*/
    }

    public static BoxStore get() {
        return boxStore;
    }

初始化ObjectBox

在App.java中:

import android.app.Application;

public class App extends Application {

    public static final String TAG = "ObjectBoxExample";

    @Override
    public void onCreate() {
        super.onCreate();
        ObjectBox.init(this);
    }
}

并在AndroidManifest.xml中配置


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

准备Box对象

在NoteActivity.java中:
我们必须为我们的Note类准备一个Box对象,我们 在onCreate()中做 :

  Box<Note>   noteBox = ObjectBox.get().boxFor(Note.class);

添加数据

private void addNote() {
    String noteText = editText.getText().toString();
    editText.setText("");
    /*MEDIUM(同时也是默认格式)     getTimeInstance方法,只获取时间的实例对象*/
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    String comment = "Added on " + df.format(new Date());
    Note note = new Note();
    note.setText(noteText);
    note.setComment(comment);
    note.setDate(new Date());
    noteBox.put(note);
    lookNotes();
}

删除

/*点击item删除*/
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Note note = (Note) notesAdapter.getItem(position);
        noteBox.remove(note);
        lookNotes();
    }
};

修改数据

public void onUpdataButtonClick(View view) {
    List<Note> notes = noteBox.query().equal(Note_.text, "123").build().find();
    if (editText.getText() != null && notes.size() > 0) {
        notes.get(0).text = editText.getText().toString();
        Toast.makeText(this, "修改成功", Toast.LENGTH_LONG).show();
        noteBox.put(notes);
    } else {
        Toast.makeText(this, "修改失败", Toast.LENGTH_LONG).show();
    }
}

查看所有

private void lookNotes() {
    noteQuery = noteBox.query().order(Note_.text).build();
    List<Note> notes = noteQuery.find();
    notesAdapter.setNote(notes);
}

按条加查询

/*按单条件查找*/
public void onFindButtonClick(View view) {
    List<Note> theseNote = noteBox.query().equal(Note_.text, "陈林颍").build().find();
    notesAdapter.setNote(theseNote);
}

/*按多条件查找*/
public void onMoreFindButtonClick(View view) {
    QueryBuilder<Note> builder = noteBox.query();
    builder.equal(Note_.text, "123").startsWith(Note_.comment, "Added on");
    List<Note> notes = builder.build().find();
    notesAdapter.setNote(notes);
}

简单Demo:https://github.com/sindicly/ObjectboxDemo
参考:https://blog.csdn.net/vxiaocai/article/details/78616526

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值