Wrong position after filter - android

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

Related

Recyclerview Search Filter not working android

My title is coming from retrofit.when I type anything in searchview it doesnt show any result/Suggestion when typed. here is the ss ---> enter image description here
im referring this blog --> https://velmm.com/android-recyclerview-search-filter-example/
help will be appreciated...thanks in advance
Search activity:
public class Search extends AppCompatActivity {
SearchView searchView;
RecyclerView recyclerView;
SearchAdapter slAdapter;
List<StartLearning.SlModel> movieList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
searchView=findViewById(R.id.searchView);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
searchView.onActionViewExpanded();
searchView.setIconified(true);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
slAdapter = new SearchAdapter();
recyclerView.setAdapter(slAdapter);
movieList = new ArrayList<>();
SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
retrofit2.Call<List<StartLearning.SlModel>> call = service.getMySlmodel();
call.enqueue(new Callback<List<StartLearning.SlModel>>() {
#Override
public void onResponse(retrofit2.Call<List<StartLearning.SlModel>> call, Response<List<StartLearning.SlModel>> response) {
movieList = response.body();
Log.d("TAG","Response = "+movieList);
slAdapter.setMovieList(getApplicationContext(),movieList);
}
#Override
public void onFailure(retrofit2.Call<List<StartLearning.SlModel>> call, Throwable t) {
Log.d("TAG","Response = "+t.toString());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1, menu);
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);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
slAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
slAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() ==android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
Search Adapter
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.CustomViewHolder> implements Filterable {
List<StartLearning.SlModel> Slmdel;
List<StartLearning.SlModel> Slmdel1;
Context context;
public SearchAdapter() {
}
public void setMovieList(Context context, final List<StartLearning.SlModel> movieList){
this.context = context;
if(this.Slmdel == null){
this.Slmdel = movieList;
this.Slmdel1 = movieList;
notifyItemChanged(0, Slmdel1.size());
} else {
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
#Override
public int getOldListSize() {
return SearchAdapter.this.Slmdel.size();
}
#Override
public int getNewListSize() {
return movieList.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return SearchAdapter.this.Slmdel.get(oldItemPosition).getTitle() == movieList.get(newItemPosition).getTitle();
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
StartLearning.SlModel newMovie = SearchAdapter.this.Slmdel.get(oldItemPosition);
StartLearning.SlModel oldMovie = movieList.get(newItemPosition);
return newMovie.getTitle() == oldMovie.getTitle() ;
}
});
this.Slmdel = movieList;
this.Slmdel1 = movieList;
result.dispatchUpdatesTo(this);
}
}
public SearchAdapter(Context context,List<StartLearning.SlModel> employees) {
this.Slmdel = employees;
this.context=context;
}
#Override
public SearchAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.startlearning_item, parent, false);
return new SearchAdapter.CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(SearchAdapter.CustomViewHolder holder, int position) {
holder.textView.setText(String.valueOf(position+1)+". ");
holder.employeeName.setText(Slmdel.get(position).getTitle());
}
#Override
public int getItemCount() {
if(Slmdel != null){
return Slmdel1.size();
} else {
return 0;
}
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
Slmdel1 = Slmdel;
} else {
List<StartLearning.SlModel> filteredList = new ArrayList<>();
for (StartLearning.SlModel movie : Slmdel) {
if (movie.getTitle().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(movie);
}
}
Slmdel1 = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = Slmdel1;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
Slmdel1 = (ArrayList<StartLearning.SlModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView employeeName;
TextView textView;
public CustomViewHolder(View view) {
super(view);
employeeName = (TextView) view.findViewById(R.id.Sl2);
textView=view.findViewById(R.id.Sl1);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NextSLactivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title", Slmdel.get(getAdapterPosition()).getTitle());
intent.putExtra("idSLnext", Slmdel.get(getAdapterPosition()).getId());
//Log.e("ashwini",WAmdel.get(getAdapterPosition()).getId());
context.startActivity(intent);
}
});
}
}
}
List:
public class SlModel
{
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
public SlModel(String id, String title) {
this.id = id;
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "SlModel{" +
"title='" + title + '\'' +
'}';
}
}}
package zon.searchview.com;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> implements Filterable {
Context context;
ArrayList<ItemModel> arrayList,arrayListFiltered;
public CustomAdapter(Context context, ArrayList<ItemModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayListFiltered = arrayList;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_list, viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(viewHolder viewHolder, int position) {
viewHolder.name.setText(arrayListFiltered.get(position).getName());
viewHolder.image.setImageResource(arrayListFiltered.get(position).getImage());
}
#Override
public int getItemCount() {
return arrayListFiltered.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView image;
public viewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayListFiltered.get(getAdapterPosition()).getName(),Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<ItemModel> arrayListFilter = new ArrayList<ItemModel>();
if(constraint == null|| constraint.length() == 0) {
results.count = arrayList.size();
results.values = arrayList;
} else {
for (ItemModel itemModel : arrayList) {
if(itemModel.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
arrayListFilter.add(itemModel);
}
}
results.count = arrayListFilter.size();
results.values = arrayListFilter;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListFiltered = (ArrayList<ItemModel>) results.values;
notifyDataSetChanged();
if(arrayListFiltered.size() == 0) {
Toast.makeText(context, "Not Found", Toast.LENGTH_LONG).show();
}
}
};
return filter;`enter code here`
}
}
For more visit this:- https://www.11zon.com/zon/android/filter-recyclerview-with-searchview.php

how to search arraylist data in recyclerview in fragment

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

Filter on RecyclerView shows only the first value in the list

I have a RecyclerView populated by a RoomDatabase and created a SearchView to filter the results if I want to extract a specific set of values from there.
The issues are as follows:
The list gets populated only after I click on the search button, not when the view is opened.
When using the search bar, whatever I write, as long as it is an element from the list, it only shows the element on the first position. If I type something that is not part of the list, it shows the list blank, so this works at least.
This is the code for the Adapter:
public class AbonamenteAdapter2 extends RecyclerView.Adapter<AbonamenteAdapter2.AbonamenteHolder2> implements Filterable {
private List<Abonamente> abonamente;
private List<Abonamente> abonamenteFiltered;
private OnItemClickClickListener listener;
public void setAbonamente(final List<Abonamente> abonamente) {
//this.context = (Context) context;
if (this.abonamente == null) {
this.abonamente = abonamente;
this.abonamenteFiltered = abonamente;
notifyItemChanged(0, abonamenteFiltered.size());
} else {
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
#Override
public int getOldListSize() {
return AbonamenteAdapter2.this.abonamente.size();
}
#Override
public int getNewListSize() {
return abonamente.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return AbonamenteAdapter2.this.abonamente.get(oldItemPosition).getTreatPicked() ==
abonamente.get(newItemPosition).getTreatPicked();
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
Abonamente newAbonament = AbonamenteAdapter2.this.abonamente.get(oldItemPosition);
Abonamente oldAbonament = abonamente.get(newItemPosition);
return newAbonament.getTreatPicked() == oldAbonament.getTreatPicked();
}
});
this.abonamente = abonamente;
this.abonamenteFiltered = abonamente;
result.dispatchUpdatesTo(this);
}
}
#NonNull
#Override
public AbonamenteHolder2 onCreateViewHolder (#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new AbonamenteHolder2(view);
}
#Override
public void onBindViewHolder(#NonNull AbonamenteHolder2 holder2, int position) {
Abonamente currentAb = abonamente.get(position);
holder2.treatChosen.setText(currentAb.getTreatPicked());
//holder2.treatChosen.setText(abonamente.get(position).getTreatPicked());
//holder2.treatDisplay = abonamente.getTreatDisplay();
//holder2.treatPrice = abonamente.getPrice();
}
#Override
public int getItemCount() {
if(abonamente != null) {
return abonamenteFiltered.size();
} else {
return 0;
}
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
abonamenteFiltered = abonamente;
} else {
List<Abonamente> filteredList = new ArrayList<>();
for (Abonamente abonament : abonamente) {
if (abonament.getTreatPicked().toLowerCase()
.contains(charString.toLowerCase())) {
filteredList.add(abonament);
}
}
abonamenteFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = abonamenteFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
abonamenteFiltered = (ArrayList<Abonamente>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class AbonamenteHolder2 extends RecyclerView.ViewHolder {
TextView treatChosen;
public AbonamenteHolder2(View view) {
super(view);
treatChosen = view.findViewById(R.id.element);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if(listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(abonamente.get(position));
}
}
});
}
}
public interface OnItemClickClickListener {
void onItemClick(Abonamente abonamente);
}
public void setOnItemClickListener(OnItemClickClickListener listener) {
this.listener = listener;
}
}
And this is the code for the activity with the list and search bar. It is triggered by a button press from a different activity:
public class RecyclerList extends AppCompatActivity {
public static final int GET_DATA_LIST = 1;
private SearchView searchView;
private AbonamenteAdapter2 adapter;
private AbonamenteViewModel viewModel;
private String treatDisplay;
private int treatPrice;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_list);
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
adapter = new AbonamenteAdapter2();
recyclerView.setAdapter(adapter);
viewModel = ViewModelProviders.of(this).get(AbonamenteViewModel.class);
viewModel.getAllEntries().observe(this, new Observer<List<Abonamente>>() {
#Override
public void onChanged(#Nullable List<Abonamente> abonamentes) {
adapter.setAbonamente(abonamentes);
}
});
adapter.setOnItemClickListener(new AbonamenteAdapter2.OnItemClickClickListener() {
#Override
public void onItemClick(Abonamente abonamente) {
Intent intent = new Intent(RecyclerList.this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_ID, abonamente.getId());
intent.putExtra(MainActivity.EXTRA_CHOICE, abonamente.getTreatPicked());
intent.putExtra(MainActivity.EXTRA_TREAT, abonamente.getTreatDisplay());
intent.putExtra(MainActivity.EXTRA_PRICE, abonamente.getPrice());
startActivityForResult(intent, GET_DATA_LIST);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_bar, menu);
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);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit (String query) {
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if(!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
}
I went through the code up and down quite a lot of time and can't seem to figure out what the issue is.
This may be comment for your question but here because of low reputation i need to write answer.
onBindViewHolder method you need to set your filtered list to your Model.
Use
Abonamente currentAb = abonamenteFiltered .get(position);
Instead of
Abonamente currentAb = abonamente.get(position);

To pass only incremented value to listview on nextpage

I am able to send data on listview in nextpage.But problem is that items with quantity 0 is also passed.I want to show items whose quantity is incremented and not all items present in listview.Here is my code-
MainActivity.java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{
Button show;
ListView list_item;
ArrayList<Items> itemsArrayList;
SearchView searchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
intent.putExtra("data", itemsArrayList);
startActivity(intent);
}
});
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
}
public void setupSearchView()
{
searchview.setOnQueryTextListener(this);
searchview.setQueryHint("Search Here");
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)) {
list_item.clearTextFilter();
} else {
list_item.setFilterText(s);
}
return true;
}
}
Custom.java
public class Custom extends BaseAdapter implements Filterable{
Activity a;
ArrayList<Items> itemsArrayList;
ArrayList<Items> filtered;
public Custom(Activity a, ArrayList<Items> itemsArrayList) {
this.a = a;
this.itemsArrayList = itemsArrayList;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int i) {
return itemsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results=new FilterResults();
ArrayList<Items> data=new ArrayList<Items>();
if (filtered==null)
filtered=itemsArrayList;
if (filtered != null && filtered.size() > 0) {
for (final Items g : filtered) {
if (g.getItemname().toLowerCase()
.contains(charSequence.toString()))
data.add(g);
}
results.values=data;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsArrayList=(ArrayList<Items>)filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public class Holder{
TextView sr,item,qty,price,pl,min,rate;
}
#Override
public View getView(final int position, final View view, ViewGroup viewGroup) {
final Holder holder=new Holder();
LayoutInflater li=a.getLayoutInflater();
final View view1=li.inflate(R.layout.customlist,viewGroup,false);
holder.sr=(TextView)view1.findViewById(R.id.s_no);
holder.item=(TextView)view1.findViewById(R.id.i_name);
holder.qty=(TextView)view1.findViewById(R.id.qty);
holder.price=(TextView)view1.findViewById(R.id.pr);
holder.rate=(TextView)view1.findViewById(R.id.frate);
holder.pl=(TextView) view1.findViewById(R.id.pl);
holder.min=(TextView) view1.findViewById(R.id.min);
final Items model = itemsArrayList.get(position);
holder.sr.setText(String.valueOf(itemsArrayList.get(position).getSrno()));
holder.item.setText(String.valueOf(itemsArrayList.get(position).getItemname()));
holder.rate.setText(String .valueOf(itemsArrayList.get(position).getFixedrate()));
holder.qty.setText(String.valueOf(itemsArrayList.get(position).getQuantity()));
holder.price.setText(String .valueOf(itemsArrayList.get(position).getRate()));
holder.pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity(model.getQuantity() + 1);
model.setRate(model.getQuantity()*model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
});
holder.min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(model.getQuantity()>0) {
model.setQuantity(model.getQuantity() - 1);
model.setRate(model.getQuantity() * model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
}
});
return view1;
}
}
Items.java
public class Items implements Serializable {
int srno,fixedrate,quantity,rate;
String itemname;
public Items(int srno, String itemname, int fixedrate, int quantity, int rate) {
this.srno = srno;
this.itemname = itemname;
this.fixedrate = fixedrate;
this.quantity = quantity;
this.rate = rate;
}
public int getSrno() {
return srno;
}
public void setSrno(int srno) {
this.srno = srno;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public int getFixedrate() {
return fixedrate;
}
public void setFixedrate(int fixedrate) {
this.fixedrate = fixedrate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
Custom_Trial.java
public class Custom_Trial extends BaseAdapter {
Activity a;
private ArrayList<Items> data = new ArrayList<>();
public Custom_Trial(Activity a, ArrayList<Items> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView sr, it, qty, amt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
LayoutInflater li = a.getLayoutInflater();
View view = li.inflate(R.layout.customtrial, parent, false);
holder.sr = (TextView) view.findViewById(R.id.head1);
holder.it = (TextView) view.findViewById(R.id.head2);
holder.qty = (TextView) view.findViewById(R.id.head3);
holder.amt = (TextView) view.findViewById(R.id.head4);
Items m = data.get(position);
holder.sr.setText(String.valueOf(m.getSrno()));
holder.it.setText(m.getItemname());
holder.qty.setText(String.valueOf(m.getQuantity()));
holder.amt.setText(String.valueOf(m.getRate()));
return view;
}
}
Trial.java
public class Trial extends Activity{
ListView listnew;
private ArrayList<Items> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trial);
listnew = (ListView) findViewById(R.id.newlist);
data.addAll((ArrayList<Items>) getIntent().getSerializableExtra("data"));
Custom_Trial ct = new Custom_Trial(this,data);
listnew.setAdapter(ct);
}
}
It's because you passing original list. You're updating values inside adapter and passing not updated list fromadapter, but original. Write method inside adapter to return your updated list.
Inside Custom.java adapter:
public ArrayList<Items> getItems(){
ArrayList<Items> quantityArrayList;
Items item;
for (int i = 0; i < itemsArrayList.size(); i++){
item = itemsArrayList.get(i);
if (item.getQuantity() > 0)
quantityArrayList.add(item);
}
return quantityArrayList;
}
And inside MainActivity onCreate() should look like this. After clicking show button you're going to get Items from Custom Adapter whose quantity >0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
List<Items> quantityList = c.getItems();
intent.putExtra("data", quantityList);
startActivity(intent);
}
});
}

Filter Recyclerview From Array of objects Android

i have RecyclerView get data from Array of objects , and i tried to make Filter in Recycler View adapter like this ,
public void filter(String filterString) {
filterString = filterString.toLowerCase(Locale.getDefault());
results.clear();
if(filterString.length() == 0) {
}
else {
for( ToDo item : stringArrayList){
if(item.getTODO_TITLE().toLowerCase(Locale.getDefault()).contains(filterString)) {
results.add(item.getTODO_TITLE() );
}
}
}
notifyDataSetChanged();
}
}
and when i call it in menu like this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
if (searchQuery.length() != 0) {
if (null != recyclerAdapter) {
recyclerAdapter.filter(searchQuery.toString());
todoRecyclerView.invalidate();
todoAdapter.notifyDataSetChanged();
}
}
else{
}
return false;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}}
its not working , and no error is showing !!! how i can solve this problem ????
this is my code into recycler
public class TodoList extends AppCompatActivity implements DialogFragUpdateListener {
RecyclerView todoRecyclerView;
private RecyclerView.Adapter todoAdapter;
private RecyclerView.LayoutManager todoLayoutManager;
public List<ToDo> results;
public List<String> list = new ArrayList<>();
TodoRecyclerAdapter recyclerAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_list);
todoRecyclerView = (RecyclerView)findViewById(R.id.todoRecyclerView);
todoRecyclerView.setHasFixedSize(true);
results= new ArrayList<ToDo>();
todoLayoutManager = new LinearLayoutManager(this);
todoRecyclerView.setLayoutManager(todoLayoutManager);
getRetrofitObject();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TodoList.this,AddToDo.class);
startActivity(intent);
}
});}
public void getRetrofitObject() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<Result> call = service.getresults();
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
results = response.body().getResults();
todoRecyclerView.setAdapter(new TodoRecyclerAdapter(this,results));
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("onFailure", t.toString());
}});}
Recycler View Adpater
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> {
static List<ToDo> todoResults;
static Context context;
List<String> results;
private List<String> mDefaultCheeses;
private List<ToDo> mData;
private List<ToDo> originalData;
private ArrayList<ToDo> arrayList = null, stringArrayList;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arrayList= (ArrayList<ToDo>) results;
}
#Override
public TodoRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_items, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final TodoRecyclerAdapter.ViewHolder holder, final int position) {
holder.todoTitle.setText(todoResults.get(position).getTODO_TITLE().toString());
String priority = todoResults.get(position).getPriority().toString();
if (priority.equals("Low")) {
holder.todoImage.setImageResource(R.drawable.low);
} else if (priority.equals("Normal")) {
holder.todoImage.setImageResource(R.drawable.normal);
} else if (priority.equals("High")) {
holder.todoImage.setImageResource(R.drawable.high);
}
}
#Override
public int getItemCount() {
return todoResults.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView todoTitle;
public ImageView todoImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
todoTitle = (TextView) itemLayoutView.findViewById(R.id.todo_title);
todoImage = (ImageView) itemLayoutView.findViewById(R.id.imageView2);
}
}
public void filter(String filterString) {
filterString = filterString.toLowerCase(Locale.getDefault());
results.clear();
if(filterString.length() == 0) {
}
else {
for( ToDo item : stringArrayList){
if(item.getTODO_TITLE().toLowerCase(Locale.getDefault()).contains(filterString)) {
results.add(item.getTODO_TITLE() );
}
}
}
notifyDataSetChanged();
}
}
I think the error isn't in the logs because you aren't adding elements to results. You must log your code and see what is happening there.
Maybe this will help you:
In your filter method try this:
ArrayList<Note> result;
List<ToDO>itemsCopy = new ArrayList<>();
private void filter(String text){
itemsCopy= items in results arraylist
result = new ArrayList<>();
text = text.toLowerCase();
for(ToDO item: itemsCopy){
if(item.getTitle().toLowerCase().contains(text)){
result.add(item);
}
}
results.clear();
results.addAll(result);
notifyDataSetChanged();
//Log your code! Always helps
Log.i(TAG, "---RESULT--" +result.toString());
}
Then in OnCreateOptionsMenu:
#Override
public boolean onQueryTextSubmit(String query) {
filter(query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(newText);
return true;
}
});
Hope it helps!

Categories

Resources