Android 使用视图模型和实时数据实现搜索 [英] Android implement search with view model and live data

查看:27
本文介绍了Android 使用视图模型和实时数据实现搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 android 中为一个 udacity 课程开发一个项目我目前正在尝试实现一个搜索功能,同时坚持 android 架构组件并使用 firestore 和 room 我对所有这些概念都很陌生,所以请指出任何看起来不对的地方.

I'm working on a project in android for a udacity course I'm currently trying to implement a search function while adhering to android architecture components and using firestore and room I'm fairly new to all these concepts so please point out anything that seems wrong.

所以我创建了一个数据库存储库来保持我的 Firestore 和房间数据库同步并提供数据.然后我使用 viewmodel 和观察者模式(我认为)所以我的观察者获取数据并查找更改并将其提供给我的适配器(refreshMyList(List)),它填充了一个 recyclerview 像这样:

So I made a database repository to keep my firestore and room databases in sync and to deliver the data. I'm then using viewmodel and the observer pattern (I think) so my observer gets the data and looks for changes gives it to my adapter (refreshMyList(List)) which populates a recyclerview like this :

 contactViewModel = ViewModelProviders.of(this).get(ContactsViewModel.class);
 contactViewModel.getAllContacts().observe(this, new 
 Observer<List<DatabaseContacts>>() {
        @Override
        public void onChanged(@Nullable List<DatabaseContacts> 
        databaseContacts) {
            ArrayList<DatabaseContacts> tempList = new ArrayList<>();
            tempList.addAll(databaseContacts);
            contactsAdapter.refreshMyList(tempList);
            if (tempList.size() < 1) {
                results.setVisibility(View.VISIBLE);
            } else {
                results.setVisibility(View.GONE);
            }
        }
    });

我现在想搜索数据,我的房间查询都设置得很好,我的数据存储库中有方法可以根据搜索字符串获取联系人,但我似乎无法刷新我的列表读到有像 Transformations.switchMap 这样的方法吗?但我似乎无法理解它是如何工作的任何人都可以帮助我

I now want to perform a search of the data, I have my room queries all set up fine and I have methods in my data repository to get contacts based on a search string but I cant seem to refresh my list I've read that there are ways to do it like Transformations.switchMap ? but i cant seem to wrap my head around how it works can anyone help me

目前我正在尝试从异步任务返回结果列表,它曾经返回实时数据,但我将其更改为 getValue() 始终为 null,不确定这是否正确,这是异步的:

Currently I'm trying to return a List of results from an async task, it used to return live data but I changed it as getValue() was always null, not sure if that's correct, heres the async :

private static class searchContactByName extends AsyncTask<String, Void, 
ArrayList<DatabaseContacts>> {

    private LiveDatabaseContactsDao mDao;

    searchContactByName(LiveDatabaseContactsDao dao){
        this.mDao = dao;
    }

    @Override
    protected ArrayList<DatabaseContacts> doInBackground(String... params) {
        ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
        mDao.findByName("%" + params[0] + "%");
        return contactsArrayList;
    }
}

我从我的联系人存储库中调用它自己的包装类型:

I call this from my contacts repository in its own sort of wrapper :

public List<DatabaseContacts> getContactByName(String name) throws 
ExecutionException, InterruptedException {
    //return databaseContactsDao.findByName(name);
    return new searchContactByName(databaseContactsDao).execute(name).get();
}

这是从我的视图模型中调用的,如下所示:

and this is called from my view model like this :

public List<DatabaseContacts> getContactByName(String name) throws 
ExecutionException, InterruptedException {
    return  contactRepository.getContactByName(name);
}

然后我从我的片段中调用它:

I'm then calling this from my fragment :

private void searchDatabase(String searchString) throws ExecutionException, 
InterruptedException {
    List<DatabaseContacts> searchedContacts = 
    contactViewModel.getContactByName("%" + searchString + "%");
    ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
    if (searchedContacts !=  null){
        contactsArrayList.addAll(searchedContacts);
        contactsAdapter.refreshMyList(contactsArrayList);
    }
}

这是从我的 onCreateOptionsMenu 中的搜索查询文本更改方法调用的:

and this is called from an on search query text changed method in my onCreateOptionsMenu :

        @Override
        public boolean onQueryTextChange(String newText) {
            try {
                searchDatabase(newText);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }

但它什么也没做,我原来的recyclerview 内容从不改变任何想法?

but it just does nothing my original recyclerview contents never change any ideas?

推荐答案

可以使用 Transformation.switchMap 进行搜索操作.

you can use Transformation.switchMap to do search operations.

  1. 在视图模型中创建具有最新搜索字符串的 MutableLiveData.

  1. In viewmodel create MutableLiveData which has latest search string.

内部视图模型使用:

    LiveData<Data> data = 
    LiveDataTransformations.switchMap(searchStringLiveData, string ->  
    repo.loadData(string)))

  1. 将上述实时数据返回给活动,以便它可以观察和更新视图.

这篇关于Android 使用视图模型和实时数据实现搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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