使用占位符以动态值查询房间 [英] Room query with dynamic values using placeholders

查看:82
本文介绍了使用占位符以动态值查询房间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个Room数据库(因为我想离开装载机),并且我有一个查询,该查询根据IN运算符选择对象:

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);

问题在于: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);
        }
    });
}

问题是我收到一个空的RecyclerView,但是当我传递带有单个图标的数组时,查询正常运行.
无法在Room中实现相同的功能,因为它会在编译时检查查询吗?
如果没有,我应该在存储库构造函数中使用db.query(...)代替它吗?

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?

我知道在此处这类问题a>,但是它也说他们正在研究它,我找不到任何迹象.

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.


如果有人偶然发现了这个问题,在实现此功能时我犯了一个小错误,onActivityCreated中提供的代码实际上可以正常工作.还值得一提的是,它可用于String[]和列表,但不能用于单个字符串:"ab,cd,ef".


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

推荐答案

在实现此功能时,我犯了一个小错误,onActivityCreated中提供的代码确实有效.还值得一提的是,它可以与String[]List一起使用,但不能与单个String:"ab,cd,ef"一起使用,这是我的错误.

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.

这篇关于使用占位符以动态值查询房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆