使用Greendao出現SQLiteConstraintException: UNIQUE constraint failed引發的一系列問題記錄
完整的錯誤信息:
io.reactivex.exceptions.OnErrorNotImplementedException:The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DBFRIENDS_ENTITY.USER_ID (Sqlite code 2067 SQLITE_CONSTRAINT_UNIQUE), (OS error - 0:Success)
使用場景
Greendao使用場景是對好友資料進行本地數據庫存儲,由于某些雞肋需求,我們并未對好友上限做限制,同時也需要對好友進行字母分組排序,在數據量較大情況下,會出現接口請求慢,UI卡頓的問題。
解決該問題時引發的新問題
針對此問題,我們在新版本上加入了異步加載,使用了RxJava2,由于沒有處理onError,出現了上述錯誤中的The exception was not handled due to missing onError handler in the subscribe() method call
Observable.create((ObservableOnSubscribe<List<ContactSection>>) emitter -> {
//這里只是對好友數據進行本地數據庫存儲
FriendDaoOpe.deleteAllData();
...
FriendDaoOpe.insertListData(mList);
} .subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subcribe()
完整錯誤:
03-26 10:02:14.271 12283 12283 W System.err: io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DBFRIENDS_ENTITY.USER_ID (Sqlite code 2067 SQLITE_CONSTRAINT_UNIQUE), (OS error - 0:Success)
6203-26 10:02:14.272 12283 12283 W System.err: at io.reactivex.internal.functions.FunctionsOnErrorMissingConsumer.accept(Functions.java:701)
6403-26 10:02:14.272 12283 12283 W System.err: at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:77)
6503-26 10:02:14.272 12283 12283 W System.err: at io.reactivex.internal.operators.observable.ObservableObserveOnObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
6703-26 10:02:14.272 12283 12283 W System.err: at io.reactivex.internal.operators.observable.ObservableObserveOnScheduledRunnable.run(HandlerScheduler.java:124)
Rxjava相關錯誤分析解決
我們可以看到警告信息中OnErrorMissingConsumer.accept(Functions.java:701)
及subscribe()源碼中看出The RxJavaPlugins.onSubscribe hook returned a null Observer
那么我們就需要如此調用:
.subscribe(new Consumer<List<ContactSection>>() {
@Override
public void accept(List<ContactSection> contactSections) throws Exception {
}
})
針對OnErrorNotImplementedException
錯誤 ,https://github.com/ReactiveX/RxJava/wiki/Error-Handling 有相關解答:這表明Observable試圖調用其觀察者的onError()
方法,但是不存在這樣的方法。
要么保證Observable不會出現錯誤,要么就在onError中處理相關。
至此,Rx相關的問題處理完成。
SQLite相關錯誤分析解決
接下來分析android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DBFRIENDS_ENTITY.USER_ID (Sqlite code 2067 SQLITE_CONSTRAINT_UNIQUE), (OS error - 0:Success
錯誤。
重要信息:UNIQUE constraint failed
出現這個問題主要有倆種可能:
定義的字段為 NOT NULL 而在插入/修改時對應的字段為NULL
定義的字段為UNIQUE , 而在插入/修改時對應字段的值已存在
先展示我的表中字段定義DBFriendsEntity
@Entity()
public class DBFriendsEntity {
@Id(autoincrement = true)
private Long id;
@Unique
private String user_id;
private String user_name;
private String head_img;
private String friend_remark;
...
}
其中id
為主鍵,必須是Long
類型 添加注解@Id(autoincrement = true)
實現自增長
user_id
添加注解@Unique
約束該字段不能出現重復的值
上述中我們提到了Unique,還有Primary key (主鍵) 簡述下二者特征: PRIMARY KEY
主鍵:
SQLite中每個表最多可以有一個Primary key,且不能為NULL
Unique
唯一約束:
定義了UNIQUE約束的字段 值不可以重復,可以為NULL。一個表中多個字段可以存在多個UNIQUE
關于PRIMARY KEY 和 UNIQUE更多相關信息可以閱讀SQLite中的介紹。
通過上面的簡單分析 user_id后臺肯定不會返回空的,只有一種情況就是重復插入了同一條數據。至于為何會出現這種情況,初步分析是因為多個線程中同時對數據表進行了操作導致(好友的資料更新/刪除/添加都會對表進行操作)
之前多條數據的插入方法:
DaoHelper.getInstance(NimHelper.getContext())
.getWriteDaoSession().getDBFriendsEntityDao().insertInTx(list);
暫時沒有發現其他原因,那么將插入方法insertInTx()
改為insertOrReplaceInTx()
,意為如果存在則替換
相同單條數據的插入也由insert()
改為insertOrReplace()
/**
* @desc 添加單條數據至數據庫
**/
public static void insertData(DBFriendsEntity friendsEntity) {
DaoHelper.getInstance(NimHelper.getContext())
.getWriteDaoSession().getDBFriendsEntityDao().insert(friendsEntity);
}
/**
* 添加數據至數據庫,如果存在,將原來的數據覆蓋
*
* @param student
*/
public static void insertOrReplace(DBFriendsEntity student) {
DaoHelper.getInstance(NimHelper.getContext())
.getWriteDaoSession().getDBFriendsEntityDao().insertOrReplace(student);
}
/**
* 將數據實體列表數據添加到數據庫
*
* @param list
*/
public static void insertListData(List<DBFriendsEntity> list) {
if (null == list || list.isEmpty()) {
return;
}
DaoHelper.getInstance(NimHelper.getContext())
.getWriteDaoSession().getDBFriendsEntityDao().insertInTx(list);
}
/**
* 將數據實體列表數據添加到數據庫
* 如果存在則替換
*
* @param list
*/
public static void insertOrReplaceListData(List<DBFriendsEntity> list) {
if (null == list || list.isEmpty()) {
return;
}
DaoHelper.getInstance(NimHelper.getContext())
.getWriteDaoSession().getDBFriendsEntityDao().insertOrReplaceInTx(list);
}
至此,上述倆個問題“大概率已經解決了”,但是還是沒有找到復現路徑,本質上沒有得到解決,后續更新此文章...
其他問題
在上述問題解決后,對好友排序和數據庫相關操作做了一些優化。
關于數據庫加密問題:
項目中用到的并非重要數據,并沒有加密,剛開始用的時候知道會報出提示加密的警告錯誤,但是沒作處理。
現在呢,見不得紅于是加入了數據庫加密。
GreenDao可以通過SQLCipher來進行加密處理,SQLCipher最新版本4.3.0
引入:
implementation 'net.zetetic:android-database-sqlcipher:4.3.0'
implementation "androidx.sqlite:sqlite:2.0.1"
DaoSession獲取方式:
openHelper.getEncryptedWritableDb("*****") //加密寫法 參數為數據庫密碼
SQLiteDatabase db = openHelper.getWritableDatabase(); //不加密的寫法
遇到一個問題:
Couldn't open nim_friend.db for writing (will try read-only):
net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master
google之后定位到問題:之前版本數據庫是未加密的,對未加密數據庫解密時錯誤了。所以需要對舊的數據庫進行加密在查詢。
public class dbencrypt {
public static dbencrypt dbencrypt;
private boolean isopen = true;
public static dbencrypt getinstences() {
if (dbencrypt == null) {
synchronized (dbencrypt.class) {
if (dbencrypt == null) {
dbencrypt = new dbencrypt();
}
}
}
return dbencrypt;
}
/**
* 如果有舊表 先加密數據庫
*
* @param context
* @param passphrase
*/
public void encrypt(context context, string passphrase) {
file file = new file("/data/data/" + context.getpackagename() + "/databases/db_name");
if (file.exists()) {
if (isopen) {
try {
file newfile = file.createtempfile("sqlcipherutils", "tmp", context.getcachedir());
net.sqlcipher.database.sqlitedatabase db = net.sqlcipher.database.sqlitedatabase.opendatabase(
file.getabsolutepath(), "", null, sqlitedatabase.open_readwrite);
db.rawexecsql(string.format("attach database '%s' as encrypted key '%s';",
newfile.getabsolutepath(), passphrase));
db.rawexecsql("select sqlcipher_export('encrypted')");
db.rawexecsql("detach database encrypted;");
int version = db.getversion();
db.close();
db = net.sqlcipher.database.sqlitedatabase.opendatabase(newfile.getabsolutepath(),
passphrase, null,
sqlitedatabase.open_readwrite);
db.setversion(version);
db.close();
file.delete();
newfile.renameto(file);
isopen = false;
} catch (exception e) {
isopen = false;
}
}
}
}
}
特此記錄,后期更新。