2

I have implemented a recycler view in my app to show the list of person in a company. I stored all those information in Realm DB. Now I want to implement search option at the top of the window so that user can search a person by name. I have tried with the following code. But this functionality is not working. I cannot make any search on this window. Here is my code for recyclerView searchView.

My activity class

public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener{

private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> colleagueResult;
private List<MyColleagueModel> filteredModelList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);

    }
    colleagueRealm = Realm.getDefaultInstance();
    recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);

    if (!Prefs.with(this).getPreLoadColleague()) {
        setRealmData();
    }
    setUpRecycler();

    showAllPersons();

}

private void showAllPersons() {
    colleagueResult = colleagueRealm.where(MyColleagueModel.class).findAll();
    setAdapter(colleagueResult);
    adapter.notifyDataSetChanged();
}

private void setAdapter(RealmResults<MyColleagueModel> results) {

    adapter = new MyColleaguesAdapter(this, colleagueRealm.where(MyColleagueModel.class).findAllSortedAsync("id"),this);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}
private void setUpRecycler() {
    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerView.setHasFixedSize(true);
    // use a linear layout manager since the cards are vertically scrollable
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
}

private void setRealmData(){

    .......
}

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

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

private void search(SearchView searchView) {

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            filteredModelList = filter(colleagueResult, newText);

            if (filteredModelList.size() > 0) {
                return true;
            } else {
                Toast.makeText(MyColleaguesPage.this, "Not Found", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
    });
}
private List<MyColleagueModel> filter(List<MyColleagueModel> models, String query) {
    query = query.toLowerCase();

    filteredModelList = new ArrayList<>();

    for (MyColleagueModel model : models) {
        final String text = model.getName().toLowerCase().toString();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }

    // arraylist in your adapter
    adapter = new MyColleaguesAdapter(this,colleagueRealm.where(MyColleagueModel.class).findAllSortedAsync("name"), getApplicationContext());
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    return filteredModelList;
  }
}

My Adapter Class

public class MyColleaguesAdapter extends RealmRecyclerViewAdapter<MyColleagueModel, MyColleaguesAdapter.ColleagueHolder>{

private List<MyColleagueModel> myColleagueModels;
private Context context;

public interface ColleagueListListener {

}

private final ColleagueListListener colleagueListListener;

public MyColleaguesAdapter(ColleagueListListener colleagueListListener, RealmResults<MyColleagueModel> realmResults, Context context ) {
    super(realmResults, true);
    this.context = context;
    this.colleagueListListener = colleagueListListener;
}

// create new views (invoked by the layout manager)
@Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflate a new colleague view
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false);
    return new ColleagueHolder(view);
}
@Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
    final MyColleagueModel myColleague = getData().get(position);
    //final MyColleagueModel myColleague=realmResults.get(position);
    holder.colleagueName.setText(myColleague.getName());
    holder.companyName.setText(myColleague.getCompany());
    holder.jobTitle.setText(myColleague.getTitle());
    holder.cardView.setTag(position);
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //editDataInterface.editData(view,position);
            int pos = (int)view.getTag();
            Intent i=new Intent(context,DetailMyColleague.class);
            i.putExtra("name",myColleague.getName());
            i.putExtra("title",myColleague.getTitle());
            i.putExtra("company",myColleague.getCompany());
            context.startActivity(i);
        }
    });

}

public class ColleagueHolder extends RecyclerView.ViewHolder{

   .......

      }
  }
 }
akshay_shahane
  • 4,423
  • 2
  • 17
  • 30
  • be specific, what does not work, and why? – Tim Aug 08 '17 at 13:24
  • I cannot search on the searching filter.the data is not updated based on input –  Aug 08 '17 at 13:24
  • @akshay whenever I wtite on search filter the data is not changed based on input.I am very new in android developing. I could not identify what would be the problem here –  Aug 08 '17 at 14:43

1 Answers1

1

Your code looks good just one mistake though

You are filtering result and storing too like below

    filteredModelList = new ArrayList<>();

    for (MyColleagueModel model : models) {
        final String text = model.getName().toLowerCase().toString();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }

but passing data old data from realm to Adapter, not the Filtered data

// arraylist in your adapter
    adapter = new MyColleaguesAdapter(this,colleagueRealm.where(MyColleagueModel.class).findAllSortedAsync("name"), getApplicationContext());
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

try this might work

adapter = new MyColleaguesAdapter(this,
colleagueRealm.where(MyColleagueModel.class).contains("fieldToQueryBy", query, Case.INSENSITIVE).findAll(), getApplicationContext());
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

and one more thing you use ignoreCase instead of toLowercase for better matching

Hope it helped

akshay_shahane
  • 4,423
  • 2
  • 17
  • 30
  • it is showing error because in Adapter class the constructor was not declared in this way –  Aug 08 '17 at 16:44
  • I have decalred constructor in this way public MyColleaguesAdapter(ColleagueListListener colleagueListListener,RealmResults realmResults, Context context ) { super(realmResults, true); this.context = context; this.colleagueListListener = colleagueListListener; } –  Aug 08 '17 at 16:45
  • adapter = new MyColleaguesAdapter(this, colleagueRealm.where(MyColleagueModel.class).contains("fieldToQueryBy", query, Case.INSENSITIVE).findAll(), getApplicationContext()); recyclerView.setAdapter(adapter); adapter.notifyDataSetChanged(); – akshay_shahane Aug 08 '17 at 16:54
  • also updated the answer please check @ktina and please accept the answer if solves your problem – akshay_shahane Aug 08 '17 at 16:54
  • above code to be included in filter() method – akshay_shahane Aug 08 '17 at 16:56
  • Thanks it is working. I have accepted your answer. Could you please also upvote my question if you do not mind. –  Aug 08 '17 at 16:59