Ограничение внешнего ключа ОГРАНИЧЕНИЕ не пойман - PullRequest
0 голосов
/ 22 июня 2019

Я пытаюсь поймать исключение ограничения внешнего ключа в Android, используя Room.

Мне не удалось поймать это исключение времени выполнения, используя конкретные исключения, от SQLiteConstraintException до самых общих, Exception, в операторе try-catch.

Вот трик-трик из меню в операторе switch:

try {
                    mViewModel.deleteTerm();
                } catch (SQLiteConstraintException ex) {
                    AlertDialog.Builder a_builder = new
                            AlertDialog.Builder(TermEditorActivity.this);
                    a_builder.setMessage("Courses are assigned for this term and it cannot be deleted." +
                            "\n\nYou must remove all courses prior to deleting a term.")
                            .setCancelable(false)
                            .setPositiveButton("Okay", new
                                    DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.cancel();
                                            //finish();
                                        }
                                    });
                    AlertDialog deleteAllAlert = a_builder.create();
                    deleteAllAlert.setTitle("CANNOT DELETE TERM!!!");
                    deleteAllAlert.show();
                    return true;

                }
                finally {
                    startActivity(new Intent(TermEditorActivity.this,
                            MainActivity.class));
                }
            return true;

Исключение, появляющееся в окне "Выполнить":

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)

Вот документация RESTRICT . Меня беспокоит то, как говорится, что исключение работает, что, очевидно, отличается от других исключений:

"The difference between the effect of a RESTRICT action and normal foreign key constraint enforcement is that the RESTRICT action processing happens as soon as the field is updated - not at the end of the current statement as it would with an immediate constraint, or at the end of the current transaction as it would with a deferred() constraint.

Even if the foreign key constraint it is attached to is deferred(), configuring a RESTRICT action causes SQLite to return an error immediately if a parent key with dependent child keys is deleted or modified.

Так что, если это ошибка SQLite, действительно ли она попадает в Ошибка ? Я не понимаю, как поймать это исключение, и подумал, может быть, это на самом деле ошибка в одежде исключений, так сказать?

Я подумал, что вместо этого NO_ACTION может быть проще иметь дело, но это тоже не перехватывается и имеет такое же сообщение об ошибке в журнале.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...