在Android中将SQLBrite逻辑提取到外部类

时间:2015-05-07 10:10:09

标签: android sqlbrite

在我的聊天应用程序中,我使用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");
    }

0 个答案:

没有答案