Room query with dynamic values using placeholders

☆樱花仙子☆ 提交于 2019-12-11 14:56:23

问题


I am implementing a Room database (because I want to move away from Loaders) and I have a query that selects objects based on the IN operator:

@Query(SELECT * FROM table WHERE icon IN(:icons))
LiveData<List<Result>> getResults(String[] icons);

The issue is that the :icons array is generated dynamically during runtime, first I generate placeholders for it and then replace them with the values, like so:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String[] iconsArray = generateIconArray();
    mViewModel = ViewModelProviders.of(this, new MyViewModelFactory(getActivity().getApplication(), iconsArray)).get(MyViewModel.class);
    mViewModel.getResults().observe(this, new Observer<List<Result>>() {
        @Override
        public void onChanged(@Nullable List<Result> results) {
            RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
            mRecyclerView.setLayoutManager(layoutManager);
            GridAdapter adapter = new GridAdapter(getActivity(), results);
            mRecyclerView.setAdapter(adapter);
        }
    });
}

The problem is that I receive an empty RecyclerView, but when I pass an array with a single icon, the query works normally.
Is it not possible to achieve the same in Room because it checks queries during compile time?
And if not, instead of that should I just use db.query(...) in my repository constructor?

I know this sort of question was asked here, but it also says that they are working on it, and I couldn't find any signs of it.

EDIT:
In case someone stumbles upon this question, I made a small mistake while implementing this feature, the code provided in onActivityCreated actually works. It's also worth mentioning that it works with String[] and lists, but not with a single string: "ab,cd,ef".


回答1:


I made a small mistake while implementing this feature, the code provided in onActivityCreated actually works. It's also worth mentioning that it works with String[] and List, but not with a single String: "ab,cd,ef", which was my mistake.



来源:https://stackoverflow.com/questions/49672842/room-query-with-dynamic-values-using-placeholders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!