通过文件室将数据插入数据库时崩溃:原因是:android.database.sqlite.SQLiteConstrain



这是我的StoreDao.class

@Dao
public interface StoreDao {
@Insert 
void insertList(List<StoreItem> storeItems);
}

由以下原因引起:android.database.sqlite.SQLiteConstraintException:UNIQUE约束失败:当尝试将相同的数据插入房间时发生此崩溃:

io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: StoreItem.ts_code (Sqlite code 1555 SQLITE_CONSTRAINT_PRIMARYKEY), (OS error - 2:No such file or directory)
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:126)
at android.os.Handler.handleCallback(Handler.java:891)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:280)
at android.app.ActivityThread.main(ActivityThread.java:7598)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:986)
Caused by: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: StoreItem.ts_code (Sqlite code 1555 SQLITE_CONSTRAINT_PRIMARYKEY), (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:841)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:803)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)

只需将(onConflict=OnConflictStrategy.REPLACE(添加到@Insert

@Dao
public interface StoreDao {
@Insert (onConflict = OnConflictStrategy.REPLACE)
void insertList(List<StoreItem> storeItems);
}

最新更新