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.
Related
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.
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
}
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;
}
I have implemented searchview filter for recyclerview in fragment like below but when I am entering the query in searchview nothing happens .
My Fragment class: DiscussionForum.java
public class DiscussionForum extends Fragment implements ForumAdapter.ForumAdapterListener {
private TextView socname;
private EditText messageinput;
private SearchView search;
// SearchView searchView;
private FloatingActionButton messagesend;
ProgressDialog progressDialog;
private static final String TAG = "Discussion Forum";
private RecyclerView recyclerView;
private List<ForumData> forumlist;
private ForumAdapter mAdapter;
private OnFragmentInteractionListener mListener;
private LinearLayout list;
private String sendurl, geturl;
public DiscussionForum() {
// Required empty public constructor
}
public static DiscussionForum newInstance(String param1, String param2) {
DiscussionForum fragment = new DiscussionForum();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
onButtonPressed("Discussion Forum");
forumlist = new ArrayList<>();
recyclerView = view.findViewById(R.id.listviewforum);
list = view.findViewById(R.id.list);
search = view.findViewById(R.id.search);
int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getContext(), resId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutAnimation(animation);
mAdapter = new ForumAdapter(getContext(), forumlist, this);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
geturl = "";
fetchforumdata(getActivity().getIntent().getStringExtra("id"));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
return view;
}
private void fetchforumdata(final String id1) {
progressDialog.setMessage("Loading...");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET,
geturl + id1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("tag2","id"+id1);
Log.d(TAG, "Response Prop: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("errors");
if (!error) {
JSONObject dataobj = jObj.getJSONObject("data");
JSONArray ticketarray = dataobj.getJSONArray("result");
if (ticketarray.length() == 0) {
list.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
List<ForumData> items = new Gson().fromJson(ticketarray.toString(), new TypeToken<List<ForumData>>() {
}.getType());
forumlist.clear();
forumlist.addAll(items);
recyclerView.setAdapter(mAdapter);
}
} else {
// String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
"Try again or report an issue", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
});
MyApplication.getInstance().addToRequestQueue(request);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String title) {
if (mListener != null) {
mListener.onFragmentInteraction(title);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public void onDocumentSelected(String id) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String title);
}}
My Adapter Class :ForumAdapter
public class ForumAdapter extends RecyclerView.Adapter<ForumAdapter.MyViewHolder> implements Filterable {
private Context context;
private List<ForumData> ticketlist;
private List<ForumData> filterlist;
private ForumAdapterListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView username,createdat,forummessage,flatno,category,likes,subcount;
ImageView edit;
public MyViewHolder(View view) {
super(view);
username=view.findViewById(R.id.user_name2);
createdat=view.findViewById(R.id.date2);
edit = view.findViewById(R.id.profile_icon2);
forummessage=view.findViewById(R.id.forum_message);
flatno=view.findViewById(R.id.flat_no);
category=view.findViewById(R.id.category);
likes=view.findViewById(R.id.likes_data);
subcount=view.findViewById(R.id.count_data);
}
}
public ForumAdapter(Context context, List<ForumData> ticketlist, ForumAdapterListener listener) {
this.context = context;
this.listener = listener;
this.ticketlist = ticketlist;
this.filterlist=ticketlist;
}
#Override
public ForumAdapter.MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.discussion_forum_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder( ForumAdapter.MyViewHolder holder, int position) {
final ForumData contact = ticketlist.get(position);
holder.username.setText(contact.getUsername());
holder.flatno.setText(contact.getFlattitle());
holder.forummessage.setText(contact.getMessage());
holder.createdat.setText(contact.getCreated_at());
holder.category.setText(contact.getCategory());
holder.likes.setText(contact.getLikes());
holder.subcount.setText(contact.getSubcount());
Glide.with(context)
.load(url+".jpg")
.apply(new RequestOptions().circleCrop().placeholder(R.drawable.man).error(R.drawable.man))
.into(holder.edit);
}
});
}
#Override
public int getItemCount() {
return ticketlist.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filterlist = ticketlist;
} else {
List<ForumData> filteredList = new ArrayList<>();
for (ForumData row : ticketlist) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getUsername().toLowerCase().contains(charString.toLowerCase()) || row.getCategory().contains(charSequence)) {
filteredList.add(row);
}
}
filterlist = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterlist;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterlist = (ArrayList<ForumData>) results.values;
notifyDataSetChanged();
}
}
;
}
public interface ForumAdapterListener {
void onDocumentSelected(String contact);
}}
I have gone through many solutions like here , here ,here
But I am unable to figure out what is wrong with my code . Please help me figure out where the exact problem is.
There are multiple issues with your Adapter implementation. If I understand your code correctly you want to keep a reference to a list of unfiltered items (List<ForumData> ticketlist) and filter this list and display the filtered results (List<ForumData> filterlist) on the screen.
Firstly, you want to display filterlist on the screen so in onBindViewHolder() and getItemCount() you need to use filterlist instead of ticketlist.
Secondly, you want to ensure that ticketlist stays unchanged so that all future searches are on the same content. To do this you will have to replace all filterlist = ticketlist; with filterlist = new ArrayList<>(ticketlist); (in your contstructor and in performFiltering()) to avoid changing the contents of ticketlist.
This should make your code functional at least. I suggest you watch this video on Java and objects and references as well.
Another way to go is to filter the data and and refresh the recyclerview's adapter in the onQueryTextChange :
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList< ForumData > filteredData = new ArrayList<>();
for (ForumData forumData : data) {
if (forumData..getUsername().toLowerCase().contains(newText.toLowerCase())) {
filteredData.add(forumData);
}
}
adapter = new ForumAdapter(data, getContext() , this);
recyclerView.setAdapter(adapter);
return true ;
}
})
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);
}
}
}
}));