Not getting proper results after performing search - android

This is my fragment which is like MainActivity :
public class cgpa_frag extends Fragment {
RecyclerView recyclerview;
adapter_cgpa ac;
ArrayList<POJO> cgpaArrayList = new ArrayList<>();
public cgpa_frag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_cgpa_frag, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.rc2);
cgpaArrayList = new ArrayList<>();
ac = new adapter_cgpa(cgpaArrayList);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
recyclerview.setAdapter(ac);
Fetchdata2();
return view;
}
private void Fetchdata2() {
dbmanager db = new dbmanager(getContext());
Cursor cursor = db.fetch_data2();
if (cursor != null) {
// cursor.moveToFirst();
while (cursor.moveToNext()) {
POJO pj = new POJO();
pj.setCname(cursor.getString(0));
pj.setNo_of_sems(cursor.getString(1));
pj.setCgpa(cursor.getString(2));
pj.setPercentage(cursor.getString(3));
pj.setSchemec(cursor.getString(4));
cgpaArrayList.add(pj);
}
ac = new adapter_cgpa(cgpaArrayList);
}
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ac.getFilter().filter(newText);
return false;
}
});
}
}
This is my adapter class:
public class adapter_cgpa extends RecyclerView.Adapter<adapter_cgpa.Viewholder> implements Filterable {
ArrayList<POJO> cgpaArrayList;
ArrayList<POJO> cgpaArrayListcopy;
public adapter_cgpa(ArrayList<POJO> cgpaArrayList) {
this.cgpaArrayList = cgpaArrayList;
cgpaArrayListcopy = new ArrayList<>(cgpaArrayList);
}
#NonNull
#Override
public adapter_cgpa.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cgpa, parent, false);
return new Viewholder(listitem);
}
#Override
public void onBindViewHolder(#NonNull adapter_cgpa.Viewholder holder, int position) {
POJO cgpa= cgpaArrayList.get(position);
holder.cname.setText(cgpa.getCname());
holder.no_of_sems.setText(cgpa.getNo_of_sems());
holder.cgpa.setText(cgpa.getCgpa());
holder.percentage.setText(cgpa.getPercentage());
holder.schemec.setText(cgpa.getSchemec());
}
#Override
public int getItemCount() {
return cgpaArrayList.size();
}
#Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<POJO>filteredList=new ArrayList<>();
if(constraint==null || constraint.length()==0){
filteredList.addAll(cgpaArrayListcopy);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for( POJO item : cgpaArrayListcopy){
if (item.getCname().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results=new FilterResults();
results.values=filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
cgpaArrayList.clear();
cgpaArrayList.addAll((List)results.values);
notifyDataSetChanged();
}
};
public class Viewholder extends RecyclerView.ViewHolder {
TextView cname, no_of_sems, cgpa, percentage,schemec;
ImageButton btndelete2;
public Viewholder(#NonNull View itemView) {
super(itemView);
cname=(TextView)itemView.findViewById(R.id.name);
no_of_sems=(TextView)itemView.findViewById(R.id.no_of_sem);
cgpa=(TextView)itemView.findViewById(R.id.textView49);
percentage=(TextView)itemView.findViewById(R.id.textView55);
schemec=(TextView)itemView.findViewById(R.id.scheme2);
btndelete2=(ImageButton)itemView.findViewById(R.id.btndelete2);
btndelete2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setMessage("Are you sure you want to delete this?");
alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
final AlertDialog dialogs = alert.create();
dialogs.show();
dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete(getAdapterPosition());
dialogs.dismiss();
}
});
dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogs.dismiss();
}
});
}
});
}
private void delete(int adapterPosition) {
cgpaArrayList.remove(adapterPosition);
notifyDataSetChanged();
final String snc = cname.getText().toString();
final String semrc = no_of_sems.getText().toString();
final String schc = schemec.getText().toString();
dbmanager db = new dbmanager(itemView.getContext());
db.delete2(snc, semrc, schc);
}
}
}
This is search_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search by name..."
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.widget.SearchView" />
</menu>
I am always getting only the first data as output irrespective of any data I am searching for.
This is my recycler view:
And this is what I am getting after search:
Can someone tell me where am I going wrong?
I have referred this video:
https://codinginflow.com/tutorials/android/searchview-recyclerview

this is not a propper answer but maybe it helps. its a longshot but I thing the issue might be in some weird code constelation you have in your fragment class mainly the way you implemented fetchdata2.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_cgpa_frag, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.rc2);
cgpaArrayList = new ArrayList<>();
//put this method here
Fetchdata2();
ac = new adapter_cgpa(cgpaArrayList);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
recyclerview.setAdapter(ac);
return view;
}
private void Fetchdata2() {
dbmanager db = new dbmanager(getContext());
Cursor cursor = db.fetch_data2();
if (cursor != null) {
// cursor.moveToFirst();
while (cursor.moveToNext()) {
POJO pj = new POJO();
pj.setCname(cursor.getString(0));
pj.setNo_of_sems(cursor.getString(1));
pj.setCgpa(cursor.getString(2));
pj.setPercentage(cursor.getString(3));
pj.setSchemec(cursor.getString(4));
cgpaArrayList.add(pj);
}
}
}
I just notices you were setting the adapter a bunch of times inside the cursor and now its only being set once. I am still not sure this will solve your problem but give it a try.
Now fetchdata2 is only populating cgpaArraylist and the adapter is created in a different step after this method is excecuted

Just add SearchView before RecyclerView, and configurate it

import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import java.util.ArrayList;
import java.util.List;
public class adapter_cgpa extends RecyclerView.Adapter<adapter_cgpa.Viewholder> implements Filterable {
ArrayList<POJO> cgpaArrayList;
ArrayList<POJO> cgpaArrayListcopy;
public adapter_cgpa(ArrayList<POJO> cgpaArrayList) {
this.cgpaArrayList = cgpaArrayList;
cgpaArrayListcopy = new ArrayList<>(cgpaArrayList);
}
#NonNull
#Override
public adapter_cgpa.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cgpa, parent, false);
return new Viewholder(listitem);
}
#Override
public void onBindViewHolder(#NonNull adapter_cgpa.Viewholder holder, int position) {
POJO cgpa = cgpaArrayList.get(position);
holder.cname.setText(cgpa.getCname());
holder.no_of_sems.setText(cgpa.getNo_of_sems());
holder.cgpa.setText(cgpa.getCgpa());
holder.percentage.setText(cgpa.getPercentage());
holder.schemec.setText(cgpa.getSchemec());
}
#Override
public int getItemCount() {
return cgpaArrayList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<POJO> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(constraint)) {
filteredList.addAll(cgpaArrayListcopy);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (POJO item : cgpaArrayListcopy) {
if (item.getCname().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}else{
filteredList.remove(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
cgpaArrayList.clear();
cgpaArrayList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cname, no_of_sems, cgpa, percentage, schemec;
ImageButton btndelete2;
public Viewholder(#NonNull View itemView) {
super(itemView);
cname = itemView.findViewById(R.id.name);
no_of_sems = itemView.findViewById(R.id.no_of_sem);
cgpa = itemView.findViewById(R.id.textView49);
percentage = itemView.findViewById(R.id.textView55);
schemec = itemView.findViewById(R.id.scheme2);
btndelete2 = itemView.findViewById(R.id.btndelete2);
btndelete2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setMessage("Are you sure you want to delete this?");
alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setPositiveButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
final AlertDialog dialogs = alert.create();
dialogs.show();
dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete(getAdapterPosition());
dialogs.dismiss();
}
});
dialogs.getButton(androidx.appcompat.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogs.dismiss();
}
});
}
});
}
private void delete(int adapterPosition) {
cgpaArrayList.remove(adapterPosition);
notifyDataSetChanged();
final String snc = cname.getText().toString();
final String semrc = no_of_sems.getText().toString();
final String schc = schemec.getText().toString();
dbmanager db = new dbmanager(itemView.getContext());
db.delete2(snc, semrc, schc);
}
}
}

Related

All itmes disappear when try use searchview in recyclerview?

everyone
I have recyclerView retrieve data from firebase database
I used searchview and filter list to search item , but when click on searchview to search something all items disappear and search view not working
my main activity is fragment because I use bottom navigation
public class RV_Worker_Fragment extends Fragment implements RecyclerView_InterFace {
private RecyclerView rv_worker;
private FirebaseDatabase db;
private ArrayList <WorkerModel> list;
private WorkerAdapter workerAdapter;
SearchView searchView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rv_persons_fragment,
container, false);
rv_worker =view.findViewById(R.id.recyclerView_persons);
db =FirebaseDatabase.getInstance();
rv_worker.setHasFixedSize(true);
rv_worker.setLayoutManager(new LinearLayoutManager(getActivity()));
searchView = view.findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
workerAdapter.getFilter().filter(newText);
return false;
}
});
getList();
return view;
}
private void getList()
{
db.getReference("Employees").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list=new ArrayList <>();
workerAdapter = new WorkerAdapter(getActivity(),list,RV_Worker_Fragment.this);
rv_worker.setAdapter(workerAdapter);
for (DataSnapshot child :snapshot.getChildren())
{
WorkerModel workerModel =child.getValue(WorkerModel.class);
list.add(workerModel);
workerAdapter.notifyItemInserted(list.size()-1);
workerAdapter.getItemCount();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(final int position) {
Intent intent = new Intent(getActivity(), Worker_Details.class);
intent.putExtra("name",list.get(position).getName());
intent.putExtra("id",list.get(position).getId());
startActivity(intent);
}
}
Adapter
public class WorkerAdapter extends RecyclerView.Adapter <WorkerAdapter.ViewHolder> implements Filterable {
private Context context;
private List <WorkerModel> list;
private List <WorkerModel> listFilter;
private RecyclerView_InterFace recyclerView_interFace;
public WorkerAdapter(Context context, List <WorkerModel> llist, RecyclerView_InterFace recyclerView_interFace) {
this.context = context;
this.list = llist;
this.recyclerView_interFace = recyclerView_interFace;
listFilter = new ArrayList <>(list);
}
#NonNull
#Override
public WorkerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_worker_treader_contractor, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final WorkerAdapter.ViewHolder holder, final int position) {
final WorkerModel workerModel = list.get(position);
holder.tv_name.setText(workerModel.getName());
holder.btn_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phonNumber = workerModel.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+phonNumber));
context.startActivity(intent);
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(context)
.setTitle("حذف")
.setMessage("هل تريد الحذف")
.setPositiveButton("نعم", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference("Employees");
db.child(list.get(position).getId()).removeValue();
}
})
.setNegativeButton("لا",null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_name;
ImageView btn_call, btn_delete ;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tx_name);
btn_call = itemView.findViewById(R.id.btn_call);
btn_delete = itemView.findViewById(R.id.btn_deleteP);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerView_interFace.onItemClick(getAdapterPosition());
}
});
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<WorkerModel> listFilter2 = new ArrayList <>();
if (charSequence ==null || charSequence.length()==0){
// if search text is empty add all original list values to filterlist
listFilter2.addAll(listFilter);
}else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
for (WorkerModel workerModel : listFilter){
if (workerModel.getName().toLowerCase().contains(filterPattern)){
listFilter2.add(workerModel);
}
}
}
FilterResults results = new FilterResults();
results.values = listFilter2;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
list.clear();
list.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
}
what is the problem guys?
thx in advance for help
Try inside performFiltering() of WorkerAdapter, add the following line as the first line: if (listFilter.size() == 0) listFilter = new ArrayList<>(list);

i have recyclerview with searchview how to send details data about item i searched about

I have recyclerview with searchview and have details data sended when select item in recyclerview
problem is when i search about item and select it the details data not change always appears the first item's details data
how can i send details data about the items that i searched about
i think it not big issue so pls help me
this my code:
in my Main avtivity
private void initRecyclerView(){
RecyclerView recyclerView = findViewById(R.id.recyclerView);
// adapter = new RecyclerViewAdapter(mNames,mImageUsls,this);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(menuItems,this);
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(int position) {
com.example.t.MenuItem menuItemmmmm = menuItems.get(position);
Intent intent = new Intent(secondActivity.this,details_page.class);
intent.putExtra("image",menuItemmmmm.getImageResource());
intent.putExtra("name",menuItemmmmm.getOilName());
intent.putExtra("details1",details.get(position));
intent.putExtra("details2",details2.get(position));
intent.putExtra("details3",details3.get(position));
intent.putExtra("details4",details4.get(position));
intent.putExtra("details5",details5.get(position));
intent.putExtra("details6",details6.get(position));
intent.putExtra("howToUse",howToUse.get(position));
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView =(SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
RecyclerviwAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private List<MenuItem> MenuItemsList;
private List<MenuItem> MenuItemListFilter; // نسخة من الزيوت
private RecyclerViewOnItemClick recyclerViewOnItemClick;
public RecyclerViewAdapter(List <MenuItem> nMenuItemsList, RecyclerViewOnItemClick NrecyclerViewOnItemClick) {
this.MenuItemsList = nMenuItemsList;
this.recyclerViewOnItemClick = NrecyclerViewOnItemClick;
MenuItemListFilter = new ArrayList <>(MenuItemsList);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item,parent,false);
ViewHolder holder =new ViewHolder(view,recyclerViewOnItemClick);
return holder; }
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
MenuItem menuItem = MenuItemsList.get(position);
holder.image.setImageResource(menuItem.getImageResource());
holder.imageName.setText(menuItem.getOilName());
}
#Override
public int getItemCount() {
return MenuItemsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView image;
TextView imageName;
CardView parentLayout;
RecyclerViewOnItemClick recyclerViewOnItemClick;
public ViewHolder(#NonNull View itemView , RecyclerViewOnItemClick recyclerViewOnItemClick) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.RelativeLayout);
this.recyclerViewOnItemClick =recyclerViewOnItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
recyclerViewOnItemClick.onItemClick(getAdapterPosition());
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<MenuItem> filterList = new ArrayList <>();
if (charSequence ==null || charSequence.length()==0){
// if search text is empty add all original list values to filterlist
filterList.addAll(MenuItemListFilter);
}else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
for (MenuItem menuu : MenuItemListFilter){
if (menuu.getOilName().toLowerCase().contains(filterPattern)){
filterList.add(menuu);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
MenuItemsList.clear();
MenuItemsList.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
public interface RecyclerViewOnItemClick {
void onItemClick(int position);
}
}
Avtivity that i send data to it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_of_oil);
imageView= findViewById(R.id.image_name);
Pdetails =findViewById(R.id.deltail_Text1);
Pdetails2 =findViewById(R.id.deltail_Text2);
Pdetails3 =findViewById(R.id.deltail_Text3);
Pdetails4 =findViewById(R.id.deltail_Text4);
Pdetails5 =findViewById(R.id.deltail_Text5);
Pdetails6 =findViewById(R.id.deltail_Text6);
price = findViewById(R.id.price);
toolbar =findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle extra = getIntent().getExtras();
if (extra != null){
int image = extra.getInt("image");
String name = extra.getString("name");
String detail1 = extra.getString("details1");
String detail2 = extra.getString("details2");
String detail3 = extra.getString("details3");
String detail4 = extra.getString("details4");
String detail5 = extra.getString("details5");
String detail6 = extra.getString("details6");
String TpriceT = extra.getString("howToUse");
imageView.setImageResource(image);
toolbar.setTitle(name);
Pdetails.setText(detail1);
Pdetails2.setText(detail2);
Pdetails3.setText(detail3);
Pdetails4.setText(detail4);
Pdetails5.setText(detail5);
Pdetails6.setText(detail6);
price.setText(TpriceT);
}
}
Glad you solved the issue. Below is the adapter code for 2nd solution:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private List<MenuItem> MenuItemsList;
private List<Integer> filteredId;
private RecyclerViewOnItemClick recyclerViewOnItemClick;
public RecyclerViewAdapter(List<MenuItem> nMenuItemsList, RecyclerViewOnItemClick NrecyclerViewOnItemClick) {
this.MenuItemsList = nMenuItemsList;
this.recyclerViewOnItemClick = NrecyclerViewOnItemClick;
filteredId = new ArrayList<>();
setDefaultIds(filteredId);
}
private void setDefaultIds(List<Integer> dataList) {
dataList.clear();
for (int i = 0; i < MenuItemsList.size(); i++) dataList.add(i);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item, parent, false);
ViewHolder holder = new ViewHolder(view, recyclerViewOnItemClick);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
MenuItem menuItem = MenuItemsList.get(filteredId.get(position));
holder.image.setImageResource(menuItem.getImageResource());
holder.imageName.setText(menuItem.getOilName());
}
#Override
public int getItemCount() {
return filteredId.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView imageName;
CardView parentLayout;
RecyclerViewOnItemClick recyclerViewOnItemClick;
public ViewHolder(#NonNull View itemView, RecyclerViewOnItemClick recyclerViewOnItemClick) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.RelativeLayout);
this.recyclerViewOnItemClick = recyclerViewOnItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
recyclerViewOnItemClick.onItemClick(filteredId.get(getAdapterPosition()));
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<Integer> filterList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
// if search text is empty add all original list values to filterlist
setDefaultIds(filterList);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
MenuItem menuu;
for (int i = 0; i < MenuItemsList.size(); i++) {
menuu = MenuItemsList.get(i);
if (menuu.getOilName().toLowerCase().contains(filterPattern)) {
filterList.add(i);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredId.clear();
filteredId.addAll((List<Integer>) filterResults.values);
notifyDataSetChanged();
}
};
public interface RecyclerViewOnItemClick {
void onItemClick(int id);
}
}

String android.content.Context.getPackageName

Hi I have a problem with click on the cardview, in practice since I added a searchview on the toolbar to search for items on the list I create, selecting an object in the list does not allow me to go to change parameters through the edit class
you would be so kind as to help me solve this problem and help me understand where I'm wrong
RoomAdapter
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.TicketHolder> implements Filterable {
//List<TicketEntity> ticketEntity = new ArrayList<>();
private List<TicketEntity> ticketEntity;
private List<TicketEntity> ticketEntitySearch;
private Context mCtx;
public RoomAdapter(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
// this.mCtx = mCtx;
ticketEntitySearch = new ArrayList<>(ticketEntity);
}
#Override
public TicketHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_recyclerview, parent, false);
return new TicketHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TicketHolder holder, int position) {
TicketEntity currenTicket = ticketEntity.get(position);
holder.mTextticket.setText(currenTicket.getNumticket());
holder.mTextredattore.setText(currenTicket.getRedattore());
holder.mTexttarga.setText(currenTicket.getTarga());
holder.mTextdataA.setText(currenTicket.getDopen());
holder.mTextmanutenzioneG.setText(currenTicket.getMateriale());
holder.mTextdataC.setText(currenTicket.getDclosed());
}
#Override
public int getItemCount() {
return ticketEntity.size();
}
public void setTicketEntity(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
notifyDataSetChanged();
}
void setTickets(List<TicketEntity> tickets){
ticketEntity = tickets;
notifyDataSetChanged();
}
#Override
public Filter getFilter() {
return ticketFilter;
}
private Filter ticketFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<TicketEntity>filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0){
filteredList.addAll(ticketEntitySearch);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for (TicketEntity item : ticketEntitySearch){
if(item.getNumticket().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ticketEntity.clear();
ticketEntity.addAll((List)results.values);
notifyDataSetChanged();
}
};
class TicketHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mTextticket,mTextredattore,mTexttarga,mTextdataA,mTextmanutenzioneG,mTextdataC;
Context mCtx;
//todo Costructor
public TicketHolder(#NonNull View itemView) {
super(itemView);
mTextticket = itemView.findViewById(R.id.txt_ticket);
mTextredattore = itemView.findViewById(R.id.txt_redattore);
mTexttarga = itemView.findViewById(R.id.txt_targa);
mTextdataA = itemView.findViewById(R.id.txt_dataA);
mTextmanutenzioneG = itemView.findViewById(R.id.txt_materiale);
mTextdataC = itemView.findViewById(R.id.txt_dataC);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TicketEntity ticket = ticketEntity.get(getAdapterPosition());
Intent intent = new Intent(mCtx,ModificaActivity.class);
intent.putExtra("ticket", ticket);
mCtx.startActivity(intent);
}
}
/*public TicketEntity getTicketSwipe(int position){
return ticketEntity.get(position);
}
*/
}
Visualizza
package alessandro.mystudio.ticketfirebase;
public class Visualizza extends AppCompatActivity {
RecyclerView mRecyclerView;
Toolbar mToolbar;
List<TicketEntity> tickets;
RoomAdapter adapter;
private AppDatabase appDatabase;
private Context mCtx;
//private static final String TAG = "Visualizza";
//public static final int ADD_TICKET_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
mToolbar = findViewById(R.id.toolbarLayout);
setSupportActionBar(mToolbar);
appDatabase = AppDatabase.getDatabase(this);
BuildRecyclearView();
new getAll().execute();
new ItemTouchHelper(simpleCallback).attachToRecyclerView(mRecyclerView);
}
//TODO METODO DI SWIPE DELETE SULLA CARDVIEW
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT)
{
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if(tickets !=null){
TicketEntity swipedTicket = tickets.get(viewHolder.getAdapterPosition());
if(swipedTicket != null){
swipeToDelete(swipedTicket, viewHolder);
}
}
}
};
//TODO MESSAGGIO ALERT DIALOG DI CONFERMA OPPURE DI ANNULLARE
private void swipeToDelete( final TicketEntity swipedTicket, final RecyclerView.ViewHolder viewHolder) {
new AlertDialog.Builder(Visualizza.this)
.setMessage("Delete Ticket?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 delete note
// Item swiped.
int pos = viewHolder.getAdapterPosition();
// Remove from database
new deleteTicket(pos).execute(tickets.get(pos));
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 Undo swipe and restore swipedNote
mRecyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());
}
})
.setCancelable(false)
.create().show();
}
//TODO Costruzione della RecyclerView
public void BuildRecyclearView() {
//todo dichiarazione adapter e chiamiamo il suo costruttore passandogli i parametri necessari
mRecyclerView = findViewById(R.id.miorecyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
//TODO VISUALIZZARE TUTTI I TICKET
private class getAll extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... voids) {
tickets = (List<TicketEntity>) appDatabase.ticketDao().getAll();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new RoomAdapter(tickets);
mRecyclerView.setAdapter(adapter);
}
}
//TODO MESSAGGIO DI ALERDIALOG
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setIcon(R.drawable.ic_error);
builder.setMessage(Message);
builder.show();
}
//TODO Procedura ToolBar Menu & SearchView
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
//searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
//TODO DELETE TICKET
private class deleteTicket extends AsyncTask<TicketEntity, Void, Void>
{
int pos;
public deleteTicket(int pos) {
this.pos = pos;
}
#Override
protected Void doInBackground(TicketEntity... ticketEntities) {
appDatabase.ticketDao().deleteTicket(ticketEntities[0].getId());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
tickets.remove(pos);
adapter.notifyItemRemoved(pos);
}
}
}

Clicking on a RecyclerView after search doesn't yield correct data

I have a fragment which displays a list of hotels on a RecyclerView. Only the hotel names are displayed. If one of the names is clicked, an activity will launched, which displays the hotel detail (name, address, location, room count). To make life easier, I also have a SearchView, so user can simply search the hotel name instead of scrolling.
HotelFragment.java
public class HotelFragment extends Fragment {
ArrayList<Kost> hotelList = new ArrayList<>();
HotelAdapter mAdapter;
SearchView searchView;
public HotelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.hotel_fragment, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
hotelAdapter = new KostAdapter(mList);
// if a hotel is clicked, launch an activity which displays its full information
mAdapter.setOnItemClickListener(new ClickListener() {
#Override
public void onItemClick(int position, View v) {
Hotel hotel = hotelList.get(position);
Bundle bnd = new Bundle();
bnd.putString("hotel_name", hotel.getName());
bnd.putString("hotel_description", hotel.getDescription());
bnd.putString("hotel_address", hotel.getAddress());
bnd.putString("hotel_room", hotel.getRoom());
bnd.putString("hotel_latitude", hotel.getLatitude());
bnd.putString("hotel_longitude", hotel.getLongitude());
Intent iii = new Intent(getActivity(), HotelDetailActivity.class);
iii.putExtra("hotel_detail", bnd);
startActivity(iii);
}
#Override
public void onItemLongClick(int position, View v) {
}
});
searchView = (SearchView) view.findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
hotelAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
hotelAdapter.getFilter().filter(query);
return false;
}
});
hotelAdapter.notifyDataSetChanged();
recyclerView.setAdapter(hotelAdapter);
getHotelListFromFirebase();
return view;
}
}
HotelAdapter.java
public class HotelAdapter extends RecyclerView.Adapter<HotelAdapter.ViewHolder> implements Filterable {
static ClickListener clickListener;
ArrayList<Hotel> hotelList;
ArrayList<Hotel> hotelList_filtered;
public KostAdapter(ArrayList<Hotel> hotelList)
{
this.hotelList = hotelList;
this.hotelList_filtered = hotelList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Hotel hotel = hotelList_filtered.get(position);
holder.tvName.setText(hotel.getName());
holder.tvDescription.setText(hotel.getDescription());
holder.tvAddress.setText(hotel.getAddress());
}
#Override
public int getItemCount() {
if (hotelList_filtered != null) return hotelList_filtered.size();
return 0;
}
public void setOnItemClickListener(ClickListener clickListener) {
HotelAdapter.clickListener = clickListener;
}
#Override
public Filter getFilter() {
return new Filter(){
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String sequence = charSequence.toString().toLowerCase();
if (sequence.isEmpty()) kostList_filtered = kostList;
else {
ArrayList<Hotel> filteredList = new ArrayList<>();
for (Hotel h : hotelList){
if (h.getName().toLowerCase().contains(sequence)){
filteredList.add(h);
}
}
hotelList_filtered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = kostList_filtered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
hotelList_filtered = (ArrayList<Hotel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView tvName;
TextView tvDescription;
TextView tvAddressl
public ViewHolder(View itemView)
{
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvAddress = (TextView) itemView.findViewById(R.id.tvAddress);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
}
#Override
public boolean onLongClick(View view) {
clickListener.onItemLongClick(getAdapterPosition(), view);
return false;
}
}
}
ClickListener.java
public interface ClickListener {
void onItemClick(int position, View v);
void onItemLongClick(int position, View v);
}
Displaying the initial list and search are fine. No problem so far. The issue is clicking the hotel after search.
Say the initial hotel list is:
{"Hotel Foobar", "Hotel California", "Hotel 2112", "Hotel Crimson"}
If I search for "2112", the RecyclerView will only show "Hotel 2112" (which is correct), but clicking it will display the detail of "Hotel Foobar". I think this because
Hotel hotel = hotelList.get(position);
and position is 0.
How to fix this?
Instead of using the list with all the hotels, try using the list that is currently being used.
hotelAdapter.hotelList_filtered.get(position);
Relpace this , I have also used same thing on my project i used as below its gives correct result
#Override
public int getItemCount() {
if (hotelList_filtered != null) return hotelList_filtered.size();
return 0;
}
with,
#Override
public int getItemCount() {
if (hotelList_filtered != null)
return hotelList_filtered.size();
}
you are getting data from your filter list so no issue with this
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Hotel hotel = hotelList_filtered.get(position);
holder.tvName.setText(hotel.getName());
holder.tvDescription.setText(hotel.getDescription());
holder.tvAddress.setText(hotel.getAddress());
}
Get position over here from your filterlist :
#Override
public void onClick(View view) {
clickListener.onItemClick(hotelList_filtered.get(getPosition()), view);
}
#Override
public boolean onLongClick(View view) {
clickListener.onItemLongClick(hotelList_filtered.get(getPosition()), view);
return false;
}

Android filter recycler view data from Retrofit

i have this recycler view and i get data from Retrofit API, the problem is when i tried to make filter in recycler , i search in the internet and all example is list of strings , but i have list of objects , how i can solve this case and create filter in the toolbar ? i will post my code and hope anyone to help , thank you
Activity
public class TodoList extends AppCompatActivity implements DialogFragUpdateListener {
RecyclerView todoRecyclerView;
private RecyclerView.Adapter todoAdapter;
private RecyclerView.LayoutManager todoLayoutManager;
public List<ToDo> results;
public List<String> list = new ArrayList<>();
TodoRecyclerAdapter recyclerAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_list);
todoRecyclerView = (RecyclerView)findViewById(R.id.todoRecyclerView);
todoRecyclerView.setHasFixedSize(true);
results= new ArrayList<ToDo>();
todoLayoutManager = new LinearLayoutManager(this);
todoRecyclerView.setLayoutManager(todoLayoutManager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TodoList.this,AddToDo.class);
startActivity(intent);
}
});}
public void getRetrofitObject() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<Result> call = service.getresults();
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
results = response.body().getResults();
if(recyclerAdapter == null){
recyclerAdapter = new TodoRecyclerAdapter(this,results);
todoRecyclerView.setAdapter(recyclerAdapter);
}
else{
recyclerAdapter.setData(results);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("onFailure", t.toString());
}});}
#Override
public void OnDBUpdate() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<Result> call = service.getresults();
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
results = response.body().getResults();
if(recyclerAdapter == null){
recyclerAdapter = new TodoRecyclerAdapter(this,results);
todoRecyclerView.setAdapter(recyclerAdapter);
}
else{
recyclerAdapter.setData(results);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("onFailure", t.toString());
}});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
recyclerAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}}
and this is Adapter
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> {
static List<ToDo> todoResults;
static Context context;
List<ToDo>results;
ArrayList<ToDo> arraylist;
private List<String> mDefaultCheeses;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
}
#Override
public TodoRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_items, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final TodoRecyclerAdapter.ViewHolder holder, final int position) {
holder.todoTitle.setText(todoResults.get(position).getTODO_TITLE().toString());
String priority = todoResults.get(position).getPriority().toString();
if (priority.equals("Low")) {
holder.todoImage.setImageResource(R.drawable.low);
} else if (priority.equals("Normal")) {
holder.todoImage.setImageResource(R.drawable.normal);
} else if (priority.equals("High")) {
holder.todoImage.setImageResource(R.drawable.high);
}
}
#Override
public int getItemCount() {
return todoResults.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView todoTitle;
public ImageView todoImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
todoTitle = (TextView) itemLayoutView.findViewById(R.id.todo_title);
todoImage = (ImageView) itemLayoutView.findViewById(R.id.imageView2);
}}
and this is menu
<menu 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"
tools:context="com.android.nigeriaexams.ui.SettingsFragment">
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/ic_search"
app:showAsAction="collapseActionView|always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:layout_width="wrap_content" />
Add a filter() method to your custom Adapter.
private ArrayList<ToDo> arraylist = null, toDoArrayList;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
this.toDoArrayList = new ArrayList<ToDo>();
this.toDoArrayList.addAll(objects);
}
public void filter(String filterString) {
filterString = filterString.toLowerCase(Locale.getDefault());
arraylist.clear();
if (filterString.length() == 0) {
arraylist.addAll(toDoArrayList);
}
else {
for (ToDo toDO : toDoArrayList) {
if(toDO.getYourSearchValue().toLowerCase(Locale.getDefault()).contains(filterString)) {
arraylist.add(toDO);
}
}
}
notifyDataSetChanged();
}
You can implement Filterable interface in adapter and can do like this
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> implements Filterable {
static List<ToDo> todoResults;
static Context context;
List<ToDo>results;
ArrayList<ToDo> arraylist;
private List<String> mDefaultCheeses;
private ToDoListFilter listFilter;
private List<ToDo> mData;
private List<ToDo> originalData;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
}
public List<ChatListData> getData() {
return mData;
}
public void setData(List<ChatListData> mData) {
this.mData = mData;
if (originalData == null) {
originalData = mData;
}
}
#Override
public TodoRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_items, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final TodoRecyclerAdapter.ViewHolder holder, final int position) {
holder.todoTitle.setText(todoResults.get(position).getTODO_TITLE().toString());
String priority = todoResults.get(position).getPriority().toString();
if (priority.equals("Low")) {
holder.todoImage.setImageResource(R.drawable.low);
} else if (priority.equals("Normal")) {
holder.todoImage.setImageResource(R.drawable.normal);
} else if (priority.equals("High")) {
holder.todoImage.setImageResource(R.drawable.high);
}
}
#Override
public Filter getFilter() {
if (listFilter == null)
listFilter = new ToDoListFilter(this,originalData);
return listFilter;
}
#Override
public int getItemCount() {
return todoResults.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView todoTitle;
public ImageView todoImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
todoTitle = (TextView) itemLayoutView.findViewById(R.id.todo_title);
todoImage = (ImageView) itemLayoutView.findViewById(R.id.imageView2);
}
}
private class ToDoListFilter extends Filter {
private final TodoRecyclerAdapter listAdapter;
private final List<ToDo> originalData;
private List<ToDo> filteredData;
public ToDoListFilter(TodoRecyclerAdapter listAdapter, List<ToDo> originalData) {
this.listAdapter = listAdapter;
this.originalData = originalData;
this.filteredData = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredData.clear();
final FilterResults results = new FilterResults();
Log.d("performFiltering: " , constraint.toString());
if (TextUtils.isEmpty(constraint.toString())) {
filteredData.addAll(originalData);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final ToDo user : originalData) {
// set condition for filter here
if (user.getToUserName().toLowerCase().contains(filterPattern)) {
filteredData.add(user);
}
}
}
results.values = filteredData;
results.count = filteredData.size();
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
//listAdapter.getData().clear();
listAdapter.setData((List<ToDo>) filterResults.values);
listAdapter.notifyDataSetChanged();
}
}
}
And to call this
listAdapter.getFilter().filter(query);
For more check here
Hope it will solve your problem...
I have tried below code :
I think it will work.
public class SearchAdapter extends RecyclerView.Adapter implements Filterable {
private ItemFilter itemFilter;
private ArrayList<CommonModel> arrayList;//filtered emoji collection
private ArrayList<CommonModel> fullList;//Full emoji collection
private Context context;
public SearchAdapter(final Context context, final ArrayList<CommonModel> arrayList) {
this.arrayList = arrayList;
this.fullList = arrayList;
this.context = context;
itemFilter = new ItemFilter();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_search, parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(KeyboardEmojiSearchAdapter.ViewHolder holder, int position) {
final CommonModel commonModel = arrayList.get(position);
Glide.with(context).load(commonModel.getDisplayImage()).asBitmap().into(holder.iv);
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public Filter getFilter() {
return itemFilter;
}
/**
* Holder class to hold grid item
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private ImageView iv;
public ViewHolder(View view) {
super(view);
iv = (ImageView) view.findViewById(R.id.row_search_iv);
}
}
/**
* Filter class allows filtering by tags from Emoji collection
*/
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults results = new FilterResults();
final ArrayList<CommonModel> newFilteredList = new ArrayList<>();
if (constraint.toString().trim().length() > 0) {
final String filterString = constraint.toString().toLowerCase();
final int count = fullList.size();
for (int i = 0; i < count; i++) {
for (int j = 0; j < fullList.get(i).getTagList().size(); j++) {
if (fullList.get(i).getTagList().get(j).toLowerCase().startsWith(filterString)) {
newFilteredList.add(fullList.get(i));
break;
}
}
}
} else {
newFilteredList.addAll(fullList);
}
results.values = newFilteredList;
results.count = newFilteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (ArrayList<CommonModel>) results.values;
notifyDataSetChanged();
}
}
Please refer below code.
edtSearch.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) {
gridAdapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});

Categories

Resources