ObjectBox使用

花欣然
2023-12-01

Step 1,build.gradle(Project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.objectboxVersion = '2.3.4'  //------》ObjectBox配置文件

    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"  //------》ObjectBox配置文件        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

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

Step 2,build.gradle(Module app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    debugImplementation "io.objectbox:objectbox-android-objectbrowser:$objectboxVersion"     //-------》ObjcetBox配置文件
    releaseImplementation "io.objectbox:objectbox-android:$objectboxVersion"                 //-------》ObjcetBox配置文件
    implementation "io.objectbox:objectbox-kotlin:$objectboxVersion"                         //-------》ObjcetBox配置文件
}

apply plugin: 'io.objectbox'                                                                 //-------》ObjcetBox配置文件

Step 3,Androidminifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <!-- ObjectBox电脑浏览数据库必备权限,其实就是网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- ObjectBox电脑浏览数据库必备权限,保持持久连接的权限 -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 4,新建一个实体类 WeatherEntity

这里我的数据是访问某个天气接口获得的,有兴趣小伙伴自己去弄一下:https://tianqiapi.com/

天气接口请求格式为:https://tianqiapi.com/api?version=v1&appid=你的id&appsecret=你的密码

@Entity
public class WeatherEntity {

    @Id
    private long id;
    private String cityid;
    private String update_time;
    private String city;
    private String cityEn;
    private String country;
    private String countryEn;

    public long getId() {
        return id;
    }

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

    public String getCityid() {
        return cityid;
    }

    public void setCityid(String cityid) {
        this.cityid = cityid;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(String update_time) {
        this.update_time = update_time;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCityEn() {
        return cityEn;
    }

    public void setCityEn(String cityEn) {
        this.cityEn = cityEn;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountryEn() {
        return countryEn;
    }

    public void setCountryEn(String countryEn) {
        this.countryEn = countryEn;
    }

    @Override
    public String toString() {
        return "WeatherEntity{" +
                "id=" + id +
                ", cityid='" + cityid + '\'' +
                ", update_time='" + update_time + '\'' +
                ", city='" + city + '\'' +
                ", cityEn='" + cityEn + '\'' +
                ", country='" + country + '\'' +
                ", countryEn='" + countryEn + '\'' +
                '}';
    }
}

Setp 5,新建实体类后,点击Android Studio 上方 Build->Make Project一下

Step 6,新建一个类 App 继承子Application

由于类App继承与Application,我们需要在Androidminifest.xml中的application添加一项属性。
这样才会生成MyObject类(这个后面会用的,大家暂时不用去管它在哪里,后面我们直接导入便可)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.objectboxdemo">

    <!-- Required to provide the web interface -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Required to run keep-alive service when targeting API 28 or higher -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

<!--由于类App继承Application因此必须在application写android:name=".App"-->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".App"         
        android:networkSecurityConfig="@xml/network_security_config">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 7,编写类App内容

package com.example.objectboxdemo;

import android.app.Application;
import android.util.Log;
import io.objectbox.BoxStore;
import io.objectbox.android.AndroidObjectBrowser;

public class App extends Application {

    private BoxStore boxStore;

    private static App myApplication = null;

    public static App getApplication() {
        return myApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;

        /**
         *  需要用浏览器查看数据库写这句代码,之后点击log打出的地址信息,
         *  用电脑浏览器访问,若不能进行访问,则在Android Studio 左下角的 Terminal,
         *  输入 adb forward tcp:8090 tcp:8090 ,之后浏览器重新访问
         */
        //写完这句代码后,我们建立一下实体类,之后Rebuild Project一下,MyObjectBox就可以导入了
        boxStore = MyObjectBox.builder().androidContext(App.this).build();
        if (BuildConfig.DEBUG) {
            boolean started = new AndroidObjectBrowser(boxStore).start(this);
            Log.i("ObjectBrowser", "Started: " + started + "   " + boxStore.getObjectBrowserPort());
        }
    }

    public BoxStore getBoxStore() {
        return boxStore;
    }
}

Step 8,MainActivity代码

package com.example.objectboxdemo;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private String weatherAddress = "https://tianqiapi.com/api?version=v1&appid=22239752&appsecret=uYUIT51H";

    private Box<WeatherEntity> weatherEntityBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BoxStore boxStore = ((App) getApplication()).getBoxStore();
        weatherEntityBox= boxStore.boxFor(WeatherEntity.class);
//        initWeatherDatas();

        /**
         * 增加
         */
        WeatherEntity weatherEntity =  new WeatherEntity();
        weatherEntity.setCity("南京");
        weatherEntityBox.put(weatherEntity);

        /**
         * 查询
         */
        //单条查询,返回数据库中城市名字为厦门的所有WeatherEntity对象集合
        List<WeatherEntity> weatherEntityList = weatherEntityBox.query().equal(WeatherEntity_.city, "厦门").build().find();

        //多条件查询,返回数据库中国家为中国、城市id大于2、城市字母为c开头的所有WeatherEntity对象集合
        List<WeatherEntity> weatherEntityList1 = weatherEntityBox.query()
                                   .equal(WeatherEntity_.country, "中国")
                                   .greater(WeatherEntity_.cityid, 2)
                                   .startsWith(WeatherEntity_.cityEn, "c")
                                   .build().find();

        //build之后的find不同
        //find()返回满足条件所有对象
        List<WeatherEntity> k1 = weatherEntityBox.query().equal(WeatherEntity_.city, "厦门").build().find();
        //findFirst()返回满足条件的第一个对象
        WeatherEntity k2 = weatherEntityBox.query().equal(WeatherEntity_.city, "厦门").build().findFirst();
        //findUnique()如果查询结果唯一,则返回该对象,如果查询结果不唯一,会抛出异常,如果没有查询结果则返回null。
        WeatherEntity k3 = weatherEntityBox.query().equal(WeatherEntity_.city, "厦门").build().findUnique();

        /**
         * 删除
         */
        weatherEntityBox.remove(k3);  //删除数据库中的k3对象
        weatherEntityBox.removeAll(); //删除数据库中所有对象

        /**
         * 修改
         */
        k3.setCity("北京");
        weatherEntityBox.put(k3);     //修改k3的城市名字
    }


    private void initWeatherDatas() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url(weatherAddress)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Gson gson=new Gson();
                        //这里weatherEntity只有response一些简单信息,才能直接对应,复杂信息的话会出问题
                        WeatherEntity weatherEntity = gson.fromJson(response.body().string(),WeatherEntity.class);
                        weatherEntityBox.put(weatherEntity);
                    }
                });
            }
        }).start();
    }
}

小提示:
新建实体类后,要生成get和set方法,不然会发生编译错误(这是我遇到的问题,不知大家是否也是一样)。另外实体类也必须有这个属性@Id private long id;不然也会发生编译错误。

 类似资料: