Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

java - Room query with dynamic values using placeholders

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...