在我的聊天应用程序中,我使用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");
}
最佳答案
我不确定是否100%理解您的问题,但是我将使用上面提供的代码创建一个SQLBrite Helper类,并在活动的onCreate()中对其进行实例化。
另外,您必须将onResume()和onPause()事件传递给您的帮助器类(因为只有在活动处于活动状态时才需要它),然后通过回调返回结果。
MyActivity.java
public class MyActivity extends Activity implements SQLHelper.ResultListener {
SQLHelper mSQLHelper;
public void onCreate() {
mSQLHelper = new SQLHelper(this);
}
public void onResume() {
mSQLHelper.onResume();
}
public void onPause() {
mSQLHelper.onPause();
}
@
Override
public void onUpdateChatList(String _message) {
//show it
}
}
SQLHelper.java
public class SQLHelper {
ResultListener mListener;
public interface ResultListener {
public void onUpdateChatList(String _message);
}
public void SQLHelper(ResultListener _resultListener) {
mListener = _resultListener;
}
public void onResume() {
//Here subscribe to your query
}
public void onPause() {
//here unsubscribe
}
private void parseQueryData(Query query) {
//... your code
mListener.onUpdateChatList(String _message);
}
}
希望能有所帮助。
关于android - 将SQLBrite逻辑提取到Android中的外部类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30097987/