SearchView problem with recyclerView populated from Firebase - android

I have a RecyclerView thats populated from my Firebase Database. The list is quite long so I want the user to be able to search the list. But when the user types the first character into the SearchView, nothing at all is returned.
This is the onCreateView in my FavouriteFragment UPDATED
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_favourites, container, false);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
recyclerView = (RecyclerView) view.findViewById(R.id.route_favourites);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
search = (SearchView) view.findViewById(R.id.search);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("BusRoute");
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot datasnapshot : dataSnapshot.getChildren()){
String key = datasnapshot.getKey();
Query query = rootRef.child(key).orderByChild("route").equalTo(newText);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
favouritesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return true;
}
});
favouritesAdapter = new FavouritesAdapter(getDataSetHistory(), getActivity());
favouritesAdapter.notifyDataSetChanged();
recyclerView.setAdapter(favouritesAdapter);
getBusRoutes();
return view;
}
This is my favouritesAdapter:
public class FavouritesAdapter extends RecyclerView.Adapter<FavouritesAdapter.ViewHolder> implements Filterable {
private List<BusRoute> favourites;
private List<BusRoute> searchList;
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView routeTextView, originTextView, destinationTextView;
ImageView addFavouritesButton;
ViewHolder(View v){
super(v);
this.routeTextView = v.findViewById(R.id.route);
this.destinationTextView = v.findViewById(R.id.destination);
this.originTextView = v.findViewById(R.id.origin);
this.addFavouritesButton = v.findViewById(R.id.addToFavourites);
addFavouritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String route = routeTextView.getText().toString();
System.out.println("clicked");
System.out.println(route);
//addToFavourites(route);
}
});
}
#NonNull
#Override
public FavouritesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.favourite_card, parent, false);
return new FavouritesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FavouritesAdapter.ViewHolder viewHolder, int i) {
BusRoute bus = favourites.get(i);
viewHolder.originTextView.setText(String.valueOf(bus.getOrigin()));
viewHolder.destinationTextView.setText(String.valueOf(bus.getDestination()));
viewHolder.routeTextView.setText(String.valueOf(bus.getRoute()));
}
public FavouritesAdapter(ArrayList<BusRoute> favourites, Context context){
this.context = context;
this.favourites = favourites;
searchList = new ArrayList<>(favourites);
}
#Override
public int getItemCount() {
System.out.println(favourites);
return favourites.size();
}
#Override
public Filter getFilter() {
return favouriteFilter;
}
private Filter favouriteFilter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("filter results");
List<BusRoute> filteredList = new ArrayList<>();
if(constraint==null || constraint.length()==0){
filteredList.addAll(searchList);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for(BusRoute br : searchList){
if(br.getRoute().toLowerCase().contains(filterPattern)){
filteredList.add(br);
}else{
System.out.println("nothing here");
}
}
}
System.out.println("set filter results");
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
favourites.clear();
favourites.addAll((List)results.values);
notifyDataSetChanged();
}
};
}
I just want to have a filterable search bar but cannot get it working! I'd appreciate any help at all!

In publish results method. Don't clear your array list. That is the reason for empty data

Try this
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String query = charSequence.toString();
List<String> filtered = new ArrayList<>();
if (query.isEmpty()) {
filtered = items;
} else {
for (String movie : items) {
if (movie.toLowerCase().contains(query.toLowerCase())) {
filtered.add(movie);
}
}
}
FilterResults results = new FilterResults();
results.count = filtered.size();
results.values = filtered;
return results;
}

Related

Android search view won't work in fragment

When I try to search for members in the search view nothing shows up. Everything just vanishes.
all_members
public class all_members extends Fragment {
ProgressDialog pg;
RecyclerView recyclerView;
AllMembersCustomAdapter myAdapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<AllMembersRecyclerRepresent> members;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
FragmentTransaction fr = getActivity().getSupportFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container,new Home());
fr.commit();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(callback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this line is very important the bwlo line will set the search view
setHasOptionsMenu(true);
return inflater.inflate(R.layout.all_member, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
pg=new ProgressDialog(getContext());
pg.setTitle("Please wait...");
pg.setMessage("Loading all members");
pg.setCanceledOnTouchOutside(false);
pg.show();
setHasOptionsMenu(true);
super.onViewCreated(view, savedInstanceState);
recyclerView=getActivity().findViewById(R.id.r_view_member);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
members = new ArrayList<>();
getvolley();
Log.d("mem",members.toString());
recyclerView.setLayoutManager(layoutManager);
myAdapter = new AllMembersCustomAdapter(members);
recyclerView.setAdapter(myAdapter);
}
public void getvolley(){
//volley and get all members list
String url="";
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonArrayRequest requestUrl=new JsonArrayRequest(Request.Method.POST, url, null,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i=0;i< response.length();i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
AllMembersRecyclerRepresent ar= new AllMembersRecyclerRepresent();
ar.setName( jsonObject.getString("name"));
ar.setSurname( jsonObject.getString("surname"));
ar.setPh_no( jsonObject.getString("ph_no"));
String id=( jsonObject.getString("member_id"));
String email=( jsonObject.getString("email"));
String is_active=( jsonObject.getString("is_active"));
String dob=( jsonObject.getString("date_of_birth"));
String medical_history=( jsonObject.getString("medical_history"));
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(dob, formatter);
ar.setDOB(String.valueOf(date));
Log.d("date:",String.valueOf(date));
ar.setId(id);
ar.setDOB(String.valueOf(date));
ar.setEmail(email);
ar.setIs_active(is_active);
ar.setMedical_history(medical_history);
ar.setIs_active(is_active);
members.add(ar);
} catch (JSONException e) {
e.printStackTrace();
}
myAdapter.notifyDataSetChanged();
}
pg.cancel();
Toast.makeText(getContext(), "Total Members: "+myAdapter.getItemCount(), Toast.LENGTH_LONG).show();
Toast.makeText(getContext(), "Total Members: "+myAdapter.getItemCount(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error+"Something went wrong.\nPlease check your internet connection", Toast.LENGTH_LONG).show();
pg.cancel();
}
});
MySingleton.getInstance(getActivity()).addRequestQueue(requestUrl);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menuu,menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
AdapterCode
public class AllMembersCustomAdapter extends RecyclerView.Adapter<AllMembersCustomAdapter.ViewHolder> implements Filterable {
private final ArrayList<AllMembersRecyclerRepresent> members;
//member's list without being filtered
private final ArrayList<AllMembersRecyclerRepresent>allMembers;
public AllMembersCustomAdapter(ArrayList<AllMembersRecyclerRepresent> list){
members=list;
allMembers=new ArrayList<>(list);
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView name,surname,ph_no,dob;
ImageView status;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.nameR);
surname=itemView.findViewById(R.id.surnameR);
ph_no=itemView.findViewById(R.id.ph_noR);
dob=itemView.findViewById(R.id.dob_r);
status=itemView.findViewById(R.id.statusR);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//this returns the position of the item clicked
int position= getAdapterPosition();
//members.get(position).getName() this return the data in the array list
// Toast.makeText(view.getContext(), "position clicked is "+String.valueOf(
// members.get(position).getName()), Toast.LENGTH_SHORT).show();
String name= members.get(position).getName();
String surname = members.get(position).getSurname();
String ph_no = members.get(position).getPh_no();
String id = members.get(position).getId();
String email = members.get(position).getEmail();
String is_active = members.get(position).getIs_active();
String dob = members.get(position).getDOB();
String medical_history = members.get(position).getMedical_history();
Intent i = new Intent(view.getContext(), memberInfo.class);
i.putExtra("name",name);
i.putExtra("surname",surname);
i.putExtra("ph_no",ph_no);
i.putExtra("id",id);
i.putExtra("email",email);
i.putExtra("is_active",is_active);
i.putExtra("dob",dob);
i.putExtra("medical",medical_history);
view.getContext().startActivity(i);
}
});
}
}
#NonNull
#Override
public AllMembersCustomAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_members_recycler,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull AllMembersCustomAdapter.ViewHolder holder, int position) {
holder.itemView.setTag(members.get(position));
holder.name.setText(members.get(position).getName());
holder.ph_no.setText(members.get(position).getPh_no());
holder.surname.setText(members.get(position).getSurname());
holder.dob.setText(members.get(position).getId());
//setting image
//volley to see if the member is Active or not
if(members.get(position).getIs_active()=="true"){
holder.status.setImageResource(R.drawable.active);
}else{
holder.status.setImageResource(R.drawable.inactive);
}
}
#Override
public int getItemCount() {
return members.size();
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
ArrayList<AllMembersRecyclerRepresent> filteredList = new ArrayList<>();
if(charSequence==null || charSequence.length()==0){
//if empty show all movies
filteredList.addAll(allMembers);
}else{
String filterPattern = charSequence.toString().toLowerCase().trim();
for(AllMembersRecyclerRepresent mem:allMembers){
if(mem.getName().toLowerCase().contains(filterPattern)){
filteredList.add(mem);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values=filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
members.clear();
members.addAll((ArrayList) filterResults.values);
notifyDataSetChanged();
}
};
}
When I click on search the list just becomes blank.
menu
<?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:title="SEARCH"
android:icon="#drawable/search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
/>
</menu>
I even tried the same on another activity but still it doesn't work. What am I doing wrong here. The data in the recycler view is being fetched by the server but it won't filter out when clicked on search.

Only get to retrieve last datasets in firebase through recyclerview

I wish to retrieve all the data but not only the last 2 sets.
Is there any solutions to retrieve every data from firebase?
Is is because the for loop or array list is having problem?
=================================================
Updated Photo
I'm trying to retrieve the data [matricno,password and temp]
But the output is only the two sets data inside key [Mdl3FODHWV6zv9d2rNr]
When i try to click on each CardView, the data output is the only the third output photo for three of these CardView.
Output:
=================================================
Userlist1.java
public class userlist1 extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database,ab;
MyAdapter1 myAdapter1;
ArrayList<Report1> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist1);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist1);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend").child(key).child("Attendance");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter1 = new MyAdapter1(this,list);
recyclerView.setAdapter(myAdapter1);
ab.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Report1 report1 = dataSnapshot.getValue(Report1.class);
list.add(report1);
}
myAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
MyAdapter1.java:
public class MyAdapter1 extends RecyclerView.Adapter<MyAdapter1.MyViewHolder> {
Context context;
ArrayList<Report1> list;
public MyAdapter1(Context context, ArrayList<Report1> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item1,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Report1 report1 = list.get(position);
holder.matricno.setText(report1.getMatricno());
holder.password.setText(report1.getPassword());
holder.temp.setText(report1.getTemp());
}
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView matricno, password, temp;
public View view;
public MyViewHolder(#NonNull View itemView){
super(itemView);
matricno = itemView.findViewById(R.id.tvmno);
password = itemView.findViewById(R.id.tvpassword);
temp = itemView.findViewById(R.id.tvtemperature);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View itemView) {
Toast.makeText(itemView.getContext(), "Data added into database", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Report1.java:
public class Report1 {
public String matricno;
public String password;
public String temp;
public Report1(){
}
public String getMatricno() {
return matricno;
}
public String getPassword() {
return password;
}
public String getTemp() {
return temp;
}
}
================================================================
Updated New Code
Userlist.java
public class userlist extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database, ab;
MyAdapter myAdapter;
ArrayList<Report> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
Menu menu;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist);
searchView = findViewById(R.id.action_search);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this, list);
recyclerView.setAdapter(myAdapter);
ab.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Report report = dataSnapshot.getValue(Report.class);
list.add(report);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
myAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
myAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dateascending:
Collections.sort(list, Report.ReportDateOldestComparator);
Toast.makeText(userlist.this, "Sort by Date [Oldest - Latest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.menu_descending:
Collections.sort(list, Report.ReportDateLatestComparator);
Toast.makeText(userlist.this, "Sort by Date [Latest - Oldest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.action_search:
// Not implemented here
return false;
default:
break;
}
searchView.setOnQueryTextListener(queryTextListener);
return super.onOptionsItemSelected(item);
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>implements Filterable {
Context context;
ArrayList<Report> list;
ArrayList<Report> listfilter;
SharedPreferences sharedpreferences;
public MyAdapter(Context context, ArrayList<Report> list) {
this.context = context;
this.list = list;
this.listfilter = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Report report = list.get(position);
holder.time.setText(report.getTime());
holder.duration.setText(report.getDuration());
holder.info.setText(report.getInfo());
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
list = listfilter;
} else {
List<Report> filteredList = new ArrayList<>();
for (Report row : listfilter) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getInfo().toLowerCase().contains(charString.toLowerCase()) || row.getTime().contains(charSequence)) {
filteredList.add(row);
}
}
list = (ArrayList<Report>) filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = list;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
list = (ArrayList<Report>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView duration, time, info;
public View view;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
time = itemView.findViewById(R.id.tvtemp);
duration = itemView.findViewById(R.id.tvfirstName);
info = itemView.findViewById(R.id.tvmatno);
SharedPreferences sharedPreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View itemView) {
sharedpreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("key", key);
editor.putString("temp", temp);
editor.apply();
Intent intent = new Intent(itemView.getContext(), userlist1.class);
itemView.getContext().startActivity(intent);// pass key to next activity;
Toast.makeText(itemView.getContext(), "Data retrieved from database", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Report.java
public class Report {
public String duration;
public String time;
public String info;
public Report(){
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setTime(String time) {
this.time = time;
}
public void setInfo(String info) {
this.info = info;
}
public String getDuration() {
return duration;
}
public String getTime() {
return time;
}
public String getInfo() {
return info;
}
public static Comparator<Report> ReportDateOldestComparator = new Comparator<Report>() {
#Override
public int compare(Report o1, Report o2) {
return o1.getTime().compareTo(o2.getTime());
}
};
public static Comparator<Report> ReportDateLatestComparator = new Comparator<Report>() {
#Override
public int compare(Report o1, Report o2) {
return o2.getTime().compareTo(o1.getTime());
}
};
}
If you want to load the Attendance from all child nodes under Student Attend, you first need to load the data from all those nodes:
ab = database.child(uid).child("Student Attend");
...
ab.addListenerForSingleValueEvent(new ValueEventListener() {
...
Since we'll load data from a higher level in the database, we'll need to navigate across the key and "Attendance" in your onDataChange method now:
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// 👇 loop over `key` level children
for(DataSnapshot childSnapshot : snapshot.getChildren()) {
// 👇 loop over Attendance children
for(DataSnapshot dataSnapshot : childSnapshot.child("Attendance").getChildren()){
Report1 report1 = dataSnapshot.getValue(Report1.class);
list.add(report1);
}
}
myAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // 👈 never ignore errors
}

how to search arraylist data in recyclerview in fragment

I am creating an app I using search view in fragment to search recycler view ArrayList data but below method not showing the result
Not show my filter result in recycler view
How to show filter result in recycle view in the fragment.
anyone tell me what changes below code to fix this problem
please help me
Fragment
import in.getagf.pickuplines.Model.dataAdapter;
import in.getagf.pickuplines.Model.dataItem;
/**
* A simple {#link Fragment} subclass.
*/
public class LatestFragment extends Fragment {
private View myView;
private DatabaseReference RootRef, AdsRef;
private AdView adView;
private RecyclerView mRecyclerView;
dataAdapter mDataAdapter;
private RecyclerView.LayoutManager mDataLayoutManager;
public LatestFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_latest, container, false);
RootRef = FirebaseDatabase.getInstance().getReference().child("App_Data");
AdsRef = FirebaseDatabase.getInstance().getReference().child("Apps Link").child("AdsUnitID");
mRecyclerView = (RecyclerView) myView.findViewById(R.id.latest_recyclerView);
mDataLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mDataLayoutManager);
mDataAdapter = new dataAdapter(getDataSetLines(), getActivity());
mRecyclerView.setAdapter(mDataAdapter);
getResult.clear();
// offlinedata();
receiverData();
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.home, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
mDataAdapter.getFilter().filter(newtext);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void receiverData()
{
RootRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists() && !dataSnapshot.child("category").getValue().toString().equals("Good Night"))
{
String Lines = dataSnapshot.child("lines").getValue().toString();
String Pic = dataSnapshot.child("pic").getValue().toString();
String visite_id = dataSnapshot.getKey();
dataItem obj = new dataItem(visite_id, Lines, Pic);
getResult.add(obj);
mDataAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
AdsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String fB_Latest = dataSnapshot.child("fB_Latest").getValue(String.class);
// Facebook Banner Ads
adView = new AdView(getActivity(), fB_Latest, AdSize.BANNER_HEIGHT_50);
LinearLayout adContainer = (LinearLayout) myView.findViewById(R.id.latest_facebook_ads);
adContainer.addView(adView);
adView.loadAd();
// end
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
dataAdapter
/**
* Created by Vinay Singh on 16/02/2019.
*/
public class dataAdapter extends RecyclerView.Adapter<DataViewHolders>
implements Filterable {
private List<dataItem> myList;
private List<dataItem> myListFull;
private Context context;
public dataAdapter(List<dataItem> myList, Context context) {
this.myList = myList;
this.context = context;
myListFull = new ArrayList<>(myList);
}
#Override
public DataViewHolders onCreateViewHolder(ViewGroup viewGroup, int position) {
View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
DataViewHolders rcv = new DataViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(DataViewHolders holder, int position) {
String lines = myList.get(position).getLines();
holder.mLines.setText(myList.get(position).getLines());
holder.mVisit_id.setText(myList.get(position).getVisite_id());
if (myList.get(position).getPic().equals("default")) {
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}else if (myList.get(position).getPic().equals("Funny"))
{
Picasso.get().load(R.drawable.funny).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Romantic"))
{
Picasso.get().load(R.drawable.romantic).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chat Tips"))
{
Picasso.get().load(R.drawable.chat).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Morning"))
{
Picasso.get().load(R.drawable.goodmorning).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Motivation"))
{
Picasso.get().load(R.drawable.motivation).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Shayri"))
{
Picasso.get().load(R.drawable.shayari).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("WhatsApp"))
{
Picasso.get().load(R.drawable.whatsapp).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Jokes"))
{
Picasso.get().load(R.drawable.jokes).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Night"))
{
Picasso.get().load(R.drawable.goodnight).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chatting"))
{
Picasso.get().load(R.drawable.chatting).into(holder.mImage);
}
else
{
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}
}
#Override
public int getItemCount() {
return this.myList.size();
}
#Override
public Filter getFilter() {
return myListFilter;
}
private Filter myListFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty())
{
myListFull = myList;
}
else
{
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myListFull)
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
}
FilterResults results = new FilterResults();
results.values = myListFull;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myList.clear();
myList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
First Remove this code in your fragment
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
and intialized ArrayList in above of onCreateView method and change this code in onCreateView method
mDataAdapter = new dataAdapter(getResult, getContext());
Now add this code in your Adapter
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
In your myListFull ArrayList to not add data of myList.
I hope this can help You!
Thank You.

how to filter RecyclerView with searchview correctly?

hi all I have implemented SearchView inside RecyclerView but when I search character name it is not searching any name and I have followed this tutorial
below my adapter class where I have implemented recyclerview with
Filtarable
public class LeovegasAdapter extends RecyclerView.Adapter implements Filterable {
private List<Hero> heros;
private List<Hero> filtarableList;
public LeovegasAdapter(List<Hero> heros) {
this.heros = heros;
filtarableList = filtarableList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.hero_list, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Hero hero = heros.get(position);
holder.heroId.setText(hero.getId());
holder.heroName.setText(hero.getName());
}
#Override
public int getItemCount() {
return heros.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filtarableList = heros;
} else {
ArrayList<Hero> filteredList = new ArrayList<>();
for (Hero hero : heros) {
if (hero.getId().toLowerCase().contains(charString) || hero.getName().toLowerCase().contains(charString)) {
filteredList.add(hero);
}
}
filtarableList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filtarableList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filtarableList = (List<Hero>) results.values;
notifyDataSetChanged();
}
};
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView heroId, heroName;
public CustomViewHolder(View view) {
super(view);
heroId = (TextView) view.findViewById(R.id.heroId);
heroName = (TextView) view.findViewById(R.id.heroName);
}
}
}
below my MainActivity.java
public class MainActivity extends AppCompatActivity {
public LeovegasAdapter leovegasAdapter;
public static final String publicKey = "4089ee37331d8211b080b047c58f6970";
public static final String privateKey = "18ccbcb58fdd12c22821f8b633a06f2b433d16c3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LeoVegasInterface leoVegasInterface = LeoVegasClient.getApiService();
String ts = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
String hash = Hasher.md5(ts + privateKey + publicKey);
Call<LeoVegas> callHeroes = leoVegasInterface.getHeroes(ts, publicKey, hash);
callHeroes.enqueue(new Callback<LeoVegas>() {
#Override
public void onResponse(Call<LeoVegas> call, Response<LeoVegas> response) {
LeoVegas leoVegas = response.body();
Data data = leoVegas.getData();
Hero[] heroes = data.getResults();
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
leovegasAdapter = new LeovegasAdapter(Arrays.asList(heroes));
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setAdapter(leovegasAdapter);
}
#Override
public void onFailure(Call<LeoVegas> call, Throwable t) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
leovegasAdapter.getFilter().filter(newText);
return true;
}
});
}
}
Change your below code
Few changes
Clear the list
Use addAll to fill with the result
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
//Updated code
String charString = charSequence.toString();
ArrayList<Hero> filteredList = new ArrayList<>();
if (charString.isEmpty()) {
filteredList.addAll(filtarableList);
} else {
ArrayList<Hero> filteredList = new ArrayList<>();
for (Hero hero : heros) {
if (hero.getId().toLowerCase().contains(charString) || hero.getName().toLowerCase().contains(charString)) {
filteredList.add(hero);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//Update code
heros.clear();
if (results == null)
heros.addAll(mFilterConversations);
else {
heros.addAll((List<Hero>) results.values);
}
notifyDataSetChanged();
}
};
}

Wrong position after filter

I have a problem with my application. Actually, I'm totally stuck. I have a list of countries with implemented clicklistener and searchview. In a situation when I click on a given element without searching the list, everything displays correctly and shows information about a given country. But when I search the list and click on the element, the application goes to the information about the random country. I dont know why this is happening. I have no error. Only a warning:
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
MainActivity
public static final String EXTRA_COUNTRY_NAME = "country_name";
public static final String EXTRA_COUNTRY_REGION = "country_region";
public static final String EXTRA_COUNTRY_NATIVE_NAME = "country_nativename";
public static final String EXTRA_COUNTRY_NAME_LANGUGES= "country_namelanguages";
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<ModelJsona> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://restcountries.eu/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<ModelJsona>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<ModelJsona>>() {
#Override
public void onResponse(Call<List<ModelJsona>> call, Response<List<ModelJsona>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
dataAdapter.setOnitemClickListener(MainActivity.this);
}
#Override
public void onFailure(Call<List<ModelJsona>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
dataAdapter.getFilter().filter(newText);
if (dataAdapter !=null)dataAdapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public void onItemClick(int position) {
Intent detailsIntent = new Intent(this,Details.class);
ModelJsona click = dataArrayList.get(position);
detailsIntent.putExtra(EXTRA_COUNTRY_NAME,click.getName());
detailsIntent.putExtra(EXTRA_COUNTRY_REGION,click.getRegion());
detailsIntent.putExtra(EXTRA_COUNTRY_NATIVE_NAME,click.getNativeName());
detailsIntent.putExtra(EXTRA_COUNTRY_NAME_LANGUGES,click.getLanguages().get(0).getName());
startActivity(detailsIntent);
}
}
DataAdapter
private Context context;
private List<ModelJsona> dataList;
private List<ModelJsona> filtr;
private OnitemClickListener mListener;
public interface OnitemClickListener {
void onItemClick (int position);
}
public void setOnitemClickListener (OnitemClickListener listener)
{
mListener=listener;
}
public DataAdapter(Context context, List<ModelJsona> dataList) {
this.context = context;
this.dataList = dataList;
this.filtr= dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.country_name.setText(filtr.get(position).getName());
holder.country_region.setText(filtr.get(position).getRegion());
holder.country_nativename.setText(filtr.get(position).getNativeName());
holder.country_languagename.setText(filtr.get(position).getLanguages().get(0).getName());
}
#Override
public int getItemCount() {
return filtr.size();
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filtr = dataList;
} else {
ArrayList<ModelJsona> listadoprzeszukiwan = new ArrayList<>();
for (ModelJsona wyszukiwarka : dataList) {
if (
wyszukiwarka.getName().contains(charString) ||
wyszukiwarka.getName().toLowerCase().contains(charString) ||
wyszukiwarka.getRegion().contains(charString) ||
wyszukiwarka.getRegion().toLowerCase().contains(charString) ||
wyszukiwarka.getNativeName().contains(charString) ||
wyszukiwarka.getNativeName().toLowerCase().contains(charString) ||
wyszukiwarka.getTopLevelDomain().contains(charString))
{
listadoprzeszukiwan.add(wyszukiwarka);
}
}
filtr = listadoprzeszukiwan;
}
FilterResults wynikiszukania = new FilterResults();
wynikiszukania.values = filtr;
return wynikiszukania;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults wynikiszukania) {
filtr = (ArrayList<ModelJsona>) wynikiszukania.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView country_name, country_region, country_languagename,country_nativename;
public MyViewHolder(View itemView) {
super(itemView);
country_name = (TextView) itemView.findViewById(R.id.country_name);
country_region = (TextView) itemView.findViewById(R.id.country_region);
country_nativename = (TextView) itemView.findViewById(R.id.country_nativename);
country_languagename= (TextView) itemView.findViewById(R.id.country_languagename);
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));
}
}
}
i see that you get the position in filter list refer to different object with same position value in dataList because after filtering filter list become reference to result but still dataList hold all data.
you can replace itemView click listner by this:
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
String name = filtr.get(position).getName();
for (int i=0 ; i <dataList.size() ; i++ ){
if(name.equals(dataList.get(i).getName()){
position = i;
break;
}
}
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));

Categories

Resources