在Android中使用RxJava2插入SQLiteDatabase [英] Insert into SQLiteDatabase using RxJava2 in Android

查看:64
本文介绍了在Android中使用RxJava2插入SQLiteDatabase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 android 中学习 RxJava2.谁能解释一下我们如何使用 RxJava2 将数据插入到 SQLiteDatabase 中.这是我尝试使用的代码示例,但它将数据插入数据库六次;

I am learning RxJava2 in android. Can Anyone explain me how can we insert Data into SQLiteDatabase using RxJava2. Here a code sample i am trying to use, but it inserts the data Six Times into the Database;

//点击

getCompletableObservable()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(getCompletableObserver());

//可观察

private Completable getCompletableObservable(){
    return Completable.create(new CompletableOnSubscribe() {
        @Override
        public void subscribe(CompletableEmitter emitter) throws Exception {
            addData();
            if(!emitter.isDisposed())
                emitter.onComplete();
        }
    });
}

//观察者

CompletableObserver getCompletableObserver(){
    return new CompletableObserver() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onComplete() {
            showMessage("Student Added Sucessfully");
        }

        @Override
        public void onError(Throwable e) {
            showMessage(e.getMessage()+"");
        }
    };
}

//添加方法

try {
        DatabaseHelper db = new DatabaseHelper(DemoRxJava.this);
        db.open();
        String c = db.AddData(new Student(random.nextInt(1000)+"",SName.getText().toString(),SContact.getText().toString(),SEmail.getText().toString()));
        Log.d("StudentData",c);
        db.close();
    }catch (Exception e){

    }

推荐答案

使用 Room Persistence图书馆.创建它是为了简化与数据库的交互.它支持使用 RxJava 和 LiveData 包装数据.

Use Room Persistence library. It is created to simplify interaction with database. It supports wrapping data with RxJava as well as LiveData.

查看文档以开始使用

基本上,您要创建实体类,该类将抽象您的表并表示单行对象.例如,这将名为 users 的表的用户实体和 uid 显示为 PK.

Basically you want to create the Entity class that will abstract your table and will represent a single row object. For example this shows user Entity for table named users and uid as PK.

@Entity(tableName="users")
public class User {
    @PrimaryKey
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    // Getters and setters are ignored for brevity,
    // but they're required for Room to work.
}

然后定义包含查询定义的 DAO 类.您将使用此接口的对象进行实际查询.Room 将为您制作具体课程

Then you define your DAO class that will contain your query definitions. You will use object of this interface to make actual queries. Room will make concrete class for you

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

最后,您创建了将用于实际查询数据库的数据库对象.这个类是抽象的,Room 也会为你创建具体的类.它包含创建 DAO 的方法,您可以随意命名方法.

Finally you created your database object that you will use to actually query the database. The class is abstract and Room will also create the concrete class for you. It contains methods for creating DAOs and you can name methods anything you want.

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

现在假设我

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "databaseName.db").build(); //Most of the time I have used this, it is a Singleton.

List<User> users = db.userDao().getAll();
for(User u : users)
{
    Log.d("SQLITE_ROOM_DATA", u.firstName);
}

这里我们返回了简单的 List 但 Room 允许你用 RxJava Observables 包裹它们,比如 Flowable> 或 Architecture 组件 livedata LiveData>

Here we returned simple List<User> but Room allows you to wrap them with RxJava Observables like Flowable<List<User>> or Architecture component livedata LiveData<List<User>>

要使用 Room,您需要将依赖项添加到您的 gradle 中,如下所示:

To use Room you need to add the dependencies to your gradle as follows:

dependencies {
    def room_version = "1.1.0" // or, for latest rc, use "1.1.1-rc1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version"

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"
    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}

这篇关于在Android中使用RxJava2插入SQLiteDatabase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆