Room:如何将SQLite方法转换为Dao的@Query

时间:2019-08-05 00:29:16

标签: android android-view

我有CardViews的RecyclerView列表。下面的方法运行一个数据库方法,该方法使用“ for”循环来更新索引值的“排序顺序”列。如果列表中有9个CardView,则“排序顺序”列的值将从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 :(得分:0)

结果是需要更新RecyclerView的适配器。我将此方法添加到removeItem():

adapter.remove(快速卡片);

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.