从Room DB

时间:2019-06-20 20:25:30

标签: android android-room android-threading

如果父母中有通过外键关联的孩子,我将试图阻止其从Room DB中删除。

我正在研究学位追踪器。如果有一个学期的课程,则该学期不能删除。如果该学期没有课程,则可以删除该学期。我正在尝试获取具有相关术语ID的课程数量,并使用简单的if语句删除没有课程的术语,如果有该课程的课程则使用弹出警报,并指示用户删除课程删除该字词之前。

来自TermEditorActivity.java

switch(item.getItemId()){
...
case R.id.delete_term:

int coursecount = queryCourses(termIdSelected);

    if(coursecount > 0){
                    AlertDialog.Builder a_builder = new 
                    AlertDialog.Builder(TermEditorActivity.this);
                    a_builder.setMessage("Courses are assigned for this 
                    term!\n\nYou must remove all courses" +
                            "prior to deleting this term.")
                            .setCancelable(false)
                            .setPositiveButton("Okay", new 
                             DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, 
                                int which) {

                                    finish();
                                }
                            });
                    AlertDialog deleteAllAlert = a_builder.create();
                    deleteAllAlert.setTitle("CANNOT DELETE TERM!!!");
                    deleteAllAlert.show();
                    return true;
                }else{
                    mViewModel.deleteTerm();
                    startActivity(new Intent(TermEditorActivity.this, 
                    MainActivity.class));
                }
...
public int queryCourses(int term) {
        int course = mViewModel.queryCourses(term);
        return course;
    }

从ViewModel:

public int queryCourses(final int term) {
        int course = mRepository.queryCourses(term);
        return course;
    }

从AppRepository(这是我认为事情崩溃的地方):

public int queryCourses(final int term) {
//        executor.execute(new Runnable() {
//            @Override
//            public void run() {
              return count = courseDb.termDao().queryCourses(term);
//            }
//        });
//            return count;
//        }

or with threading:

 public int queryCourses(final int term) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
              count = courseDb.termDao().queryCourses(term);
            }
        });
            return count;
        }

来自TermDAO:

@Query("SELECT COUNT(*) FROM course WHERE term_id = :termIdSelected")
    int queryCourses(int termIdSelected);

这将导致运行时错误,当按下删除按钮时会崩溃。这个概念很简单-使用术语的id来查询课程数据库,以获取带有术语id外键的课程数。如果没有,请删除该术语并返回到术语列表。如果有课程(计数> 0),则警告用户并完成操作而不会删除。

没有线程的异常:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

使用线程时,它将删除有或没有课程的术语,并且当该术语附加课程时,不会显示任何警报。在调试模式下运行,当有一门课程时,coursecount返回0,因此查询无法正常运行。

是否需要做一些事情才能从线程中获取值?

这是针对RESTRICT约束引发SQLiteConstraintException时运行时错误的崩溃日志。即使使用Exception也不会被捕获。

E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
    Process: com.mattspriggs.termtest, PID: 23927
    android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 1811 SQLITE_CONSTRAINT_TRIGGER)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:784)
        at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
        at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
        at android.arch.persistence.db.framework.FrameworkSQLiteStatement.executeUpdateDelete(FrameworkSQLiteStatement.java:45)
        at android.arch.persistence.room.EntityDeletionOrUpdateAdapter.handle(EntityDeletionOrUpdateAdapter.java:70)
        at com.mattspriggs.termtest.database.TermDao_Impl.deleteTerm(TermDao_Impl.java:144)
        at com.mattspriggs.termtest.database.AppRepository$4.run(AppRepository.java:83)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

1 个答案:

答案 0 :(得分:1)

Room实际上支持此行为:

在为子实体定义foreign键时,只需将操作onDelete设置为RESTRICT即可,而父项中有与之相关的子项则无法删除。

您的子类应如下所示:

@Entity(tableName = "child_table",foreignKeys ={
    @ForeignKey(onDelete = RESTRICT,entity = ParentEntity.class,
    parentColumns = "uid",childColumns = "parentId")},
    indices = {
            @Index("parentId"),
    })
public class ChildEntity {
    @PrimaryKey
    public String id;
    public String parentId;
}

您的父类如下:

@Entity
public class ParentEntity{
    @PrimaryKey
    public String uid;
}

您可以检查here以获得有关如何定义外键的更多信息