I have spent about two days on it but cant find the error. everything else is working but when i search something it does not show anything.
this is my adapter class for volley
public class GethubAdapter extends RecyclerView.Adapter<GethubAdapter.GethubViewHolder> implements Filterable {
private List<User> userListFull;
private List<User> userList;
private Context context;
public GethubAdapter(Context context, List<User> userList) {
this.context = context;
this.userList = userList;
userListFull= new ArrayList<>(userList);
}
#NonNull
#Override
public GethubViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_user_layout2, parent, false);
return new GethubViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull GethubViewHolder holder, int position) {
User user = userList.get(position);
holder.label.setText(user.getAvatarUrl());
holder.value.setText(String.valueOf(user.getId()));
holder.unit.setText(user.getFollowersUrl());
//Glide.with(holder.imageView.getContext()).load(user.getAvatarUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return userList.size();
}
public class GethubViewHolder extends RecyclerView.ViewHolder {
TextView label, value, unit;
public GethubViewHolder(#NonNull View itemView) {
super(itemView);
label = itemView.findViewById(R.id.label);
value = itemView.findViewById(R.id.value);
unit = itemView.findViewById(R.id.unit);
}
}
#Override
public Filter getFilter() {
return userFilter;
}
private Filter userFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(userListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (User item : userListFull) {
if (item.getId().toString().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
userList.clear();
userListFull.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
this is my main activity class where i am using gson to convert jason objects into java objects
public class MainActivity extends AppCompatActivity {
//private static final String URL = "http://192.168.18.18:1880/mac/user/data.json";
private static final String URL = "https://api.github.com/users";
List<User> light;
GethubAdapter adapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.userList);
light = new ArrayList<>();
adapter = new GethubAdapter(this, light);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("code", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
//light = (List<User>) gson.fromJson(response,User.class);
List<User> items = new Gson().fromJson(response, new TypeToken<List<User>>() {
}.getType());
Type listType = new TypeToken<ArrayList<User>>() {
}.getType();
List<User> light = new Gson().fromJson(response, listType);
adapter = new GethubAdapter(MainActivity.this, light);
recyclerView.setAdapter(adapter);
//Toast.makeText(MainActivity.this,user[0].getBody(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
i am using volley library for getting data from api
Here :
protected void publishResults(CharSequence constraint, FilterResults results) {
userList.clear();
userListFull.addAll((List) results.values);
notifyDataSetChanged();
}
You have not updated userlist . Update there , it will work like :
protected void publishResults(CharSequence constraint, FilterResults results) {
userList.clear();
userList.addAll((List) results.values);
notifyDataSetChanged();
}
Related
Basically I am trying trying to implement checkboxes in recyclerview, but when I try to filter it, it unchecks the boxes. This is my adapter. I tried different adapters, but nothing seems to work.
IngAdapter.java
public class IngAdapter extends RecyclerView.Adapter<IngAdapter.ViewHolder> implements Filterable {
View view;
Context context;
ArrayList<String> getArrayList;
ArrayList<String> ingList;
IngListener ingListener;
ArrayList<String> arrayList_0 = new ArrayList<>();
public IngAdapter(Context context, ArrayList<String> arrayList, IngListener ingListener) {
this.context = context;
this.getArrayList = arrayList;
this.ingListener = ingListener;
this.ingList = new ArrayList<>(arrayList);
}
public View getView() {
return view;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(context).inflate(R.layout.rv_layout,parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
if (getArrayList != null && getArrayList.size() > 0) {
holder.check_box.setText((CharSequence) getArrayList.get(position));
holder.check_box.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.check_box.isChecked()) {
arrayList_0.add(getArrayList.get(position));
} else {
arrayList_0.remove(getArrayList.get(position));
}
ingListener.onIngChange(arrayList_0);
}
});
}
}
#Override
public int getItemCount() {
return getArrayList.size();
}
Here is my filter function.
#Override
public Filter getFilter() {
return filter;
}
final Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if (charSequence.toString().isEmpty()) {
filterResults.values = ingList;
filterResults.count = ingList.size();
} else {
String searchIng = charSequence.toString().toLowerCase();
List<String> filtered = new ArrayList<>();
for (String ingredient : ingList) {
if (ingredient.toLowerCase().contains(charSequence.toString().toLowerCase())) {
filtered.add(ingredient);
}
}
filterResults.values = filtered;
filterResults.count = filtered.size();
}
return filterResults;
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
getArrayList.clear();
getArrayList.addAll((Collection<? extends String>) filterResults.values);
ingListener.onIngChange(arrayList_0);
notifyDataSetChanged();
}
};
[]
[]
I cannot find a solution to the same problem. Goal: Keep checkboxes selected after search
I'm looking to implement a searchview next to recyclerview to make filtering of book records occur. I'm having trouble on the following line in the ListBooks.java file:
Line:
recyclerAdapter = new BookAdapter();
The error of this line is:
error: constructor BookAdapter in class BookAdapter cannot be applied to given types; required: List<Book>,Context found: no arguments
reason: actual and formal argument lists differ in length.
ListBooks.java
public class ListBooks extends AppCompatActivity {
RecyclerView recyclerView;
BookAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listar_livros);
recyclerView = findViewById(R.id.recyclerView);
recyclerAdapter = new BookAdapter();
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
DB db = new DB(this);
List<Book> books = db.ReadBooks();
if (books.size() > 0){
BookAdapter bookadapter = new BookAdapter(books,ListBooks.this);
recyclerView.setAdapter(bookadapter);
} else {
Toast.makeText(this, "No books in database.", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.search_book,menu);
MenuItem menuItem = menu.findItem(R.id.s_book);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
BookAdapter.java
public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> implements Filterable {
List<Book> books;
List<Book> books2;
Context context;
DB db;
public BookAdapter(List<Book> books, Context context) {
this.books = books;
this.books2 = new ArrayList<>(books2);
this.context = context;
bd = new BD(context);
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<Book> filter_books = new ArrayList<>();
if (charSequence.toString().isEmpty()){
filter_books.addAll(books2);
} else {
for (Book book: books2){
if (book.getTitle_book().toLowerCase().contains(charSequence.toString().toLowerCase())){
filter_book.add(book);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filter_books;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
books.clear();
books.addAll((Collection<? extends Book>) filterResults.values);
notifyDataSetChanged();
}
};
}
A search view is implemented in action bar, the search works fine, but for example,
If user search for two characters pa, my list contains 2 data related to the related to pa i.e., pack1,pack2 then data loads in the recycler view. now if user enter another character l, to the previous characters pa, now my search view has pal , but array list doesn't match with the search, the list doesn't contain any item with pal. i.e., now the recycler view is empty. now, if I clear the character l, the list gets reloaded with data pack1, pack2, but result loads 2 times i.e., instead of showing 2 items in recyclerview, it shows 4 items in total.
It is duplicating the items, when the search is cleared.
searchview
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_order, menu);
searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
mOrderAdapter.getFilter().filter(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length()==0){
getData();
searchView.clearFocus();
}
mOrderAdapter.getFilter().filter(newText);
return true ;
}
});
return true;
}
Filter code
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty()||charString.length()==0) {
mListFilter = mOrderArrayList;
} else {
List<Order> filteredList = new ArrayList<>();
ArrayList<Order> templist=new ArrayList<Order>();
for (Order ord : mOrderArrayList) {
if (ord.getOs_OrderNo().toLowerCase().contains(charString.toLowerCase())
|| ord.getItemName().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(ord);
templist.addAll(mListFilter);
}
}
mOrderArrayList.removeAll(templist);
mOrderArrayList.addAll(filteredList);
mListFilter = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mListFilter;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mListFilter = (ArrayList<Order>) results.values;
notifyDataSetChanged();
}
};
}
Any help is really appreciated.
Adapter code
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.MyViewHolder> implements Filterable {
private Context mContext;
private List<Order> mListFilter,mOrderArrayList;
private SharedPreferences sharedPreferences;
private Resources r;
public OrderAdapter(Context context, ArrayList<Order> orderList) {
mContext = context;
mListFilter = orderList;
mOrderArrayList = orderList;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
r = context.getResources();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView orderNoView, itemNameView, qtyView, statusView, companyNameView;
private Order currentItem;
MyViewHolder(View view) {
super(view);
orderNoView = view.findViewById(R.id.orderNo);
itemNameView = view.findViewById(R.id.item);
qtyView = view.findViewById(R.id.qty);
statusView = view.findViewById(R.id.status);
companyNameView = view.findViewById(R.id.company);
}
void bind (Order om) { //<--bind method allows the ViewHolder to bind to the data it is displaying
orderNoView.setText(om.getOs_OrderNo());
itemNameView.setText(String.valueOf(om.getItemName()));
qtyView.setText("Qty - " + String.valueOf(om.getOs_Qty()));
statusView.setText(om.getStatusName());
if (sharedPreferences.getString(r.getString(R.string.key_CompanyInUser), "").equals("0")){
companyNameView.setVisibility(View.GONE);
} else {
companyNameView.setText(om.getCustomerName());
}
currentItem = om; //<-- keep a reference to the current item
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_order, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Order item = mListFilter.get(position);
holder.bind(item);
}
#Override
public int getItemCount() {
return mListFilter.size();
}
#Override
public int getItemViewType(int position){
return position;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
List<Order> filteredList = new ArrayList<>();
if (charString.isEmpty()||charString.length()==0) {
filteredList.addAll(mOrderArrayList);
} else {
for (Order ord : mOrderArrayList) {
if (ord.getOs_OrderNo().toLowerCase().contains(charString.toLowerCase())
|| ord.getItemName().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(ord);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mListFilter = (ArrayList<Order>) results.values;
notifyDataSetChanged();
}
};
}
}
Clicklistener code
brandView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), brandView,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
isRefreshData = true;
startActivity(new Intent(mContext, ViewOrderDetails.class).putExtra("Key-Intent-OrderNo",mOrderArrayList.get(position).getOs_OrderNo()).putExtra("Key-Intent-BrandName",mOrderArrayList.get(position).getos_BrandName()));
}
#Override
public void onLongClick(View view, int position) {
}
}));
Its because you are using addAll inside a loop in #performFiltering . Also why you have two local list for filtering? Check the method below it should work . i have removed the extra code and code which is causing the issue .
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
List<Order> filteredList = new ArrayList<>();
if (charString.isEmpty()||charString.length()==0) {
filteredList.addAll(mOrderArrayList);
} else {
for (Order ord : mOrderArrayList) {
if (ord.getOs_OrderNo().toLowerCase().contains(charString.toLowerCase())
|| ord.getItemName().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(ord);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mListFilter = (ArrayList<Order>) results.values;
notifyDataSetChanged();
}
};
}
Am trying to implement Filterable in my recyclerview which contains <Object> here is the code
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Object> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(mRecyclerViewItemsAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Object item : mRecyclerViewItemsAll) {
if (item.getVideo_name().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mRecyclerViewItems.clear();
mRecyclerViewItems.addAll((List) results.values);
notifyDataSetChanged();
}
};
When i try above code i get cannot resolve method getVideo_name() in Object
So how do i implement Filterable. I have used same code with <String> and it worked.
Recycler view adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
private final Context mContext;
private final ArrayList<Object> mRecyclerViewItems;
ArrayList<Object> mRecyclerViewItemsAll;
public RecyclerViewAdapter(Context context, ArrayList<Object> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
this.mRecyclerViewItemsAll = new ArrayList<>(recyclerViewItems);
}
#Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Object> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(mRecyclerViewItemsAll);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Object item : mRecyclerViewItemsAll) {
if (item.getVideo_name().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mRecyclerViewItems.clear();
mRecyclerViewItems.addAll((List) results.values);
notifyDataSetChanged();
}
};
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder{
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = mRecyclerViewItems.get(position);
if (recyclerViewItem instanceof UnifiedNativeAd) {
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}
return MENU_ITEM_VIEW_TYPE;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
}
private void populateNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {
}
And here is MainActivity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actionbar_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recyclerViewAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
Can someone help me what wrong am doing and how to correct it.
cannot resolve method getVideo_name() in Object
Your list is type of Object which is super class in Java and does not contain method called getVideo_name()
Object class has predefined method namely:
toString()
hashCode()
clone()
equals(Object obj)
getClass()
finalize()
wait()
notify()
notifyAll()
What you can do is to create your class that is by default subtype of Object class and define class behavious(methods)
For example:
class MyData {
private String name;
public String getVideoName() {
return this.name;
}
public void setVideoName(String name) {
this.name = name;
}
}
And then use it like :
private final ArrayList<MyData> mRecyclerViewItems;
So I have a little problem where I have a giant recycler view (7000 items) and I have it filled up with generated cards that have college information on them and a button on the right hand side. I included a picture for you to see exactly what I mean. So here is the question: I want to fetch the name and ID when I click on the "details" button so that I can query the rest of college information from an SQLite database later but when I scroll down enough and click the button it sometimes returns information of other college instead of the one I want. The first one always works as intended though. Here is the adapter code:
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.CustomViewHolder> implements Filterable {
private List<CollegeItem> collegeList;
private List<CollegeItem> collegeListFull;
private ItemClickListener itemClickListener;
private Context context;
private Button details;
private DatabaseCollege collegeDB;
public CustomRecyclerAdapter(List<CollegeItem> collegeList, Context context) {
this.collegeList = collegeList;
this.context = context;
collegeListFull = new ArrayList<>(collegeList);
}
#NonNull
#Override
public CustomRecyclerAdapter.CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.college_item, parent, false);
return new CustomRecyclerAdapter.CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomRecyclerAdapter.CustomViewHolder holder, int position) {
final String id = collegeList.get(position).getId();
final String name = collegeList.get(position).getName();
holder.name.setText(collegeList.get(position).getName());
holder.id.setText(collegeList.get(position).getId());
details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(id + " - " + name); //This sometimes gives information of incorrect college when clicked
}
});
}
#Override
public int getItemCount() {
return collegeList.size();
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public Filter getFilter() {
return collegeFilter;
}
public Filter getFilterName() {
return collegeFilterName;
}
private Filter collegeFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CollegeItem> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(collegeListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(CollegeItem college : collegeListFull) {
if(college.getName().toLowerCase().contains(filterPattern)) {
filteredList.add(college);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
collegeList.clear();
collegeList.addAll((List) results.values);
notifyDataSetChanged();
}
};
private Filter collegeFilterName = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CollegeItem> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(collegeListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(CollegeItem college : collegeListFull) {
if(college.getId().toLowerCase().contains(filterPattern)) {
filteredList.add(college);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
collegeList.clear();
collegeList.addAll((List) results.values);
notifyDataSetChanged();
}
};
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name, id;
public CustomViewHolder(View v) {
super(v);
name = v.findViewById(R.id.college_name);
id = v.findViewById(R.id.college_id);
details = v.findViewById(R.id.btn_college_details);
}
#Override
public void onClick(View v) {
if(itemClickListener != null) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
}
I am not sure exactly why but it seems to be a positioning issue maybe? Because when I scroll and click the information outputed seem to change. Whats the correct way to get the information from the cards the way I want?
and just in case here is the fragment java code where the recycler view sits:
public class CollegeFragment extends Fragment implements ItemClickListener{
private RecyclerView recyclerView;
private CustomRecyclerAdapter customRecyclerAdapter;
private List<CollegeItem> collegeItemList = new ArrayList<>();
private DatabaseCollege dbCollege;
private EditText cName, cId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View myFragmentView = inflater.inflate(R.layout.fragment_college, container, false);
dbCollege = new DatabaseCollege(getActivity());
recyclerView = myFragmentView.findViewById(R.id.recycler);
customRecyclerAdapter = new CustomRecyclerAdapter(dbCollege.getCollegeData(), getActivity());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(customRecyclerAdapter);
customRecyclerAdapter.setItemClickListener(this);
cId = myFragmentView.findViewById(R.id.et_ipeds);
cId.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cName.getText().clear();
CollegeFragment.this.customRecyclerAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
cName = myFragmentView.findViewById(R.id.et_name);
cName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cId.getText().clear();
CollegeFragment.this.customRecyclerAdapter.getFilterName().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
return myFragmentView;
}
#Override
public void onClick(View v, int position) {
String name = collegeItemList.get(position).getName();
String id = collegeItemList.get(position).getId();
}
}
Adapter
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.CustomViewHolder> implements Filterable {
private List<CollegeItem> collegeList;
private List<CollegeItem> collegeListFull;
private ItemClickListener itemClickListener;
private Context context;
private DatabaseCollege collegeDB;
public CustomRecyclerAdapter(List<CollegeItem> collegeList, Context context) {
this.collegeList = collegeList;
this.context = context;
collegeListFull = new ArrayList<>(collegeList);
}
#NonNull
#Override
public CustomRecyclerAdapter.CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.college_item, parent, false);
return new CustomRecyclerAdapter.CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomRecyclerAdapter.CustomViewHolder holder, int position) {
final String id = collegeList.get(position).getId();
final String name = collegeList.get(position).getName();
holder.name.setText(collegeList.get(position).getName());
holder.id.setText(collegeList.get(position).getId());
}
#Override
public int getItemCount() {
return collegeList.size();
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public Filter getFilter() {
return collegeFilter;
}
public Filter getFilterName() {
return collegeFilterName;
}
private Filter collegeFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CollegeItem> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(collegeListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(CollegeItem college : collegeListFull) {
if(college.getName().toLowerCase().contains(filterPattern)) {
filteredList.add(college);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
collegeList.clear();
collegeList.addAll((List) results.values);
notifyDataSetChanged();
}
};
private Filter collegeFilterName = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CollegeItem> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(collegeListFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(CollegeItem college : collegeListFull) {
if(college.getId().toLowerCase().contains(filterPattern)) {
filteredList.add(college);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
collegeList.clear();
collegeList.addAll((List) results.values);
notifyDataSetChanged();
}
};
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name, id;
Button details; // Button should be here
public CustomViewHolder(View v) {
super(v);
name = v.findViewById(R.id.college_name);
id = v.findViewById(R.id.college_id);
details = v.findViewById(R.id.btn_college_details);
details.setOnClickListener(this); // set click listener here instead
}
#Override
public void onClick(View v) {
if(itemClickListener != null) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
}
Here, you're utilizing the ItemClickListener callback that you implemented in your fragment instead of creating new instances of click listener for your details button. In this case, your listener for all items is your Fragment that implements ItemClickListener