ObjectBox 初探

12 篇文章 0 订阅
8 篇文章 0 订阅

使用效果:感觉比MySqlite简单一些

内容包含:增、删、查(改和增差不多,只要id是一样,就默认为修改)

ObjectBox  添加数据

ObjectBox  随机添加

ObjectBox 模糊查询

ObjectBox  匹配查询

ObjectBox  查询全部

ObjectBox  删除全部

ObjectBox  分页查询

其中代码里 ViewBinding 不懂的,可以查看:ViewBinding 初探-在Activity和Adapter中使用_thiscopy的博客-CSDN博客

界面展示

正文代码

一、build.gradle配置: ObjectBox 相关

        1、项目 build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    //ObjectBox 相关
    ext.objectboxVersion = "3.2.1"
    repositories {
        google()
        jcenter()
        //ObjectBox 相关
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        //ObjectBox 相关
        classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion")
    }
}

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

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

        2、app build.gradle

注意:apply plugin: "io.objectbox" 须要添加到 dependencies 后面

apply plugin: 'com.android.application'

android {
    compileSdkVersion 32
    buildToolsVersion "32.0.0"

    defaultConfig {
        applicationId "com.xolo.myobjectbox"
        minSdkVersion 16
        targetSdkVersion 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

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

    //ButterKnife
    /*implementation 'com.jakewharton:butterknife:10.2.3'
    annotationProcessor  'com.jakewharton:butterknife-compiler:10.2.3'*/

    //RecyclerView 列表
    implementation 'androidx.recyclerview:recyclerview:1.2.0-beta01'

    //SmartRefreshLayout 下拉刷新 上拉加载
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.4-7'
}

//ObjectBox 相关
apply plugin: "io.objectbox" // Add after other plugins.

二、增、删、查相关代码

        1、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="名称"
            android:textColor="#000000"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/etAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="年龄"
            android:inputType="number"
            android:textColor="#000000"
            android:textSize="18sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnAdd"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="添加" />
            <Button
                android:id="@+id/btnQuery"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="查询" />


        </LinearLayout>


    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#D9F8F5"
        android:gravity="center|left"
        android:paddingLeft="20dp"
        android:text="数据列表-点击可删、下拉刷新、上拉加载"
        android:textColor="#000000"
        android:textSize="18sp" />

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/srlControl"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        app:srlAccentColor="#00000000"
        app:srlEnablePreviewInEditMode="true"
        app:srlPrimaryColor="#00000000">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvData"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnRandomFill"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="随机填充 100 条" />
        <Button
            android:id="@+id/btnDel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="删除全部" />


    </LinearLayout>


</LinearLayout>

        2、MainActivity 

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Bundle;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.xolo.myobjectbox.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;
import io.objectbox.query.Query;
import io.objectbox.query.QueryBuilder;

public class MainActivity extends AppCompatActivity {

    //系统依据 activity_main.xml 自动生成的 ActivityMainBinding 类,通过 ActivityMainBinding 可以获取对应的控件
    ActivityMainBinding mainBinding;

    private StudentAdapter studentAdapter;
    private List<StudentModel> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main); -需要注释掉
        //加载界面
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());

        //获取数据表对象
        Box<StudentModel> studentModelBox = MyObjectBoxApplication.getBoxStore().boxFor(StudentModel.class);

        //添加StudentAdapter适配器
        list = new ArrayList<>();
        studentAdapter = new StudentAdapter(this, list, o -> {
            studentModelBox.remove(list.get((int)o));
            list.remove((int)o);
            studentAdapter.notifyDataSetChanged();
            Toasts("删除成功");
        });
        mainBinding.rvData.setLayoutManager(new GridLayoutManager(this, 1));
        mainBinding.rvData.setNestedScrollingEnabled(true);
        mainBinding.rvData.setAdapter(studentAdapter);

        //添加点击事件
        mainBinding.btnAdd.setOnClickListener(v -> {
            String name = mainBinding.etName.getText().toString();
            String age = mainBinding.etAge.getText().toString();
            StudentModel studentModel = new StudentModel(name, age);
            //添加进入数据库
            studentModelBox.put(studentModel);
            list.add(0, studentModel);
            studentAdapter.notifyDataSetChanged();
            Toasts("添加成功");
            //清空输入框
            mainBinding.etName.setText("");
            mainBinding.etAge.setText("");
        });

        //点击查询
        mainBinding.btnQuery.setOnClickListener(v -> {
            String name = mainBinding.etName.getText().toString();
            String age = mainBinding.etAge.getText().toString();

            //模糊查询
            list.clear();
            Query<StudentModel> query = studentModelBox.query()
                    //匹配查询用 equal
                    //.equal(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                    //.equal(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                    //模糊查询用 contains
                    .contains(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                    .contains(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
                    .build();
            list.addAll(query.find(list.size(), 2));

            //查询全部数据
            //list.addAll(studentModelBox.getAll());

            studentAdapter.notifyDataSetChanged();

            Toasts("查询成功");
        });

        //删除全部
        mainBinding.btnDel.setOnClickListener(v -> {
            //清空界面
            list.clear();
            studentAdapter.notifyDataSetChanged();
            //删除全部条码
            studentModelBox.removeAll();
        });

        //随机填充 100 条数据
        mainBinding.btnRandomFill.setOnClickListener(v -> {
            for(int i=0;i<100;i++){
                //添加进入数据库-随机生成姓名和年龄
                studentModelBox.put(new StudentModel(RandomWordUtils.randomWord(), String.valueOf((int)(Math.random()*100 + 1))));
            }
            Toasts("添加成功");
        });


        //下拉刷新
        mainBinding.srlControl.setRefreshHeader(new BezierRadarHeader(getApplicationContext()).setEnableHorizontalDrag(true));
        mainBinding.srlControl.setOnRefreshListener(refreshLayout -> {
            //启用刷新动画
            mainBinding.srlControl.setEnableRefresh(true);

            //查询第一条-从第 list.size() 条开始查,一次查10条,这里经过  list.clear() ,所以 list.size() 为 0
            list.clear();
            Query<StudentModel> query = studentModelBox.query().build();
            list.addAll(query.find(list.size(), 10));
            studentAdapter.notifyDataSetChanged();

            //结束刷新动画
            mainBinding.srlControl.finishRefresh();
        });
        //上拉加载
        mainBinding.srlControl.setOnLoadmoreListener(refreshLayout -> {
            //启用加载动画
            mainBinding.srlControl.setEnableLoadmore(true);

            //分页查询-从第 list.size() 条开始查,一次查10条
            Query<StudentModel> query = studentModelBox.query().build();
            list.addAll(query.find(list.size(), 10));
            studentAdapter.notifyDataSetChanged();

            //结束加载动画
            mainBinding.srlControl.finishLoadmore();
        });

    }

    //Toast
    public void Toasts(String content){
        Toast.makeText(MyObjectBoxApplication.getMyObjectBoxApplication(), content, Toast.LENGTH_SHORT).show();
    }

}

三、adapter代码

        1、adapter_student.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp"
    android:background="#FFFFFF"
    android:layout_marginBottom="1dp"
    android:id="@+id/llClick">

    <TextView
        android:id="@+id/tvId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ID:"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name:"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="age:"
        android:textColor="#000000"
        android:textSize="18sp" />


</LinearLayout>

        2、StudentAdapter

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xolo.myobjectbox.databinding.AdapterStudentBinding;

import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {

    private Context context;
    private List<StudentModel> list;
    private ClickInterface clickInterface;

    public StudentAdapter(Context context, List<StudentModel> list, ClickInterface clickInterface) {
        this.context = context;
        this.list = list;
        this.clickInterface = clickInterface;
    }

    @NonNull
    @Override
    public StudentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //界面设置
        AdapterStudentBinding studentBinding = AdapterStudentBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ViewHolder(studentBinding);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull StudentAdapter.ViewHolder holder, int position) {
        holder.studentBinding.tvId.setText("ID:"+list.get(position).getId());
        holder.studentBinding.tvName.setText("姓名:"+list.get(position).getName());
        holder.studentBinding.tvAge.setText("年龄:"+list.get(position).getAge());
        holder.studentBinding.llClick.setOnClickListener(v -> clickInterface.ClickOnThe(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        系统依据 activity_main.xml 自动生成的 AdapterStudentBinding 类,通过 ActivityMainBinding 可以获取对应的控件
        AdapterStudentBinding studentBinding;
        public ViewHolder(@NonNull AdapterStudentBinding itemView) {
            super(itemView.getRoot());
            studentBinding = itemView;
        }
    }
}

四、RandomWordUtils 随机生成姓名代码

//随机生成英文串串
public class RandomWordUtils {

    public static String randomWord() {
        int length = 12 + (int) (Math.random() * 9);
        String word = "";
        for (int i = 0; i < length; i++) {
            word += (char) randomChar();
        }
        return word;
    }

    private static byte randomChar() {
        int flag = (int) (Math.random() * 2);// 0小写字母1大写字母
        byte resultBt;
        if (flag == 0) {
            byte bt = (byte) (Math.random() * 26);// 0 <= bt < 26
            resultBt = (byte) (65 + bt);
        } else {
            byte bt = (byte) (Math.random() * 26);// 0 <= bt < 26
            resultBt = (byte) (97 + bt);
        }
        return resultBt;
    }
}

五、StudentModel 代码

注意事项:ObjectBox 需要创建任意一个 @Entity class 否则会一直提示找不到MyObjectBox
需要rebuild project 项目,此时就可以在Application下使用MyObjectBox了

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

//ObjectBox 需要创建任意一个 @Entity class 否则会一直提示找不到MyObjectBox
//需要rebuild project 项目,此时就可以在Application下使用MyObjectBox了
@Entity
public class StudentModel {

    //@Id 也是 ObjectBox 必须添加的
    @Id
    private long id;
    private String name;
    private String age;

    public StudentModel() {
    }

    public StudentModel(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

六、MyObjectBoxApplication 代码:需要在 AndroidManifest.xml 引入

import android.app.Application;
import android.util.Log;


import io.objectbox.BoxStore;
import io.objectbox.android.AndroidObjectBrowser;

public class MyObjectBoxApplication extends Application {

    private static BoxStore boxStore;
    private static MyObjectBoxApplication myObjectBoxApplication;

    @Override
    public void onCreate() {
        super.onCreate();

        myObjectBoxApplication = this;

        //初始化 ObjectBox
        boxStore = MyObjectBox.builder().androidContext(MyObjectBoxApplication.this).build();
        if (BuildConfig.DEBUG) {
            new AndroidObjectBrowser(boxStore).start(this);
        }

        Log.d("App", "Using ObjectBox " + BoxStore.getVersion() + " (" + BoxStore.getVersionNative() + ")");
    }

    public static MyObjectBoxApplication getMyObjectBoxApplication() {
        return myObjectBoxApplication;
    }

    public static BoxStore getBoxStore() {
        return boxStore;
    }
}

七、AndroidManifest.xml 代码

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

    <application
        android:name=".MyObjectBoxApplication"
        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>

八、ClickInterface 代码

public interface ClickInterface {
    void ClickOnThe(Object o);
}

九、代码界面展示

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值