Androidandroid 集结号

Room中List<>使用详解

2018-01-09  本文已影响299人  王诛魔Phy

手摸手教你在Room中使用List<Object>.

实际项目有很多这样的结构:

{
  "id": "001",
  "name": "王诛魔",
  "age": 2018,
  "books": [
    {
      "bookId": 10081,
      "userId": 1,
      "book": "断罪小学",
      "desc": "漫画讲述了李杀神、王诛魔和刘斩仙三位少年,为了十万小学生的未来、为了改变被诅咒的命运,相聚在狼牙区飞虎路私立断罪小学,誓死打败四年级的魔神赵日天的故事。"
    },
    {
      "bookId": 10088,
      "userId": 1,
      "book": "狂霸天下之断罪学园",
      "desc": "《狂霸天下之断罪学园》,后来因为名字太长,而且“学园”和“学院”容易混淆的原因而改名。"
    }
  ]
}

也就是,类似books这样的,List<Object>作为一个元素存在.

下面就以上面的结构为例,做一个简单的演示,按照最简答的方法实现.

1.添加依赖

https://developer.android.google.cn/topic/libraries/architecture/adding-components.html

值得注意的是,如果你在kotlin中使用

apply plugin: 'kotlin-kapt'
...
dependencies{
  
  ...
    //这个无法生成代码,要用下面的那一条,不要疏忽忘掉了.
    //annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
    
    kapt "android.arch.persistence.room:compiler:1.0.0"
}

一定记得使用kapt,要不然就会遇到这个BUG.

2.创建表

3.Dao实现

/**
 * If you have any questions, you can contact by email { wangzhumoo@gmail.com}
 * @author 王诛魔 2018/1/3 下午4:20
 */
@Dao
public abstract class UserAndBookDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void insert(User user);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public abstract void insert(List<Book> books);

    @Transaction
    public void insert(UserAndBook userAndBook){
        insert(userAndBook.userEntity);
        insert(userAndBook.books);
    }
  
    @Query("SELECT * FROM users")
    public abstract List<UserAndBook> getAll();
}

insert(User user); ,insert(List<Book> books);

两个方法,也可以私有化,只对外提供insert(UserAndBook userAndBook)

最近换公司项目的数据库,用sql,真的有意思,可以很方便的实现很多功能

4.建立数据库

/**
 * If you have any questions, you can contact by email { wangzhumoo@gmail.com}
 * @author 王诛魔 2017/10/24 上午10:13
 * 数据库
 */
@Database(entities = {Book.class, User.class}, 
          version = 1, exportSchema = false)
public abstract class AppDB extends RoomDatabase {
    private static final String TAG = "AppDB";

    /**
     * 数据库实例
     */
    private static AppDB sInstance;
    private static String DATABASE_NAME = "developer.db";
    private ObservableBoolean mIsDatabaseCreated = new ObservableBoolean(false);

    
    public abstract UserAndBookDao userbook();

    /**
     * 单例
     * @param context
     * @return
     */
    public static AppDB getInstance(Context context) {
        if (sInstance == null) {
            synchronized (AppDB.class) {
                if (sInstance == null) {
                    sInstance = buildDatabase(context);
                    sInstance.updateDatabaseCreated(context);
                }
            }
        }
        return sInstance;
    }

    /**
     * Build the database.
     * creates a new instance of the database.
     */
    private static AppDB buildDatabase(Context appContext) {
         AppDB appDB = Room.databaseBuilder(appContext, AppDB.class, DATABASE_NAME)
                .addCallback(new Callback() {
                    @Override
                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
                        super.onCreate(db);
                        AppDB database = AppDB.getInstance(appContext);
                        database.setDatabaseCreated();
                    }

                    @Override
                    public void onOpen(@NonNull SupportSQLiteDatabase db) {
                        super.onOpen(db);
                        Log.e(TAG, "onOpen: " + db.getPath());
                    }
                }).build();

        return appDB;
    }

    /**
     * Check whether the database already exists and expose it via 
     */
    private void updateDatabaseCreated(final Context context) {
        if (context.getDatabasePath(DATABASE_NAME).exists()) {
            setDatabaseCreated();
        }
    }

    private void setDatabaseCreated() {
        mIsDatabaseCreated.set(true);
    }

    public ObservableBoolean getDatabaseCreated() {
        return mIsDatabaseCreated;
    }
}

为了方便使用,在Application中添加了

public static AppDB getDatabase() {
    return AppDB.getInstance(context);
}

5.使用

这里的使用方式,不建议使用,太粗暴了.

可以学学Demo,Google出的googlesamples/android-architecture-components

class RoomActivity : BindingActivity<ActivityRoomBinding, RoomViewModel>() {
    val gson = Gson()

    override fun getBundle(extras: Bundle) {
    }

    override fun layoutID(): Int = R.layout.activity_room

    override fun initViews(savedInstanceState: Bundle?) {
        
        //点击事件  ADD按钮,添加数据到数据库
        mBindingView.button.setOnClickListener({
            val userBook = UserAndBook()
            val jsonStr = FileUtils.getJson(this, "data.txt")
            val objectJson = JsonParser().parse(jsonStr).asJsonObject

            //获取用户
            val user = objectJson.get("user")
            userBook.userEntity = gson.fromJson<User>(user, User::class.java)

            //保存用户
            Observable
                .empty<Any>()
                .observeOn(Schedulers.io())
                .subscribe(object : EmptyObserver<Any?>() {
                    override fun onComplete() {
                        App.getDatabase().userbook().insert(userBook.userEntity)
                    }
                })

            //获取书籍
            val books = objectJson.get("books")
            userBook.books = gson.fromJson<ArrayList<Book>>
                                (books, object : TypeToken<List<Book>>() {}.type)
            //保存书籍
            Observable
                .empty<Any>()
                .observeOn(Schedulers.io())
                .subscribe(object : EmptyObserver<Any?>() {
                     override fun onComplete() {
                        App.getDatabase().userbook().insert(userBook.books)
                    }
                })
        })


        //点击事件,按钮QUERY   查询数据
        mBindingView.button2.setOnClickListener {
            Flowable.create(FlowableOnSubscribe<List<UserAndBook>> { e ->
                val userBook = App.getDatabase().userbook().all
                e.onNext(userBook)
                e.onComplete()
            }, BackpressureStrategy.DROP)
                    .compose(DatabaseTransformer())
                    .subscribe(object : DatabaseSubscriber<List<UserAndBook>>() {
                        override fun onNext(userAndBooks: List<UserAndBook>) {
                            mBindingView.data = userAndBooks[0]
                        }
                    })
        }

    }
}
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="com.wangzhumo.app.data.UserAndBook"/>
        <import type="com.wangzhumo.app.data.User"/>
        <import type="com.wangzhumo.app.data.Book"/>
        <variable
            name="data"
            type="com.wangzhumo.app.data.UserAndBook"/>
    </data>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="57dp"
            android:layout_marginStart="57dp"
            android:layout_marginTop="125dp"
            android:text="Add" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/button"
            android:layout_alignBottom="@+id/button"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_marginEnd="56dp"
            android:layout_marginRight="56dp"
            android:text="Query" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/button"
            android:layout_marginTop="68dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="36dp"
                android:layout_marginStart="36dp"
                android:layout_marginTop="32dp"
                android:text="@{data.userEntity.name}" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView"
                android:layout_alignStart="@+id/textView"
                android:layout_below="@+id/textView"
                android:layout_marginTop="41dp"
                android:text="@{data.books.get(0).book}" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView2"
                android:layout_alignStart="@+id/textView2"
                android:layout_centerVertical="true"
                android:text="@{data.books.get(0).desc}" />
        </RelativeLayout>
    </RelativeLayout>
</layout>

上一篇下一篇

猜你喜欢

热点阅读