• ObjectBox 初探


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

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

    ObjectBox  添加数据

    ObjectBox  随机添加

    ObjectBox 模糊查询

    ObjectBox  匹配查询

    ObjectBox  查询全部

    ObjectBox  删除全部

    ObjectBox  分页查询

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

    界面展示

    正文代码

    一、build.gradle配置: ObjectBox 相关

            1、项目 build.gradle

    1. // Top-level build file where you can add configuration options common to all sub-projects/modules.
    2. buildscript {
    3. //ObjectBox 相关
    4. ext.objectboxVersion = "3.2.1"
    5. repositories {
    6. google()
    7. jcenter()
    8. //ObjectBox 相关
    9. mavenCentral()
    10. }
    11. dependencies {
    12. classpath "com.android.tools.build:gradle:4.0.1"
    13. //ObjectBox 相关
    14. classpath("io.objectbox:objectbox-gradle-plugin:$objectboxVersion")
    15. }
    16. }
    17. allprojects {
    18. repositories {
    19. google()
    20. jcenter()
    21. }
    22. }
    23. task clean(type: Delete) {
    24. delete rootProject.buildDir
    25. }

            2、app build.gradle

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

    1. apply plugin: 'com.android.application'
    2. android {
    3. compileSdkVersion 32
    4. buildToolsVersion "32.0.0"
    5. defaultConfig {
    6. applicationId "com.xolo.myobjectbox"
    7. minSdkVersion 16
    8. targetSdkVersion 32
    9. versionCode 1
    10. versionName "1.0"
    11. testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    12. }
    13. buildTypes {
    14. release {
    15. minifyEnabled false
    16. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    17. }
    18. }
    19. buildFeatures {
    20. viewBinding = true
    21. }
    22. compileOptions {
    23. sourceCompatibility JavaVersion.VERSION_1_8
    24. targetCompatibility JavaVersion.VERSION_1_8
    25. }
    26. }
    27. dependencies {
    28. implementation fileTree(dir: "libs", include: ["*.jar"])
    29. implementation 'androidx.appcompat:appcompat:1.3.1'
    30. implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    31. testImplementation 'junit:junit:4.12'
    32. androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    33. androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    34. //ButterKnife
    35. /*implementation 'com.jakewharton:butterknife:10.2.3'
    36. annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'*/
    37. //RecyclerView 列表
    38. implementation 'androidx.recyclerview:recyclerview:1.2.0-beta01'
    39. //SmartRefreshLayout 下拉刷新 上拉加载
    40. implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7'
    41. implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.4-7'
    42. }
    43. //ObjectBox 相关
    44. apply plugin: "io.objectbox" // Add after other plugins.

    二、增、删、查相关代码

            1、activity_main.xml

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. xmlns:app="http://schemas.android.com/apk/res-auto"
    3. xmlns:tools="http://schemas.android.com/tools"
    4. android:layout_width="match_parent"
    5. android:layout_height="match_parent"
    6. android:orientation="vertical"
    7. tools:context=".MainActivity">
    8. <LinearLayout
    9. android:layout_width="match_parent"
    10. android:layout_height="wrap_content"
    11. android:orientation="vertical">
    12. <EditText
    13. android:id="@+id/etName"
    14. android:layout_width="match_parent"
    15. android:layout_height="wrap_content"
    16. android:hint="名称"
    17. android:textColor="#000000"
    18. android:textSize="18sp" />
    19. <EditText
    20. android:id="@+id/etAge"
    21. android:layout_width="match_parent"
    22. android:layout_height="wrap_content"
    23. android:hint="年龄"
    24. android:inputType="number"
    25. android:textColor="#000000"
    26. android:textSize="18sp" />
    27. <LinearLayout
    28. android:layout_width="match_parent"
    29. android:layout_height="wrap_content"
    30. android:orientation="horizontal">
    31. <Button
    32. android:id="@+id/btnAdd"
    33. android:layout_width="0dp"
    34. android:layout_weight="1"
    35. android:layout_height="wrap_content"
    36. android:text="添加" />
    37. <Button
    38. android:id="@+id/btnQuery"
    39. android:layout_width="0dp"
    40. android:layout_weight="1"
    41. android:layout_height="wrap_content"
    42. android:layout_marginLeft="5dp"
    43. android:text="查询" />
    44. LinearLayout>
    45. LinearLayout>
    46. <TextView
    47. android:layout_width="match_parent"
    48. android:layout_height="40dp"
    49. android:background="#D9F8F5"
    50. android:gravity="center|left"
    51. android:paddingLeft="20dp"
    52. android:text="数据列表-点击可删、下拉刷新、上拉加载"
    53. android:textColor="#000000"
    54. android:textSize="18sp" />
    55. <com.scwang.smartrefresh.layout.SmartRefreshLayout
    56. android:id="@+id/srlControl"
    57. android:layout_width="match_parent"
    58. android:layout_height="0dp"
    59. android:layout_weight="1"
    60. app:srlAccentColor="#00000000"
    61. app:srlEnablePreviewInEditMode="true"
    62. app:srlPrimaryColor="#00000000">
    63. <com.scwang.smartrefresh.layout.header.ClassicsHeader
    64. android:layout_width="match_parent"
    65. android:layout_height="wrap_content" />
    66. <androidx.recyclerview.widget.RecyclerView
    67. android:id="@+id/rvData"
    68. android:layout_width="match_parent"
    69. android:layout_height="match_parent" />
    70. <com.scwang.smartrefresh.layout.footer.ClassicsFooter
    71. android:layout_width="match_parent"
    72. android:layout_height="wrap_content" />
    73. com.scwang.smartrefresh.layout.SmartRefreshLayout>
    74. <LinearLayout
    75. android:layout_width="match_parent"
    76. android:layout_height="wrap_content"
    77. android:orientation="horizontal">
    78. <Button
    79. android:id="@+id/btnRandomFill"
    80. android:layout_width="0dp"
    81. android:layout_weight="1"
    82. android:layout_height="wrap_content"
    83. android:text="随机填充 100 条" />
    84. <Button
    85. android:id="@+id/btnDel"
    86. android:layout_width="0dp"
    87. android:layout_weight="1"
    88. android:layout_height="wrap_content"
    89. android:layout_marginLeft="5dp"
    90. android:text="删除全部" />
    91. LinearLayout>
    92. LinearLayout>

            2、MainActivity 

    1. import androidx.appcompat.app.AppCompatActivity;
    2. import androidx.recyclerview.widget.GridLayoutManager;
    3. import android.os.Bundle;
    4. import android.widget.Toast;
    5. import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
    6. import com.xolo.myobjectbox.databinding.ActivityMainBinding;
    7. import java.util.ArrayList;
    8. import java.util.List;
    9. import io.objectbox.Box;
    10. import io.objectbox.query.Query;
    11. import io.objectbox.query.QueryBuilder;
    12. public class MainActivity extends AppCompatActivity {
    13. //系统依据 activity_main.xml 自动生成的 ActivityMainBinding 类,通过 ActivityMainBinding 可以获取对应的控件
    14. ActivityMainBinding mainBinding;
    15. private StudentAdapter studentAdapter;
    16. private List list;
    17. @Override
    18. protected void onCreate(Bundle savedInstanceState) {
    19. super.onCreate(savedInstanceState);
    20. //setContentView(R.layout.activity_main); -需要注释掉
    21. //加载界面
    22. mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
    23. setContentView(mainBinding.getRoot());
    24. //获取数据表对象
    25. Box studentModelBox = MyObjectBoxApplication.getBoxStore().boxFor(StudentModel.class);
    26. //添加StudentAdapter适配器
    27. list = new ArrayList<>();
    28. studentAdapter = new StudentAdapter(this, list, o -> {
    29. studentModelBox.remove(list.get((int)o));
    30. list.remove((int)o);
    31. studentAdapter.notifyDataSetChanged();
    32. Toasts("删除成功");
    33. });
    34. mainBinding.rvData.setLayoutManager(new GridLayoutManager(this, 1));
    35. mainBinding.rvData.setNestedScrollingEnabled(true);
    36. mainBinding.rvData.setAdapter(studentAdapter);
    37. //添加点击事件
    38. mainBinding.btnAdd.setOnClickListener(v -> {
    39. String name = mainBinding.etName.getText().toString();
    40. String age = mainBinding.etAge.getText().toString();
    41. StudentModel studentModel = new StudentModel(name, age);
    42. //添加进入数据库
    43. studentModelBox.put(studentModel);
    44. list.add(0, studentModel);
    45. studentAdapter.notifyDataSetChanged();
    46. Toasts("添加成功");
    47. //清空输入框
    48. mainBinding.etName.setText("");
    49. mainBinding.etAge.setText("");
    50. });
    51. //点击查询
    52. mainBinding.btnQuery.setOnClickListener(v -> {
    53. String name = mainBinding.etName.getText().toString();
    54. String age = mainBinding.etAge.getText().toString();
    55. //模糊查询
    56. list.clear();
    57. Query query = studentModelBox.query()
    58. //匹配查询用 equal
    59. //.equal(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
    60. //.equal(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
    61. //模糊查询用 contains
    62. .contains(StudentModel_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE)
    63. .contains(StudentModel_.age, age, QueryBuilder.StringOrder.CASE_INSENSITIVE)
    64. .build();
    65. list.addAll(query.find(list.size(), 2));
    66. //查询全部数据
    67. //list.addAll(studentModelBox.getAll());
    68. studentAdapter.notifyDataSetChanged();
    69. Toasts("查询成功");
    70. });
    71. //删除全部
    72. mainBinding.btnDel.setOnClickListener(v -> {
    73. //清空界面
    74. list.clear();
    75. studentAdapter.notifyDataSetChanged();
    76. //删除全部条码
    77. studentModelBox.removeAll();
    78. });
    79. //随机填充 100 条数据
    80. mainBinding.btnRandomFill.setOnClickListener(v -> {
    81. for(int i=0;i<100;i++){
    82. //添加进入数据库-随机生成姓名和年龄
    83. studentModelBox.put(new StudentModel(RandomWordUtils.randomWord(), String.valueOf((int)(Math.random()*100 + 1))));
    84. }
    85. Toasts("添加成功");
    86. });
    87. //下拉刷新
    88. mainBinding.srlControl.setRefreshHeader(new BezierRadarHeader(getApplicationContext()).setEnableHorizontalDrag(true));
    89. mainBinding.srlControl.setOnRefreshListener(refreshLayout -> {
    90. //启用刷新动画
    91. mainBinding.srlControl.setEnableRefresh(true);
    92. //查询第一条-从第 list.size() 条开始查,一次查10条,这里经过 list.clear() ,所以 list.size() 为 0
    93. list.clear();
    94. Query query = studentModelBox.query().build();
    95. list.addAll(query.find(list.size(), 10));
    96. studentAdapter.notifyDataSetChanged();
    97. //结束刷新动画
    98. mainBinding.srlControl.finishRefresh();
    99. });
    100. //上拉加载
    101. mainBinding.srlControl.setOnLoadmoreListener(refreshLayout -> {
    102. //启用加载动画
    103. mainBinding.srlControl.setEnableLoadmore(true);
    104. //分页查询-从第 list.size() 条开始查,一次查10条
    105. Query query = studentModelBox.query().build();
    106. list.addAll(query.find(list.size(), 10));
    107. studentAdapter.notifyDataSetChanged();
    108. //结束加载动画
    109. mainBinding.srlControl.finishLoadmore();
    110. });
    111. }
    112. //Toast
    113. public void Toasts(String content){
    114. Toast.makeText(MyObjectBoxApplication.getMyObjectBoxApplication(), content, Toast.LENGTH_SHORT).show();
    115. }
    116. }

    三、adapter代码

            1、adapter_student.xml

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2. android:layout_width="match_parent"
    3. android:layout_height="wrap_content"
    4. android:orientation="vertical"
    5. android:padding="5dp"
    6. android:background="#FFFFFF"
    7. android:layout_marginBottom="1dp"
    8. android:id="@+id/llClick">
    9. <TextView
    10. android:id="@+id/tvId"
    11. android:layout_width="match_parent"
    12. android:layout_height="wrap_content"
    13. android:text="ID:"
    14. android:textColor="#000000"
    15. android:textSize="18sp" />
    16. <TextView
    17. android:id="@+id/tvName"
    18. android:layout_width="match_parent"
    19. android:layout_height="wrap_content"
    20. android:text="name:"
    21. android:textColor="#000000"
    22. android:textSize="18sp" />
    23. <TextView
    24. android:id="@+id/tvAge"
    25. android:layout_width="match_parent"
    26. android:layout_height="wrap_content"
    27. android:text="age:"
    28. android:textColor="#000000"
    29. android:textSize="18sp" />
    30. LinearLayout>

            2、StudentAdapter

    1. import android.annotation.SuppressLint;
    2. import android.content.Context;
    3. import android.view.LayoutInflater;
    4. import android.view.ViewGroup;
    5. import androidx.annotation.NonNull;
    6. import androidx.recyclerview.widget.RecyclerView;
    7. import com.xolo.myobjectbox.databinding.AdapterStudentBinding;
    8. import java.util.List;
    9. public class StudentAdapter extends RecyclerView.Adapter.ViewHolder> {
    10. private Context context;
    11. private List<StudentModel> list;
    12. private ClickInterface clickInterface;
    13. public StudentAdapter(Context context, List<StudentModel> list, ClickInterface clickInterface) {
    14. this.context = context;
    15. this.list = list;
    16. this.clickInterface = clickInterface;
    17. }
    18. @NonNull
    19. @Override
    20. public StudentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    21. //界面设置
    22. AdapterStudentBinding studentBinding = AdapterStudentBinding.inflate(LayoutInflater.from(context), parent, false);
    23. return new ViewHolder(studentBinding);
    24. }
    25. @SuppressLint("SetTextI18n")
    26. @Override
    27. public void onBindViewHolder(@NonNull StudentAdapter.ViewHolder holder, int position) {
    28. holder.studentBinding.tvId.setText("ID:"+list.get(position).getId());
    29. holder.studentBinding.tvName.setText("姓名:"+list.get(position).getName());
    30. holder.studentBinding.tvAge.setText("年龄:"+list.get(position).getAge());
    31. holder.studentBinding.llClick.setOnClickListener(v -> clickInterface.ClickOnThe(position));
    32. }
    33. @Override
    34. public int getItemCount() {
    35. return list.size();
    36. }
    37. public class ViewHolder extends RecyclerView.ViewHolder {
    38. 系统依据 activity_main.xml 自动生成的 AdapterStudentBinding 类,通过 ActivityMainBinding 可以获取对应的控件
    39. AdapterStudentBinding studentBinding;
    40. public ViewHolder(@NonNull AdapterStudentBinding itemView) {
    41. super(itemView.getRoot());
    42. studentBinding = itemView;
    43. }
    44. }
    45. }

    四、RandomWordUtils 随机生成姓名代码

    1. //随机生成英文串串
    2. public class RandomWordUtils {
    3. public static String randomWord() {
    4. int length = 12 + (int) (Math.random() * 9);
    5. String word = "";
    6. for (int i = 0; i < length; i++) {
    7. word += (char) randomChar();
    8. }
    9. return word;
    10. }
    11. private static byte randomChar() {
    12. int flag = (int) (Math.random() * 2);// 0小写字母1大写字母
    13. byte resultBt;
    14. if (flag == 0) {
    15. byte bt = (byte) (Math.random() * 26);// 0 <= bt < 26
    16. resultBt = (byte) (65 + bt);
    17. } else {
    18. byte bt = (byte) (Math.random() * 26);// 0 <= bt < 26
    19. resultBt = (byte) (97 + bt);
    20. }
    21. return resultBt;
    22. }
    23. }

    五、StudentModel 代码

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

    1. import io.objectbox.annotation.Entity;
    2. import io.objectbox.annotation.Id;
    3. //ObjectBox 需要创建任意一个 @Entity class 否则会一直提示找不到MyObjectBox
    4. //需要rebuild project 项目,此时就可以在Application下使用MyObjectBox了
    5. @Entity
    6. public class StudentModel {
    7. //@Id 也是 ObjectBox 必须添加的
    8. @Id
    9. private long id;
    10. private String name;
    11. private String age;
    12. public StudentModel() {
    13. }
    14. public StudentModel(String name, String age) {
    15. this.name = name;
    16. this.age = age;
    17. }
    18. public long getId() {
    19. return id;
    20. }
    21. public void setId(long id) {
    22. this.id = id;
    23. }
    24. public String getName() {
    25. return name;
    26. }
    27. public void setName(String name) {
    28. this.name = name;
    29. }
    30. public String getAge() {
    31. return age;
    32. }
    33. public void setAge(String age) {
    34. this.age = age;
    35. }
    36. }

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

    1. import android.app.Application;
    2. import android.util.Log;
    3. import io.objectbox.BoxStore;
    4. import io.objectbox.android.AndroidObjectBrowser;
    5. public class MyObjectBoxApplication extends Application {
    6. private static BoxStore boxStore;
    7. private static MyObjectBoxApplication myObjectBoxApplication;
    8. @Override
    9. public void onCreate() {
    10. super.onCreate();
    11. myObjectBoxApplication = this;
    12. //初始化 ObjectBox
    13. boxStore = MyObjectBox.builder().androidContext(MyObjectBoxApplication.this).build();
    14. if (BuildConfig.DEBUG) {
    15. new AndroidObjectBrowser(boxStore).start(this);
    16. }
    17. Log.d("App", "Using ObjectBox " + BoxStore.getVersion() + " (" + BoxStore.getVersionNative() + ")");
    18. }
    19. public static MyObjectBoxApplication getMyObjectBoxApplication() {
    20. return myObjectBoxApplication;
    21. }
    22. public static BoxStore getBoxStore() {
    23. return boxStore;
    24. }
    25. }

    七、AndroidManifest.xml 代码

    1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    2. package="com.xolo.myobjectbox">
    3. <application
    4. android:name=".MyObjectBoxApplication"
    5. android:allowBackup="true"
    6. android:icon="@mipmap/ic_launcher"
    7. android:label="@string/app_name"
    8. android:roundIcon="@mipmap/ic_launcher_round"
    9. android:supportsRtl="true"
    10. android:theme="@style/AppTheme">
    11. <activity android:name=".MainActivity">
    12. <intent-filter>
    13. <action android:name="android.intent.action.MAIN" />
    14. <category android:name="android.intent.category.LAUNCHER" />
    15. intent-filter>
    16. activity>
    17. application>
    18. manifest>

    八、ClickInterface 代码

    1. public interface ClickInterface {
    2. void ClickOnThe(Object o);
    3. }

    九、代码界面展示

  • 相关阅读:
    直流无刷电机PID控制
    浅析搭建视频监控汇聚平台的必要性及场景应用
    【SpingBoot定时任务】Spring自带@Scheduled、异步多线程@Async、quartz框架 定时任务示例
    分享一道手搓链表玩矩阵的算法题
    pycharm/vscode 配置black和isort
    【Docker】Docker File
    仿牛客网项目第五,六章:异步消息系统和分布式搜索引擎(详细步骤和思路)
    结构体的内存对齐
    去除社区版本 idea 没有添加括号的报红
    UE427_Logging
  • 原文地址:https://blog.csdn.net/weixin_41454168/article/details/126320529