简体   繁体   中英

Android sql multiple search

I create database that can be search by single string(Name), and now i need to search by multiple strings that is separated by comma, and here I am stuck. Example how i want to look like: Mark,John,Mia .... Anybody know how to add that to this code?

TestListActivity

@Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.test_search, menu);

        MenuItem search = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query){
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText){
        newText = newText.toLowerCase();
        ArrayList<Test> newList = new ArrayList<>();
        for (Test test : listTest){
            String name = test.getName().toLowerCase();
            if (name.contains(newText)){
                newList.add(test);
            }
        }

        testRecyclerAdapter.setFilter(newList);
        return true;
    }

TestRecyclerAdapter

public void setFilter (ArrayList<Test> newList){
    listTest = new ArrayList<>();
    listTest.addAll(newList);
    notifyDataSetChanged();
}

This is how it looks right now RecyclerSearch

Update your onQueryTextChange method to this:

public boolean onQueryTextChange(String newText){
        newText = newText.toLowerCase();
        String[] splitter = newText.split(","); //splits the query into array by ',' 
        ArrayList<Test> newList = new ArrayList<>();
        for (Test test : listTest){
            boolean contain = false;
            String name = test.getName().toLowerCase();
            for(int i = 0; i < splitter.length; i++){
               if (name.contains(splitter[i])){ //contains at least one of the tags
                   contain=true;break;
               }
            }
            if(contain) 
                newList.add(test);
        }

        testRecyclerAdapter.setFilter(newList);
        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM