房间:如何将转换为SQLite方法到Dao的@Query

3

我有一个CardViews的RecyclerView列表。下面的方法运行一个数据库方法,该方法使用“for”循环来更新索引值的排序顺序列。如果列表中有9个CardViews,则排序顺序列将从9开始降序到1。

public void resetSortIndexes() {

    int index = List.size();
    for (ListItem s : List) {
        s.setSortorder(index);         
        // update the SQLite database with the new, 
        // descending Sort numbers.   
        sqLiteDB.updateSortIndexes(s);                   
        index--;
    }
}

Database
...
public void updateSortIndexes (ListItem item) { 

    ContentValues values = new ContentValues();
    values.put(ItemContract.ItemEntry.COLUMN_SORTORDER, item.getSortorder());

    db.update(TABLE_NAME,values,ItemContract.ItemEntry.COLUMN_ID + " = ?",new String[]{String.valueOf(item.getId())});
}

我试图使用Dao方法在Room中复制相同的方法和数据库更新,但没有成功。我错过了什么吗?

public void resetSortIndexes() {

    int sortId = -1;
    int sortOrder = -1;
    int index = List.size();
    for (Card q : List) {
        q.setSortorder(index);
        sortOrder = q.getSortorder();
        sortId = q.getId();
        // update the Room database with the new, descending Sort index numbers.
        mCardViewModel.updateSortOrder(sortOrder, sortId);
        index--;
    }
}

ViewModel
...
public void updateSortOrder(int sortOrder, int sortId) {
    repository.updateSortOrder(sortOrder, sortId);
}

Repository
...
public void updateSortOrder(int sortOrder, int sortId) {
    try {
        new UpdateSortOrderColAsyncTask(quickcardDao).execute(sortOrder, sortId).get();
    } catch (ExecutionException | InterruptedException e) {
    e.printStackTrace();
    }
}

private static class UpdateSortOrderColAsyncTask extends AsyncTask<Integer, Void, Void> {

    private QuickcardDao asyncTaskDao;

    UpdateSortOrderColAsyncTask(QuickcardDao dao) {
        asyncTaskDao = dao;
    }

    @Override
    protected Void doInBackground(final Integer... params) {

        asyncTaskDao.updateSortorder(params[0],params[1]);
        return null;
    }
}

Dao
...
@Query("UPDATE quickcards SET quickcardSortorder = :sortOrder WHERE quickcardId = :sortId")
void updateSortorder(int sortOrder, int sortId);
1个回答

0
原来需要更新RecyclerView的适配器。我在removeItem()方法中添加了以下代码:

adapter.remove(quickcard);

Adapter
...
public void remove(Card item) {

    int position = mCards.indexOf(item);

    if (mCards.size()==0) {
        mCards.clear();
    }
    else if (position > -1) {
        mCards.remove(position);
    }
}

The updated (and correct) RecyclerView list size 
then allowed resetSortIndexes() to run properly.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接