在我的聊天应用程序中,我使用 SQLBrite 包装器从本地数据库更新聊天。目前我的活动同时包含 UI 和 SQLBrite。现在我想将 SQLBrite 逻辑提取到外部类。因此,当我的活动还活着时,我需要提取的 SQLBrite 也活着。目前我有订阅者的问题。我还将它提取到外部类,并且它一直在发出查询,尽管一切都与它在活动时一样,并且它正在工作。
这是旧代码,所有内容都在同一个活动中:我该怎么做?
SqlBrite sqlBrite;
sqlBrite = SqlBrite.create(DatabaseManager.DatabaseHelper);
private final CompositeSubscription subscriptions = new CompositeSubscription();
private void saveMessage(Message message) {
ContentValues values = new ContentValues();
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_MESSAGE_ID, message.getId());
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_SERIAL_NUMBER, message.getSerialNumber());
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, message.getText());
sqlBrite.insert(DatabaseContract.MessageEntry.TABLE_NAME, values, SQLiteDatabase.CONFLICT_IGNORE);
}
private void subscribeToDbChanges() {
String NEW_MSG_QUERY = "SELECT * FROM "
+ DatabaseContract.MessageEntry.TABLE_NAME
+ " WHERE "
+ DatabaseContract.MessageEntry.COLUMN_NAME_CREATED_AT_MILLS
+ " >= ? ORDER BY "
+ DatabaseContract.MessageEntry.COLUMN_NAME_CREATED_AT_MILLS
+ " DESC";
String grpId = String.valueOf(groupId);
String msgDate = String.valueOf(dividerMsgDate);
Observable<Query> freshMessages = sqlBrite.createQuery(DatabaseContract.MessageEntry.TABLE_NAME, NEW_MSG_QUERY, grpId, msgDate);
subscriptions.add(
freshMessages.subscribe(query -> parseQueryData(query)));
}
private void parseQueryData(Query query) {
Log.d(TAG, "subscriber called");
List<Message> messages = new ArrayList<>();
Cursor c = query.run();
try {
while (c.moveToNext()) {
Message message = new Message();
message.setLocalId(c.getInt(c.getColumnIndexOrThrow(DatabaseContract.MessageEntry._ID)));
message.setId(c.getInt(c.getColumnIndexOrThrow(DatabaseContract.MessageEntry.COLUMN_NAME_MESSAGE_ID)));
messages.add(message);
}
} finally {
c.close();
}
updateChatList(messages, "new");
}