Handle materialsearchbar search results in android - android

I am using com.github.mancj:MaterialSearchBar:+ dependency in my app to search data in my SQLite database. It does load suggestions based on the data i have in the database but when a user clicks on one of the suggestion and confirms it by clicking the search icon in the keyboard nothing gets displayed, the adapter is not being called to display the result. below is my search activity
recyclerView = findViewById(R.id.hyme_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = findViewById(R.id.searchBar);
database = new Database(this);
materialSearchBar.setHint("Search here");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
List<String> sugest = new ArrayList<>();
for (String search: suggestList) {
if (search.toUpperCase().contains(materialSearchBar.getText().toUpperCase()))
sugest.add(search);
}
materialSearchBar.setLastSuggestions(sugest);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled){
searchAdapter = new SearchAdapter(getBaseContext(),database.getSongs());
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
searchAdapter = new SearchAdapter(this,database.getSongs());
recyclerView.setAdapter(searchAdapter);
}
private void startSearch(String text) {
searchAdapter = new SearchAdapter(this,database.getSongByName(text));
recyclerView.setAdapter(searchAdapter);
}
private void loadSuggestList() {
suggestList = database.getTitle();
materialSearchBar.setLastSuggestions(suggestList);
}

Related

Retrieve data from specific user of firebase in Android

I am trying to read "specific" data from my firebase realtime database. I have seen examples of getting all data from a table and going through it to find the data record you want.
Below is how I save my data`
FirebaseDatabase database;
DatabaseReference foodList;
String categoryId="";
FirebaseRecyclerAdapter<Food,FoodViewHolder>adapter;
FirebaseRecyclerAdapter<Food,FoodViewHolder>searchAdapter;
List<String> suggestList=new ArrayList<>();
MaterialSearchBar materialSearchBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
database=FirebaseDatabase.getInstance();
foodList=database.getReference("Foods");
recyclerView=findViewById(R.id.recycler_food);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if(getIntent()!=null)
{
categoryId=getIntent().getStringExtra("CategoryId");
}
if(!categoryId.isEmpty() )
{
loadListFood(categoryId);
}
materialSearchBar=findViewById(R.id.searchBar);
materialSearchBar.setHint("Enter food name");
loadSuggestion();
materialSearchBar.setLastSuggestions(suggestList);
materialSearchBar.setCardViewElevation(10);
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String>suggest=new ArrayList<>();
for (String search:suggestList)
{
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
{
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text);
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
}
private void startSearch(CharSequence text) {
searchAdapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(
Food.class,
R.layout.food_item,
FoodViewHolder.class,
foodList.orderByChild("Name").equalTo(text.toString())// compare Food Name//////
) {
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) {
viewHolder.food_name.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.food_image);
final Food local=model;
viewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(FoodList.this,""+local.getName(),Toast.LENGTH_SHORT).show();//there is problem local.getName???????????
//Start new Acitvity
Intent foodDetail=new Intent(FoodList.this,FoodDetail.class);
foodDetail.putExtra("FoodId",searchAdapter.getRef(position).getKey());//send Food ID to new Acitivity
startActivity(foodDetail);
}
});
}
};
recyclerView.setAdapter(searchAdapter);
}
private void loadSuggestion() {
foodList.orderByChild("MenuId").equalTo(categoryId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren() )
{
Food item=postSnapshot.getValue(Food.class);
suggestList.add(item.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void loadListFood(String categoryId) {
adapter=new FirebaseRecyclerAdapter<Food, FoodViewHolder>(Food.class,
R.layout.food_item,
FoodViewHolder.class,
foodList.orderByChild("menuId").equalTo(categoryId))
{
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) {
viewHolder.food_name.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.food_image);
final Food local=model;
viewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(FoodList.this,""+local.getName(),Toast.LENGTH_SHORT).show();
Intent foodDetail=new Intent(FoodList.this,FoodDetail.class);
foodDetail.putExtra("FoodId",adapter.getRef(position).getKey());
startActivity(foodDetail);
}
});
}
};
recyclerView.setAdapter(adapter);
}
}
UPDATE
When I try to get the data from firebase to update the food list , i didn't found the database to change. Below is database that i want to update.

Implementing Search filter Causing problem when pressed backspace

I am trying to implement a search filter on complex object data in recyclerview when I type in the Edit text first-time it works properly, but whenever I try to delete characters by pressing back-space in order to modify our search- I am repeatedly failing in this regard.
I can only search once !!
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myAdapter.filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
now the filter code
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
Log.d("users ",s.getName());
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
Whats the issue, I cannot search more than once-any help is appreciated
Here is my Adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
{
Context cxt;
ArrayList<user> arr;
ArrayList<user> arrcopy;
DatabaseReference dref;
MyAdapter myAdapter;
public MyAdapter(Context context, ArrayList<user> arrayList)
{
cxt = context;
arr = arrayList;
arrcopy=new ArrayList<>(arr);
Log.d("Very start arr",arr.toString());
notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(cxt).inflate(R.layout.item_chatroom,viewGroup,false);
myAdapter = new MyAdapter(cxt, arr);
Log.d("Inside MyHolder arr",arr.toString());
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder,final int i) {
final String name = arr.get(i).getUsername();
String pic=arr.get(i).getPic();
final String mail=arr.get(i).getEmail();
myHolder.name.setText(name);
Glide.with(myHolder.profile.getContext())
.load(pic)
.into(myHolder.profile);
myHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(cxt,MainActivity.class);
intent.putExtra("Id",arr.get(i).getId());
intent.putExtra("Name",arr.get(i).getUsername());
cxt.startActivity(intent);
}
});
myHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SweetAlertDialog pDialog = new SweetAlertDialog(cxt, SweetAlertDialog.SUCCESS_TYPE);
pDialog.setTitleText("User Information e-mail ID");
pDialog.setContentText("Name: "+name+"\n\n E-mail: "+mail);
pDialog.setConfirmText("Ok");
pDialog.show();
}
});
}
#Override
public int getItemCount() {
return arr.size();
}
class MyHolder extends RecyclerView.ViewHolder
{
TextView name;
ImageView profile,info;
public MyHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.txv);
profile=itemView.findViewById(R.id.profile);
info=itemView.findViewById(R.id.profileinfo);
}
}
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
}
I assume the arrcopy is the copy of arr like:
ArrayList<User> arrcopy = new ArrayList<>(arr);
If you modify arr, it also change the content of arrcopy. And when no result matches, the arr is empty, so is the arrcopy.
else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
Now temp is empty, the arr data you set for adapter is empty, so issues happens.
Please try:
In MyAdapter:
Context cxt;
ArrayList<user> arr;
public MyAdapter(Context context) {
cxt = context;
dref = FirebaseDatabase.getInstance().getReference("users");
}
public void setData(ArrayList<User> arrayList) {
arr = arrayList;
notifyDataSetChanged();
}
Also put the filter() in your activity/fragment:
protected void onCreate(final Bundle savedInstanceState) {
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etSearch.requestFocus();
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filter(etSearch.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
etSearch.clearFocus();
mAdapter = new MyAdapter(this);
mAdapter.setData(arrayList);
mRecyclerView.setAdapter(mAdapter);
...
}
public void filter(String input) {
if (!TextUtils.isEmpty(input)) {
ArrayList<User> temp = new ArrayList<>();
for (user s : arr) {
if (s.getName().toLowerCase().contains(input)) {
temp.add(s);
}
}
mAdapter.setData(temp);
} else {
mAdapter.setData(arr);
}
mAdapter.notifyDataSetChanged();
}
Implement Filterable in your MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
implements Filterable {
// change MyObject to user class
//replace myObjects with arr and reservedList with arrcopy
Context cxt;
ArrayList<MyObject> myObjects;
ArrayList<MyObject> reservedList;
DatabaseReference dref;
public MyAdapter(Context context, ArrayList<MyObject> arrayList){
cxt = context;
myObjects = arrayList;
reservedList = arrayList
Log.d("Very start arr",myObjects.toString());
// notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
//...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
if (!charString.isEmpty()) {
List<MyObject> filteredList = new ArrayList<>();
for (MyObject row : reservedList) {
if (row.getName().toLowerCase().contains(charString)){
filteredList.add(row);
}
}
myObjects = filteredList;
} else {
myObjects = reservedList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = myObjects;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
myObjects = (ArrayList<MyObject>) filterResults.values;
notifyDataSetChanged();
}
};
}
and from your activity
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});

Recyclerview not updating on searchview text change

Friends , I have an edittext which is acting like a searchview.On text change,it is fetching data and storing in filterdNames but it is not updating the recyclerview.Kindly help, i am new to andriod.
Here is my recyclerview adapter code-
public class MyCategoryAdaptercheckbox extends RecyclerView.Adapter<MyCategoryAdaptercheckbox.ViewHolder> {
List<GetMyCategoryAdapter> getMyCategoryAdapter;
Context context;
List<String> category_name;
GetMyCategoryAdapter getMyCategoryAdapter1;
public MyCategoryAdaptercheckbox(List<GetMyCategoryAdapter> getMyCategoryAdapter, Context context, List<String> category_name) {
this.getMyCategoryAdapter = getMyCategoryAdapter;
this.context = context;
this.category_name = category_name;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (viewHolder instanceof ViewHolder){
}
getMyCategoryAdapter1 = getMyCategoryAdapter.get(i);
((ViewHolder) viewHolder).tv_categorytitle.setText(getMyCategoryAdapter1.getC_name());
((ViewHolder) viewHolder).tv_categoryid.setText(getMyCategoryAdapter1.getC_id());
((ViewHolder) viewHolder).gt= getMyCategoryAdapter1;
}
public void filterList(ArrayList<String> filterdNames) {
this.category_name = filterdNames;
notifyDataSetChanged();
}
}
Here is my GetMyCategoryAdapter class code -
public class GetMyCategoryAdapter {
String c_name,c_id;
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getC_id() {
return c_id;
}
public void setC_id(String c_id) {
this.c_id = c_id;
}
}
And here is the fragment code -
searchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//after the change calling the method and passing the search input
filter(editable.toString());
}
});
private void filter(String text) {
//new array list that will hold the filtered data
ArrayList<String> filterdNames = new ArrayList<>();
//looping through existing elements
for (String s : category_name) {
//if the existing elements contains the search input
if (s.toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filterdNames.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
((MyCategoryAdaptercheckbox) MyAdapter).filterList(filterdNames);
}
The problem is in filterList method:
you update category_name, but not getMyCategoryAdapter (which is used in onBindViewHolder). Try change getMyCategoryAdapter as well before notifyDataSetChanged

Search in RecyclerView with EditText

I write this code for search in recyclerview with edit text but, when I run the application and input a text that I need to search about it on the edit text in the first letter the recycler content not changed and when I input the second Letter the RecyclerView become empty.
how can I filter the recycler? what is the wrong in my code ?
xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FamilyActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/search"
android:layout_width="294dp"
android:layout_height="70dp"
android:layout_marginTop="-20dp"
android:hint="Search ..."
android:drawableLeft="#drawable/ic_search_black_24dp"
/>
<Button
android:id="#+id/add"
android:layout_width="54dp"
android:layout_height="match_parent"
android:layout_marginLeft="35dp"
android:drawableTop="#drawable/ic_person_add_black_24dp"
android:onClick="add_new_family"
tools:ignore="OnClick" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
code in main activity:
public class FamilyActivity extends AppCompatActivity {
RecyclerView recyclerView;
FamilyAdapter familyAdapter;
Button add_family;
EditText search;
List<Family> familyList;
String patientID = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family);
add_family=(Button)findViewById(R.id.add);
search =(EditText)findViewById(R.id.search);
familyList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Bundle extras = getIntent().getExtras();
if (extras != null) {
patientID = extras.getString("ID");
}
loadFamilyList();
//adding some items to our list
//creating recyclerView adapter
FamilyAdapter adapter = new FamilyAdapter(this, familyList);
//setting adapter to recyclerView
recyclerView.setAdapter(adapter);
addTextListener();
}
public void addTextListener(){
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final List<Family> filteredList = new ArrayList<>();
for (int i = 0; i < familyList.size(); i++) {
final String text = familyList.get(i).toString().toLowerCase();
if (text.contains(query)) {
filteredList.add(familyList.get(i));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(FamilyActivity.this));
FamilyAdapter fadapter = new FamilyAdapter(FamilyActivity.this,filteredList);
recyclerView.setAdapter(fadapter);
fadapter.notifyDataSetChanged(); // data set changed
}
});
}
code in adapter:
public class FamilyAdapter extends RecyclerView.Adapter<FamilyAdapter.FamilyViewHolder> {
private Context context;
private List<Family> familyList;
private List<Family> familyListFull;
public FamilyAdapter(Context context, List<Family> familyList) {
this.context = context;
this.familyList = familyList;
familyListFull=new ArrayList<>(familyList);
}
#NonNull
#Override
public FamilyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_layout, null);
return new FamilyViewHolder(view);
}
#Override
public void onBindViewHolder(FamilyViewHolder familyViewHolder, final int position) {
Family family = familyList.get(position);
familyViewHolder.textViewTitle.setText(family.getName());
familyViewHolder.familyLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on : " + familyList.get(position));
String name = familyList.get(position).getName();
String num = familyList.get(position).getNum();
Intent intent = new Intent(context, Chatting.class);
intent.putExtra("num", num);
intent.putExtra("name", name);
context.startActivity(intent);
}
});
familyViewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Delete");
builder.setMessage("Are you sure you want to delete this one ")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RemoveFamilyMember(position);
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builder.setCancelable(true);
}
});
AlertDialog alert=builder.create();
alert.show();
}
});
}
you can try something like this I think this might work, I haven't tested it but I think that making a new adapter everytime that the edittext has something in it is a bad idea. and if you get to the point back to where the query is equal to "" empty string then you should make the fileterd list back into the whole list which I didn't put in there
public class FamilyActivity extends AppCompatActivity {
RecyclerView recyclerView;
FamilyAdapter familyAdapter;
Button add_family;
EditText search;
List<Family> familyList;
List<Family> filteredList;
String patientID = "";
FamilyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family);
add_family=(Button)findViewById(R.id.add);
search =(EditText)findViewById(R.id.search);
familyList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Bundle extras = getIntent().getExtras();
if (extras != null) {
patientID = extras.getString("ID");
}
loadFamilyList();
filteredList = new ArrayList<>(familyList);
//adding some items to our list
//creating recyclerView adapter
adapter = new FamilyAdapter(this, filteredList);
//setting adapter to recyclerView
recyclerView.setAdapter(adapter);
addTextListener();
}
public void addTextListener(){
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
filteredList = new ArrayList<>();
for (int i = 0; i < familyList.size(); i++) {
final String text = familyList.get(i).toString().toLowerCase();
if (text.contains(query)) {
filteredList.add(familyList.get(i));
}
}
recyclerView.removeAllViews();;
adapter.notifyDataSetChanged(); // data set changed
}
});
}
editTextSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
private void filter(String text) {
ArrayList<Model> newList = new ArrayList<>();
for (Model item : mModelList) {
if (item.getTitle().contains(text)){
newList.add(item);
}
}
yourAdapter.setFilter(newList);
}

v7 SearchView android

How to filter a RecyclerView with a SearchView(android.support.v7.widget.SearchView) which is not included in toolbar?
I want to filter the results in my recycler adapter using names which i am getting from api in a model.
I have set the recyclerview inside a fragment.
you can simply do it by searchview or edit text
for search view
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
filter(s.toString(),getCustomDeviceCheckItemsList());
return true;
}
});
private void filter(String text,ArrayList<CustomCheckItem> names) {
//new array list that will hold the filtered data
ArrayList<CustomCheckItem> filterdNames = new ArrayList<>();
//looping through existing elements
for (CustomCheckItem s : names) {
//if the existing elements contains the search input
if (s.getTitle().toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filterdNames.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
childAdapter.filterList(filterdNames);
}
and in adapter you have to write
public void filterList(ArrayList<CustomItem> filterdNames) {
this.list = filterdNames;
notifyDataSetChanged();
}
and if you want to do it by edit text then
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString(),getCustomDeviceCheckItemsList());
}
});

Categories

Resources