Search View with RecyclerView on click show old data - android

I am doing Search view with RecyclerView every thing work fine like data show in RecyclerView on search data also filter and showing result but when i touch data it give old position means filter position not showing on toast, if we search typing z in search view it show all data start with z but when i click data start with z it show me on toast data which is old means data start with a
I am getting same problem with list there i found solution with ListView Object
list.getItemAtPosition this solve problem the same problem in RecyclerView
here is interface
public interface RecyclerViewClickListener {
public void recyclerViewListClicked(View v, int position);}
this code getting problem
recycleitemclicklistener = new RecyclerViewClickListener() {
#Override
public void recyclerViewListClicked(View v, int position) {
if (positionvalue.equals("CommonCustomer")) {
CommonSetterANDGetter getclick= commonSetterANDGetters.get(position);
Toast.makeText(maincontext, "denm"+ getclick.getValueNameCustomer()+getclick.getIdCustomer(), Toast.LENGTH_SHORT).show();
}
}
};
this is Adaptor
public class SearchAdapter extends
RecyclerView.Adapter<SearchAdapter.ViewHolder> implements Filterable {
private ArrayList<CommonSetterANDGetter> mArrayList;
private ArrayList<CommonSetterANDGetter> mFilteredList;
private String positionvalue = null;
RecyclerViewClickListener itemclicklistener;
Context maincontext;
public SearchAdapter(Context maincontext, ArrayList<CommonSetterANDGetter> arrayList, String positionvalue, RecyclerViewClickListener recycleitemclicklistener) {
this.maincontext = maincontext;
this.mArrayList = arrayList;
this.mFilteredList = arrayList;
this.itemclicklistener = recycleitemclicklistener;
this.positionvalue=positionvalue;
}
#Override
public SearchAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = null;
if(positionvalue.equals( "StockSummary_List")) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.stocksummary_petty, viewGroup, false);
}else if(positionvalue.equals( "CommonCustomer")){
view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.customersearch_petty,viewGroup,false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(SearchAdapter.ViewHolder viewHolder, int i) {
if(positionvalue.equals( "StockSummary_List")) {
viewHolder.itemCodeStock.setText(mFilteredList.get(i).getItemCodeStock());
viewHolder.itemNameStock.setText(mFilteredList.get(i).getItemNameStock());
viewHolder.issuedStock.setText("Iss :" + mFilteredList.get(i).getIssuedStock() + mFilteredList.get(i).getUmoStock());
viewHolder.recievedStock.setText("Rec :" + mFilteredList.get(i).getRecievedStock() + mFilteredList.get(i).getUmoStock());
viewHolder.closingStock.setText("Clo :" + mFilteredList.get(i).getClosingStock() + mFilteredList.get(i).getUmoStock());
// viewHolder.umoStock.setText(mFilteredList.get(i).getUmoStock());
}else if(positionvalue.equals( "CommonCustomer")){
viewHolder.custName_commonCustdetail.setText(mFilteredList.get(i).getValueNameCustomer());
}
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<CommonSetterANDGetter> filteredList = new ArrayList<>();
for (CommonSetterANDGetter commonsetget : mArrayList) {
if (positionvalue.equals("StockSummary_List")) {
if (commonsetget.getItemCodeStock().toLowerCase().contains(charString) || commonsetget.getItemNameStock().toLowerCase().contains(charString)) {
filteredList.add(commonsetget);
}
}else if(positionvalue.equals( "CommonCustomer")){
if (commonsetget.getValueNameCustomer().toLowerCase().contains(charString)) {
filteredList.add(commonsetget);
}
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredList = (ArrayList<CommonSetterANDGetter>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView itemCodeStock, itemNameStock, issuedStock, recievedStock, closingStock, umoStock;// stock Sum
TextView custName_commonCustdetail;// common detail cust
public ViewHolder(View view) {
super(view);
if(positionvalue.equals( "StockSummary_List")) {
itemCodeStock = (TextView) view.findViewById(R.id.itemcode_stocksum);
itemNameStock = (TextView) view.findViewById(R.id.itemname_stocksum);
issuedStock = (TextView) view.findViewById(R.id.issue_stocksum);
recievedStock = (TextView) view.findViewById(R.id.recieve_stocksum);
closingStock = (TextView) view.findViewById(R.id.closing_stocksum);
}else if(positionvalue.equals( "CommonCustomer")){
custName_commonCustdetail= (TextView) view.findViewById(R.id.commonname_customerdetail);
custName_commonCustdetail.setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
itemclicklistener.recyclerViewListClicked(v, this.getAdapterPosition());
}
}
}

Related

When select two item at the same time in recycle view application crash,how can i solve this?

public class BrandsAdapter extends RecyclerView.Adapter<BrandsAdapter.ViewHolder> implements Filterable {
private final OnListFragmentInteractionListener mListener;
int itemLayout = R.layout.brand_item;
private List<Brand> mValues;
private List<Brand> contactListFiltered;
private LoadImage loadImage;
Context mcontext;
public BrandsAdapter(Context context, List<Brand> items, int i, OnListFragmentInteractionListener listener) {
mValues = items;
loadImage = LoadImage.getInstance(context);
contactListFiltered = items;
mListener = listener;
if (i == 1) {
itemLayout = R.layout.brand_item2;
}
mcontext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(itemLayout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = contactListFiltered.get(position);
holder.mNameView.setText(holder.mItem.getBrandname());
PicassoTrustAll.getInstance(mcontext).load(contactListFiltered.get(position).getBrandimage()).placeholder(R.drawable.progress_animation).into(holder.mLogoView);
holder.mView.setOnClickListener(v -> {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
}
});
}
#Override
public int getItemCount() {
return contactListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = mValues;
} else {
List<Brand> filteredList = new ArrayList<>();
for (Brand row : mValues) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getBrandname().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<Brand>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
final View mView;
final TextView mNameView;
final ImageView mLogoView;
final ProgressBar progressBar;
Brand mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mNameView = view.findViewById(R.id.brand_name);
mLogoView = view.findViewById(R.id.brand_img);
progressBar = view.findViewById(R.id.progress_bar);
}
#Override
public String toString() {
return super.toString() + " '" + mNameView.getText() + "'";
}
}
}
when i clicked two item at the same time the app calls the interface method two times mListener.onListFragmentInteraction(holder.mItem);
It does
findNavController(requireActivity(), R.id.nav_host_support).navigate(R.id.action_brandsFragment_to_devicesFragment, bundle);
StackTrace
Process: com.unicomg.proserve, PID: 25752
java.lang.IllegalArgumentException: navigation destination com.unicomg.proserve:id/action_brandsFragment_to_devicesFragment is unknown to this NavController
at androidx.navigation.NavController.navigate(NavController.java:789)
at androidx.navigation.NavController.navigate(NavController.java:730)
at androidx.navigation.NavController.navigate(NavController.java:716)
at com.unicomg.proserve.ui.main.fragments.brands.BrandsFragment.lambda$initBrands$4$BrandsFragment(BrandsFragment.java:75)
at com.unicomg.proserve.ui.main.fragments.brands.-$$Lambda$BrandsFragment$pny4rYwzqdcDuB9NcgZbiyK2Ick.onListFragmentInteraction(Unknown Source:2)
at com.unicomg.proserve.ui.main.fragments.brands.BrandsAdapter.lambda$onBindViewHolder$0$BrandsAdapter(BrandsAdapter.java:74)
at com.unicomg.proserve.ui.main.fragments.brands.-$$Lambda$BrandsAdapter$NWl2ZJhVqEGxSaOEOsJQCc9r7Po.onClick(Unknown Source:6)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
That's because on the first tap it switches to DevicesFragment, and the action doesn't exist in that graph when the second tap is handled.
You could add this check:
if (navController.currentDestination?.id != R.id.devicesFragment) {
navController.navigate(R.id.action_brandsFragment_to_devicesFragment)
}
or this one:
navController.currentDestination?.getAction(R.id.action_brandsFragment_to_devicesFragment)?.let {
navController.navigate(R.id.action_brandsFragment_to_devicesFragment)
}
and you can also make them extension functions if you want to

filter function on recyclerview not showing list

i need help for this filter or search with editText on fragment with recyclerView, when afterTextChanged running filter and toast show correct data, but in recyclerView not showing anything only blank list, i try create new add list but still nothing.
this is my fragment
public class HomeFragment extends Fragment {
private SQLiteHandler db;
private TextView welcome;
private TextView jmlInspection;
private RecyclerView mRecyclerView;
private ListAdapter mListadapter;
EditText searchHome;
private ArrayList<DataNote> arraylist = new ArrayList<DataNote>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
welcome = (TextView) view.findViewById(R.id.txtWelcome);
jmlInspection = (TextView) view.findViewById(R.id.txtJmlInspection);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
searchHome = (EditText) view.findViewById(R.id.searchHome);
welcome.setText("Welcome, "+name +"!");
jmlInspection.setText("Saat ini anda memiliki 7 Data.");
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
//ArrayList data = new ArrayList<DataNote>();
for (int i = 0; i < DataNoteImformation.id.length; i++)
{
DataNote wp = new DataNote(
DataNoteImformation.id[i],
DataNoteImformation.branchArray[i],
DataNoteImformation.assetcodeArray[i],
DataNoteImformation.customerArray[i],
DataNoteImformation.licenseplateArray[i]
);
arraylist.add(wp);
}
mListadapter = new ListAdapter(arraylist);
mRecyclerView.setAdapter(mListadapter);
searchHome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence query, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
String text = searchHome.getText().toString().toLowerCase(Locale.getDefault());
mListadapter.filter(text);
}
});
return view;
}
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>
{
private ArrayList<DataNote> dataList;
private List<DataNote> filterlist = null;
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
this.filterlist = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textViewBranch;
TextView textViewAsset;
TextView textViewCustomer;
TextView textViewLicense;
Button btnReceive;
public ViewHolder(View itemView)
{
super(itemView);
this.textViewBranch = (TextView) itemView.findViewById(R.id.branch);
this.textViewAsset = (TextView) itemView.findViewById(R.id.assetcode);
this.textViewCustomer = (TextView) itemView.findViewById(R.id.customername);
this.textViewLicense = (TextView) itemView.findViewById(R.id.licenseplate);
this.btnReceive = (Button) itemView.findViewById(R.id.receiveBtn);
}
}
#Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
holder.textViewBranch.setText(dataList.get(position).getBranch());
holder.textViewAsset.setText(dataList.get(position).getAssetcode());
holder.textViewCustomer.setText(dataList.get(position).getCustomer());
holder.textViewLicense.setText(dataList.get(position).getLisenceplate());
holder.btnReceive.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(),
AssetReceiveActivity.class);
intent.putExtra("name",dataList.get(position).getCustomer());
intent.putExtra("code",dataList.get(position).getAssetcode());
intent.putExtra("plat",dataList.get(position).getLisenceplate());
startActivity(intent);
}
});
}
#Override
public int getItemCount()
{
return dataList.size();
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
filterlist.clear();
if (charText.length() == 0) {
filterlist.addAll(dataList);
}
else
{
for (DataNote wp : dataList)
{
if (wp.getCustomer().toLowerCase().contains(charText.toLowerCase()))
{
//Toast.makeText(getActivity(), "data " + wp.getCustomer() , Toast.LENGTH_SHORT).show();
filterlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
no error on Logcat. i need help for this, sorry for bad english.
Look at this example
Adapter
public class ListAdapter extends RecyclerView.Adapter<ItemHolder> implements Filterable {
private Context iContext;
private List<DataNote > dataList = new ArrayList<>();
private List<DataNote > filterlist = new ArrayList<>();
public ListAdapter (List<DataNote > dataList, Context context) {
this.dataList = dataList;
this.filterlist = dataList;
iContext = context;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
dataList= (List<DataNote >) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<DataNote> filteredList = new ArrayList<>();
String searchText = constraint.toString().toLowerCase();
String[] split = searchText.split(",");
ArrayList<String> searchGenres = new ArrayList<>(split.length);
for (String aSplit : split) {
// remove spaces
String trim = aSplit.trim();
// skip empty entries
if (trim.length() > 0)
searchGenres.add(trim);
}
for (DataNote dataNames : filterlist) {
// filter by title
if (dataNames.getCustomer().toLowerCase().trim().contains(searchText)) {
filteredList.add(dataNames);
}
}
results.count = filteredList.size();
results.values = filteredList;
return results;
}
};
return filter;
}
}
In Fragment :
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mListadapter.getFilter().filter(s.toString());
}
1) In on bind, you are accessing object from dataList Object and your getItemCount() is also returning the size of dataList.
2) During filtering, you are performing filtering and storing the filtered data in filterlist and calling notifyDataSetChanged().
So here your dataList which has all the data, is shown always and not the filterlist which has the data which is filtered.
If you want to show the filtered data, you should use the filterlist with the recyclerview like,
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
this.filterlist = new ArrayList(dataList);
}
#Override
public int getItemCount()
{
return filterlist.size();
}
#Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
holder.textViewBranch.setText(filterlist.get(position).getBranch());
holder.textViewAsset.setText(filterlist.get(position).getAssetcode());
holder.textViewCustomer.setText(filterlist.get(position).getCustomer());
holder.textViewLicense.setText(filterlist.get(position).getLisenceplate());
holder.btnReceive.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(),
AssetReceiveActivity.class);
intent.putExtra("name",filterlist.get(position).getCustomer());
intent.putExtra("code",filterlist.get(position).getAssetcode());
intent.putExtra("plat",filterlist.get(position).getLisenceplate());
startActivity(intent);
}
});
}

How to get item position in viewholder when swipe with filtered text

I was able to get the value of the viewHolder.getAdapterPosition() but what Im after is when I search for items using Filter and tried to swipe the searched item it always gives me the position 0.
Example list:
0: Apple
1: Banana
2: Mango
3: Coconut
4: Peanut
I searched for peanut and it should be in the first item on the list but when I tried to swiped it always return 0 as apple.
Here is my code
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, final int direction) {
Log.e("ITEM ID", String.valueOf(viewHolder.viewHolder.getAdapterPosition());
adapters.notifyDataSetChanged();
}
Please see Adapter Class:
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.MyViewHolder>{
private Context context;
private List<ProductObject> productList;
private double total;
private List<ProductObject> filteredItems;
private ProductsInterface productsInterface;
public interface ProductsInterface {
void productsInt(ProductObject position);
}
public void setProductsInterface(ProductsInterface productsInterfaceListener){
productsInterface = productsInterfaceListener;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView img_url;
TextView prod_desc, prod_uom, prod_price, prod_quantity;
public MyViewHolder(View itemView, final ProductsInterface listener) {
super(itemView);
prod_desc = (TextView) itemView.findViewById(R.id.card_product_name);
prod_uom = (TextView) itemView.findViewById(R.id.card_uom);
prod_price = (TextView) itemView.findViewById(R.id.card_price);
img_url = (ImageView) itemView.findViewById(R.id.card_imageView);
prod_quantity = (TextView) itemView.findViewById(R.id.prod_quantity);
//listener.productsInt(filteredItems.get(getAdapterPosition()));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
//productsInterface.productsInt();
int position = getAdapterPosition();
Log.e("ADAPTER", String.valueOf(position));
if(position != RecyclerView.NO_POSITION){
listener.productsInt(filteredItems.get(getAdapterPosition()));
//ProductObject clickedItems = filteredItems.get(position);
}
}
}
});
}
}
public ProductsAdapter (Context context, List<ProductObject> listItems){
this.context = context;
this.productList = listItems;
this.filteredItems = listItems;
}
#Override
public ProductsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_card_view, parent, false);
return new MyViewHolder(view, productsInterface);
}
#Override
public void onBindViewHolder(ProductsAdapter.MyViewHolder holder, int position) {
final ProductObject objectModel = filteredItems.get(holder.getAdapterPosition());
holder.prod_desc.setText(objectModel.getProd_desc());
holder.prod_uom.setText(objectModel.getProd_stockCode());
holder.prod_price.setText(String.valueOf(objectModel.getProd_price()));
holder.prod_quantity.setText(String.valueOf(objectModel.getProd_quantity()));
//prod id add here
/* Glide.with(context)
.load(objectModel.getProd_image())
.into(holder.img_url);*/
Glide.with(context)
.load(R.drawable.logo)
.into(holder.img_url);
}
#Override
public int getItemCount() {
return filteredItems.size();
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty()) {
filteredItems = productList;
} else {
final ArrayList<ProductObject> mFilteredList = new ArrayList<>();
for (final ProductObject listFilter : productList) {
if (listFilter.getProd_desc().toLowerCase().contains(charString) ||
listFilter.getProd_stockCode().toLowerCase().contains(charString)
) {
mFilteredList.add(listFilter);
}
}
filteredItems = mFilteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredItems;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList<ProductObject>) results.values;
notifyDataSetChanged();
}
};
}
}
Modify publishResults method to below
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems.clear();
filteredItems.addAll((ArrayList<ProductObject>) results.values);
notifyDataSetChanged();
}

search resultlist not getting set to recyclerview

i m implementing search functionality with realmData i got printed searched string but the searched string not getting set to recyclerview.
realm serchfilter return complete result and print it but return mFilteredList not getting set to recyclerview
package "";
public class FollowAdapter extends RecyclerView.Adapter<FollowAdapter.Holder> implements Filterable {
private Context context;
ActionListener actionListener;
InviteListener inviteListener;
private String TAG = getClass().getName();
List<ContactClass> realmList;
private List<ContactClass> mFilteredList;
public FollowAdapter(Context context, List<ContactClass> realmList) {
this.context = context;
this.realmList = realmList;
mFilteredList = realmList;
}
public InviteListener getInviteListener() {
return inviteListener;
}
public void setInviteListener(InviteListener inviteListener) {
this.inviteListener = inviteListener;
}
public ActionListener getActionListener() {
return actionListener;
}
public void setActionListener(ActionListener actionListener) {
this.actionListener = actionListener;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new Holder(LayoutInflater.from(parent.getContext()).inflate(R.layout.follow_item, parent, false));
}
#Override
public void onBindViewHolder(final Holder holder, final int position) {
final ContactClass contactClass = realmList.get(position);
holder.contactName.setText(contactClass.getName());
Drawable drawable = ResourcesCompat.getDrawable(holder.itemView.getContext().getResources(), R.drawable.camera, null);
Glide.with(holder.itemView.getContext()).load(contactClass.getAvatar()).into(holder.contact_pic).onLoadFailed(drawable);
holder.contactNumber.setText(contactClass.getNumber());
}
}
#Override
public int getItemCount() {
return realmList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = realmList;
} else {
List<ContactClass> filteredList = new ArrayList<>();
Realm realm = Realm.getDefaultInstance();
RealmQuery<ContactClass> query = realm.where(ContactClass.class).contains("name", charString, Case.INSENSITIVE);
RealmResults<ContactClass> realmResults = query.findAll();
for (ContactClass c : realmResults) {
filteredList.add(c);
Log.e("filter", c.getName() + " " + c.getNumber() + " " + c.getId());
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if (mFilteredList != null) {
Log.e("sized", mFilteredList.size() + "");
}
mFilteredList = (List<ContactClass>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class Holder extends RecyclerView.ViewHolder {
ImageView contact_pic;
TextView contactName, contactNumber;
AppCompatButton follow;
public Holder(View itemView) {
super(itemView);
contact_pic = itemView.findViewById(R.id.contact_pic);
contactName = itemView.findViewById(R.id.contact_name);
contactNumber = itemView.findViewById(R.id.contact_number);
follow = itemView.findViewById(R.id.btn_follow);
contactName.setSelected(true);
contactNumber.setSelected(true);
}
}}
code to search query
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
followAdapter.getFilter().filter(newText);
return false;
}

Getting wrong item selected from filtered list using recyclerview

I have a RecyclerView & EditText. I can select the item from RecyclerView & gets correct item unless it is not filtered.
On entering in EditText, RecyclerView list gets filtered & when I select any item from the list it shows me actual list item instead of selected one.
Fragment Class :
public class RegionListFragment extends DialogFragment implements View.OnClickListener,
OnRecylerViewClickable {
private RecyclerView regionRecyclerView;
private ArrayList<RegionDetail> regionDetailArrayList = new ArrayList<>();
private GenericRegionListAdapter genericRegionListAdapter;
private Context context = this.getActivity();
private RecyclerView.LayoutManager mLayoutManager;
private View view;
private EditText editTextSearchView;
private DatabaseHandler spcl_databaseHandler;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.spinner_fragment_list_screen, container, false);
databaseHandler = new DatabaseHandler(getActivity());
regionDetailArrayList = (ArrayList<RegionDetail>) spcl_databaseHandler.getAllRegionDetails();
editTextSearchView = (EditText) view.findViewById( R.id.search);
editTextSearchView.setHint(getString(R.string.region_search_hint));
mLayoutManager = new LinearLayoutManager(context);
regionRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_Locations);
regionRecyclerView.setLayoutManager(mLayoutManager);
relativeLayoutBottom = (RelativeLayout) view.findViewById(R.id.rlBottom);
genericRegionListAdapter = new GenericRegionListAdapter(context, regionDetailArrayList, this, false);
regionRecyclerView.setAdapter(genericRegionListAdapter);
addTextListener();
return view;
}
public void addTextListener(){
editTextSearchView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
genericRegionListAdapter.getFilter().filter(query.toString());
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onRecyclerItemClicked(int position, String itemName, String itemID) {
Log.v("Region Name", " : " + regionDetailArrayList.get(position).getRegionName());
}
}
Adapter Class :
public class GenericRegionListAdapter extends RecyclerView.Adapter<GenericRegionListAdapter.DataObjectHolder>
implements Filterable {
private ArrayList<RegionDetail> originalArrayList;
private ArrayList<RegionDetail> filterArrayList;
private GenericRegionListAdapter.ValueFilter valueFilter;
private OnRecylerViewClickable onRecylerViewClickable;
private Context mContext = null;
#Override
public GenericRegionListAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sd_custom_cardview_for_walk_list_item, parent, false);
GenericRegionListAdapter.DataObjectHolder dataObjectHolder = new GenericRegionListAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new GenericRegionListAdapter.ValueFilter();
}
return valueFilter;
}
public class DataObjectHolder extends RecyclerView.ViewHolder{
TextView textViewWalkName;
public DataObjectHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
textViewWalkName = (TextView) itemView.findViewById(R.id.textView_Walk_Name);
}
}
public GenericRegionListAdapter(Context context, ArrayList<RegionDetail> detailsArrayList,
OnRecylerViewClickable onRecylerViewClickable, boolean doShowCheckbox) {
mContext = context;
this.originalArrayList = detailsArrayList;
this.filterArrayList = detailsArrayList;
this.onRecylerViewClickable = onRecylerViewClickable;
}
#Override
public void onBindViewHolder(final GenericRegionListAdapter.DataObjectHolder holder, final int position) {
holder.textViewWalkName.setText(originalArrayList.get(position).getRegionName());
holder.textViewWalkName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRecylerViewClickable.onRecyclerItemClicked(position, originalArrayList.get(position).getRegionName(), originalArrayList.get(position).getRegionID());
}
});
}
// method to access in activity after updating selection
public ArrayList<RegionDetail> getRegionList() {
return originalArrayList;
}
#Override
public int getItemCount() {
return originalArrayList.size();
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
for (int i = 0; i < filterArrayList.size(); i++) {
if ((filterArrayList.get(i).getRegionName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filterArrayList.size();
results.values = filterArrayList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
Log.v("Size", " : " + originalArrayList.size());
if (originalArrayList.size() == 0) {
new GlobalToast().showToastMessage(mContext, mContext.getResources().getString(R.string.no_records_found));
}
}
}
}
Please help me.
Please use this code snippet
private class ItemFilter extends Filter {
String filterString;
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = filterArrayList.size();
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
String filterableString;
for (int i = 0; i < count; i++) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
results.values =filterList;
results.count = filterList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
}
}
i hope this code will filter your list correctly and you get right list item onClick.

Categories

Resources