All itmes disappear when try use searchview in recyclerview? - android

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);

Related

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);
}
}

Not getting proper results after performing search

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);
}
}
}

How to add Search Filter in RecyclerView from firebase [duplicate]

This question already has an answer here:
Firebase Realtime Database Search by word in between the query?
(1 answer)
Closed 4 years ago.
I have worked for search about how to search in FireBase by value and I couldn't have a fully answer so I am asking now
I have used this method and I couldn't get the correct result:
public class Search extends Fragment {
public Search() {
// Required empty public constructor
}
private SearchView mSearch;
private RecyclerView rvSearch;
private DatabaseReference mRef;
private SearchPlaceAdapter mAdapter;
ArrayList<Place> arrayList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
//Recylerview of place
rvSearch = (RecyclerView) view.findViewById(R.id.rvSearch);
rvSearch.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
//final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvSearch.setLayoutManager(layoutManager);
mRef = FirebaseDatabase.getInstance().getReference();
mRef.child("Place").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
arrayList = new ArrayList<>();
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
arrayList.add(eventSnapshot.getValue(Place.class));
}
mAdapter = new SearchPlaceAdapter(getContext(), arrayList);
rvSearch.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//searchView of place
mSearch = (SearchView) view.findViewById(R.id.mSearch);
mSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(mAdapter!=null){
mAdapter.getFilter().filter(newText);
}
return false;
}
});
return view;
}
}
Adapter Code
......................................................
public class SearchPlaceAdapter extends RecyclerView.Adapter<SearchPlaceAdapter.SearchPlaceAdapterViewHolder> implements Filterable {
Context mCntx;
public ArrayList<Place> arrayList;
public ArrayList<Place> arrayListFiltered;
public SearchPlaceAdapter(Context mCntx, ArrayList<Place> arrayList)
{
this.mCntx = mCntx;
this.arrayList = arrayList;
arrayListFiltered = arrayList;
/*arrayListFiltered = new ArrayList<>(arrayList);*/
}
#Override
public int getItemCount()
{
return arrayList.size();
}
public long getItemId(int position)
{
return position;
}
#Override
public SearchPlaceAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_layout, parent, false);
SearchPlaceAdapterViewHolder viewHolder = new SearchPlaceAdapterViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(SearchPlaceAdapterViewHolder holder, final int position)
{
final Place place = arrayList.get(position);
holder.txtPlace.setText(arrayList.get(position).getBuilding());
Picasso.with(mCntx).load(place.getPlaceImg()).into(holder.image);//using picasso to load image
holder.cardPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(mCntx, CardviewSearch.class);
intent.putExtra("placeId", String.valueOf(place.getPlaceId()));
intent.putExtra("building", String.valueOf(place.getBuilding()));
intent.putExtra("street", String.valueOf(place.getStreet()));
intent.putExtra("imgurl", String.valueOf(place.getPlaceImg()));
mCntx.startActivity(intent);
}
});
}
public class SearchPlaceAdapterViewHolder extends RecyclerView.ViewHolder
{
TextView txtPlace;
ImageView image;
CardView cardPlace;
public SearchPlaceAdapterViewHolder(View itemView) {
super(itemView);
txtPlace = (TextView) itemView.findViewById(R.id.txtPlace);
image = (ImageView) itemView.findViewById(R.id.image);
cardPlace = (CardView) itemView.findViewById(R.id.cardPlace);
}
}
public Filter getFilter()
{
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Place> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(arrayListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Place item : arrayListFull) {
if (item.getBuilding().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
arrayList.clear();
arrayList.addAll((List)results.values);
notifyDataSetChanged();
}
};
}
It only search by front keyword not the whole thing filtered. How to use contains?
I wanted the values to be searched with every possible values not only by front values. Please I need help.
Hope it helps:
public class SearchPlaceAdapter extends RecyclerView.Adapter<SearchPlaceAdapter.SearchPlaceAdapterViewHolder> implements Filterable {
Context mCntx;
public ArrayList<Place> arrayList;
public ArrayList<Place> arrayListFiltered;
public SearchPlaceAdapter(Context mCntx, ArrayList<Place> arrayList)
{
this.mCntx = mCntx;
this.arrayList = arrayList;
this.arrayListFiltered = new ArrayList<>(arrayList);
}
#Override
public int getItemCount()
{
return arrayList.size();
}
public long getItemId(int position)
{
return position;
}
#Override
public SearchPlaceAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_layout, parent, false);
SearchPlaceAdapterViewHolder viewHolder = new SearchPlaceAdapterViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(SearchPlaceAdapterViewHolder holder, final int position)
{
final Place place = arrayList.get(position);
holder.txtPlace.setText(arrayList.get(position).getBuilding());
Picasso.with(mCntx).load(place.getPlaceImg()).into(holder.image);//using picasso to load image
holder.cardPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(mCntx, CardviewSearch.class);
intent.putExtra("placeId", String.valueOf(place.getPlaceId()));
intent.putExtra("building", String.valueOf(place.getBuilding()));
intent.putExtra("street", String.valueOf(place.getStreet()));
intent.putExtra("imgurl", String.valueOf(place.getPlaceImg()));
mCntx.startActivity(intent);
}
});
}
public class SearchPlaceAdapterViewHolder extends RecyclerView.ViewHolder
{
TextView txtPlace;
ImageView image;
CardView cardPlace;
public SearchPlaceAdapterViewHolder(View itemView) {
super(itemView);
txtPlace = (TextView) itemView.findViewById(R.id.txtPlace);
image = (ImageView) itemView.findViewById(R.id.image);
cardPlace = (CardView) itemView.findViewById(R.id.cardPlace);
}
}
public Filter getFilter()
{
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Place> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(arrayListFiltered);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Place item : arrayListFiltered) {
if (item.getBuilding().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
arrayList.clear();
arrayList.addAll((List)results.values);
notifyDataSetChanged();
}
};
}

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;
}

wrong positions of two arrays after filter

I created a recyclerview that takes data from Firebase. I have two arrays that are sent to the adapter to be used in the items. I've implemented a search filter. This works for the first array, but the second one is always in the starting position. How can I get the second array in the same position as the first filter? Thank you
MainActivity
public class FriendActivity3 extends AppCompatActivity
//implements FriendHoldAdapter3.ItemClickListener{
FriendHoldAdapter3 adapter;
RecyclerView recyclerView;
ArrayList<FriendItem> username;
ArrayList<String> uid, url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend2);
SearchView search = (SearchView) findViewById(R.id.ciao);
recyclerView = (RecyclerView) findViewById(R.id.friend_list2);
//recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
final DatabaseReference mPostReference = FirebaseDatabase.getInstance().getReference().child("user-profile");
mPostReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
username = new ArrayList<>();
uid = new ArrayList<String>();
url = new ArrayList<String>();
for (DataSnapshot data : dataSnapshot.getChildren()){
final FriendItem friendItem = data.getValue(FriendItem.class);
final String friendItem2 = data.getKey();
username.add(friendItem);
uid.add(friendItem2);
adapter = new FriendHoldAdapter3(getApplicationContext(), username, uid, url);
//adapter.setClickListener(FriendActivity3.this);
recyclerView.setAdapter(adapter);
/**
adapter = new FriendHoldAdapter2(FriendActivity2.this, username, uid);
adapter.setClickListener(FriendActivity2.this);
recyclerView.setAdapter(adapter);
**/
final List<FriendItem> filteredModelList = filter(username, " ");
adapter.setFilter(filteredModelList);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.equals("")){
newText = " ";
}
if (newText.equals("View All")){
newText = "";
}
final List<FriendItem> filteredModelList = filter(username, newText);
adapter.setFilter(filteredModelList);
return true;
}
});
private List<FriendItem> filter(List<FriendItem> models, String query) {
query = query.toLowerCase();final List<FriendItem> filteredModelList = new ArrayList<>();
for (FriendItem model : models) {
final String text = model.username.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}}
Adapter
public class FriendHoldAdapter3 extends RecyclerView.Adapter<FriendHoldAdapter3.ViewHolder> {
private List<FriendItem> mData_username = Collections.emptyList();
private List<String> mData_uid = Collections.emptyList();
private List<String> mData_url = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public FriendHoldAdapter3(Context context, List<FriendItem> data_username, List<String> data_uid, List<String> data_url) {
this.mInflater = LayoutInflater.from(context);
this.mData_username = data_username;
this.mData_uid = data_uid;
this.mData_url = data_url;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.friend_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FriendItem username = mData_username.get(position);
String uid = mData_uid.get(position);
holder.myTextView.setText(username.username);
holder.uid_txt.setText(uid);
}
// total number of rows
#Override
public int getItemCount() {
return mData_username.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView, uid_txt;
public ViewHolder(final View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.friend_item_name);
uid_txt = (TextView) itemView.findViewById(R.id.friend_item_uid);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(),mData_uid.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
if (uid_txt.getText().toString()!=null | !uid_txt.getText().toString().equals("") ){
Intent intent = new Intent(itemView.getContext(), AccountPubblic.class);
//MANDARE TESTO A AccountPubblic
intent.putExtra(AccountPubblic.EXTRA_UID, uid_txt.getText().toString());
itemView.getContext().startActivity(intent);
}
}
});
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public FriendItem getItem(int id) {
return mData_username.get(id);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
public void setFilter(List<FriendItem> countryModels) {
mData_username = new ArrayList<>();
mData_username.addAll(countryModels);
notifyDataSetChanged();
}}

Categories

Resources