Hi I have a problem with click on the cardview, in practice since I added a searchview on the toolbar to search for items on the list I create, selecting an object in the list does not allow me to go to change parameters through the edit class
you would be so kind as to help me solve this problem and help me understand where I'm wrong
RoomAdapter
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.TicketHolder> implements Filterable {
//List<TicketEntity> ticketEntity = new ArrayList<>();
private List<TicketEntity> ticketEntity;
private List<TicketEntity> ticketEntitySearch;
private Context mCtx;
public RoomAdapter(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
// this.mCtx = mCtx;
ticketEntitySearch = new ArrayList<>(ticketEntity);
}
#Override
public TicketHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_recyclerview, parent, false);
return new TicketHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TicketHolder holder, int position) {
TicketEntity currenTicket = ticketEntity.get(position);
holder.mTextticket.setText(currenTicket.getNumticket());
holder.mTextredattore.setText(currenTicket.getRedattore());
holder.mTexttarga.setText(currenTicket.getTarga());
holder.mTextdataA.setText(currenTicket.getDopen());
holder.mTextmanutenzioneG.setText(currenTicket.getMateriale());
holder.mTextdataC.setText(currenTicket.getDclosed());
}
#Override
public int getItemCount() {
return ticketEntity.size();
}
public void setTicketEntity(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
notifyDataSetChanged();
}
void setTickets(List<TicketEntity> tickets){
ticketEntity = tickets;
notifyDataSetChanged();
}
#Override
public Filter getFilter() {
return ticketFilter;
}
private Filter ticketFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<TicketEntity>filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0){
filteredList.addAll(ticketEntitySearch);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for (TicketEntity item : ticketEntitySearch){
if(item.getNumticket().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ticketEntity.clear();
ticketEntity.addAll((List)results.values);
notifyDataSetChanged();
}
};
class TicketHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mTextticket,mTextredattore,mTexttarga,mTextdataA,mTextmanutenzioneG,mTextdataC;
Context mCtx;
//todo Costructor
public TicketHolder(#NonNull View itemView) {
super(itemView);
mTextticket = itemView.findViewById(R.id.txt_ticket);
mTextredattore = itemView.findViewById(R.id.txt_redattore);
mTexttarga = itemView.findViewById(R.id.txt_targa);
mTextdataA = itemView.findViewById(R.id.txt_dataA);
mTextmanutenzioneG = itemView.findViewById(R.id.txt_materiale);
mTextdataC = itemView.findViewById(R.id.txt_dataC);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TicketEntity ticket = ticketEntity.get(getAdapterPosition());
Intent intent = new Intent(mCtx,ModificaActivity.class);
intent.putExtra("ticket", ticket);
mCtx.startActivity(intent);
}
}
/*public TicketEntity getTicketSwipe(int position){
return ticketEntity.get(position);
}
*/
}
Visualizza
package alessandro.mystudio.ticketfirebase;
public class Visualizza extends AppCompatActivity {
RecyclerView mRecyclerView;
Toolbar mToolbar;
List<TicketEntity> tickets;
RoomAdapter adapter;
private AppDatabase appDatabase;
private Context mCtx;
//private static final String TAG = "Visualizza";
//public static final int ADD_TICKET_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
mToolbar = findViewById(R.id.toolbarLayout);
setSupportActionBar(mToolbar);
appDatabase = AppDatabase.getDatabase(this);
BuildRecyclearView();
new getAll().execute();
new ItemTouchHelper(simpleCallback).attachToRecyclerView(mRecyclerView);
}
//TODO METODO DI SWIPE DELETE SULLA CARDVIEW
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT)
{
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if(tickets !=null){
TicketEntity swipedTicket = tickets.get(viewHolder.getAdapterPosition());
if(swipedTicket != null){
swipeToDelete(swipedTicket, viewHolder);
}
}
}
};
//TODO MESSAGGIO ALERT DIALOG DI CONFERMA OPPURE DI ANNULLARE
private void swipeToDelete( final TicketEntity swipedTicket, final RecyclerView.ViewHolder viewHolder) {
new AlertDialog.Builder(Visualizza.this)
.setMessage("Delete Ticket?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 delete note
// Item swiped.
int pos = viewHolder.getAdapterPosition();
// Remove from database
new deleteTicket(pos).execute(tickets.get(pos));
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 Undo swipe and restore swipedNote
mRecyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());
}
})
.setCancelable(false)
.create().show();
}
//TODO Costruzione della RecyclerView
public void BuildRecyclearView() {
//todo dichiarazione adapter e chiamiamo il suo costruttore passandogli i parametri necessari
mRecyclerView = findViewById(R.id.miorecyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
//TODO VISUALIZZARE TUTTI I TICKET
private class getAll extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... voids) {
tickets = (List<TicketEntity>) appDatabase.ticketDao().getAll();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new RoomAdapter(tickets);
mRecyclerView.setAdapter(adapter);
}
}
//TODO MESSAGGIO DI ALERDIALOG
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setIcon(R.drawable.ic_error);
builder.setMessage(Message);
builder.show();
}
//TODO Procedura ToolBar Menu & SearchView
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_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;
}
//TODO DELETE TICKET
private class deleteTicket extends AsyncTask<TicketEntity, Void, Void>
{
int pos;
public deleteTicket(int pos) {
this.pos = pos;
}
#Override
protected Void doInBackground(TicketEntity... ticketEntities) {
appDatabase.ticketDao().deleteTicket(ticketEntities[0].getId());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
tickets.remove(pos);
adapter.notifyItemRemoved(pos);
}
}
}
Related
everyone
I have recyclerView retrieve data from firebase database
I used searchview and filter list to search item , but when click on searchview to search something all items disappear and search view not working
my main activity is fragment because I use bottom navigation
public class RV_Worker_Fragment extends Fragment implements RecyclerView_InterFace {
private RecyclerView rv_worker;
private FirebaseDatabase db;
private ArrayList <WorkerModel> list;
private WorkerAdapter workerAdapter;
SearchView searchView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rv_persons_fragment,
container, false);
rv_worker =view.findViewById(R.id.recyclerView_persons);
db =FirebaseDatabase.getInstance();
rv_worker.setHasFixedSize(true);
rv_worker.setLayoutManager(new LinearLayoutManager(getActivity()));
searchView = view.findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
workerAdapter.getFilter().filter(newText);
return false;
}
});
getList();
return view;
}
private void getList()
{
db.getReference("Employees").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list=new ArrayList <>();
workerAdapter = new WorkerAdapter(getActivity(),list,RV_Worker_Fragment.this);
rv_worker.setAdapter(workerAdapter);
for (DataSnapshot child :snapshot.getChildren())
{
WorkerModel workerModel =child.getValue(WorkerModel.class);
list.add(workerModel);
workerAdapter.notifyItemInserted(list.size()-1);
workerAdapter.getItemCount();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(final int position) {
Intent intent = new Intent(getActivity(), Worker_Details.class);
intent.putExtra("name",list.get(position).getName());
intent.putExtra("id",list.get(position).getId());
startActivity(intent);
}
}
Adapter
public class WorkerAdapter extends RecyclerView.Adapter <WorkerAdapter.ViewHolder> implements Filterable {
private Context context;
private List <WorkerModel> list;
private List <WorkerModel> listFilter;
private RecyclerView_InterFace recyclerView_interFace;
public WorkerAdapter(Context context, List <WorkerModel> llist, RecyclerView_InterFace recyclerView_interFace) {
this.context = context;
this.list = llist;
this.recyclerView_interFace = recyclerView_interFace;
listFilter = new ArrayList <>(list);
}
#NonNull
#Override
public WorkerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_worker_treader_contractor, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final WorkerAdapter.ViewHolder holder, final int position) {
final WorkerModel workerModel = list.get(position);
holder.tv_name.setText(workerModel.getName());
holder.btn_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phonNumber = workerModel.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+phonNumber));
context.startActivity(intent);
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(context)
.setTitle("حذف")
.setMessage("هل تريد الحذف")
.setPositiveButton("نعم", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference("Employees");
db.child(list.get(position).getId()).removeValue();
}
})
.setNegativeButton("لا",null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_name;
ImageView btn_call, btn_delete ;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tx_name);
btn_call = itemView.findViewById(R.id.btn_call);
btn_delete = itemView.findViewById(R.id.btn_deleteP);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerView_interFace.onItemClick(getAdapterPosition());
}
});
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<WorkerModel> listFilter2 = new ArrayList <>();
if (charSequence ==null || charSequence.length()==0){
// if search text is empty add all original list values to filterlist
listFilter2.addAll(listFilter);
}else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
for (WorkerModel workerModel : listFilter){
if (workerModel.getName().toLowerCase().contains(filterPattern)){
listFilter2.add(workerModel);
}
}
}
FilterResults results = new FilterResults();
results.values = listFilter2;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
list.clear();
list.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
}
what is the problem guys?
thx in advance for help
Try inside performFiltering() of WorkerAdapter, add the following line as the first line: if (listFilter.size() == 0) listFilter = new ArrayList<>(list);
After searching for RecyclerView items in Android, always open first item of RecyclerView When I opened the searched item, it is opening the first item of RecyclerView not the searched one. Even if search and find the items successfuly.
MainActivity.java
public class MainActivityDalil extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Adapter adapter;
private List<Pets> petsList;
ApiInterface apiInterface;
Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_dalil);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listener = new Adapter.RecyclerViewClickListener() {
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(MainActivityDalil.this, ViewActivity.class);
intent.putExtra("id", petsList.get(position).getId());
intent.putExtra("name", petsList.get(position).getName());
intent.putExtra("species", petsList.get(position).getSpecies());
intent.putExtra("breed", petsList.get(position).getBreed());
intent.putExtra("gender", petsList.get(position).getGender());
intent.putExtra("picture", petsList.get(position).getPicture());
intent.putExtra("birth", petsList.get(position).getBirth());
startActivity(intent);
}
#Override
public void onLoveClick(View view, int position) {
final int id = petsList.get(position).getId();
final Boolean love = petsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
petsList.get(position).setLove(false);
updateLove("update_love", id, false);
adapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
petsList.get(position).setLove(true);
updateLove("update_love", id, true);
adapter.notifyDataSetChanged();
}
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivityDalil.this, EditorActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
public void getPets(){
Call<List<Pets>> call = apiInterface.getPets();
call.enqueue(new Callback<List<Pets>>() {
#Override
public void onResponse(Call<List<Pets>> call, Response<List<Pets>> response) {
progressBar.setVisibility(View.GONE);
petsList = response.body();
Log.i(MainActivity.class.getSimpleName(), response.body().toString());
adapter = new Adapter(petsList, MainActivityDalil.this, listener);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Pets>> call, Throwable t) {
Toast.makeText(MainActivityDalil.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
Call<Pets> call = apiInterface.updateLove(key, id, love);
call.enqueue(new Callback<Pets>() {
#Override
public void onResponse(Call<Pets> call, Response<Pets> response) {
Log.i(MainActivity.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(MainActivityDalil.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivityDalil.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Pets> call, Throwable t) {
Toast.makeText(MainActivityDalil.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
Customfilter.java
public class CustomFilter extends Filter {
Adapter adapter;
ArrayList<Pets> filterList;
public CustomFilter(ArrayList<Pets> filterList, Adapter adapter)
{
this.adapter=adapter;
this.filterList=filterList;
}
//FILTERING OCURS
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
//CHECK CONSTRAINT VALIDITY
if(constraint != null && constraint.length() > 0)
{
//CHANGE TO UPPER
constraint=constraint.toString().toUpperCase();
//STORE OUR FILTERED PLAYERS
ArrayList<Pets> filteredPets=new ArrayList<>();
for (int i=0;i<filterList.size();i++)
{
//CHECK
if(filterList.get(i).getName().toUpperCase().contains(constraint))
{
//ADD PLAYER TO FILTERED PLAYERS
filteredPets.add(filterList.get(i));
}
}
results.count=filteredPets.size();
results.values=filteredPets;
}else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.pets= (ArrayList<Pets>) results.values;
//REFRESH
adapter.notifyDataSetChanged();
}
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable {
List<Pets> pets, petsFilter;
private Context context;
private RecyclerViewClickListener mListener;
CustomFilter filter;
public Adapter(List<Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.petsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getBreed() + " / "
+ pets.get(position).getSpecies());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new CustomFilter((ArrayList<Pets>) petsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
What am I missing?
I have recyclerview with searchview and have details data sended when select item in recyclerview
problem is when i search about item and select it the details data not change always appears the first item's details data
how can i send details data about the items that i searched about
i think it not big issue so pls help me
this my code:
in my Main avtivity
private void initRecyclerView(){
RecyclerView recyclerView = findViewById(R.id.recyclerView);
// adapter = new RecyclerViewAdapter(mNames,mImageUsls,this);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(menuItems,this);
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(int position) {
com.example.t.MenuItem menuItemmmmm = menuItems.get(position);
Intent intent = new Intent(secondActivity.this,details_page.class);
intent.putExtra("image",menuItemmmmm.getImageResource());
intent.putExtra("name",menuItemmmmm.getOilName());
intent.putExtra("details1",details.get(position));
intent.putExtra("details2",details2.get(position));
intent.putExtra("details3",details3.get(position));
intent.putExtra("details4",details4.get(position));
intent.putExtra("details5",details5.get(position));
intent.putExtra("details6",details6.get(position));
intent.putExtra("howToUse",howToUse.get(position));
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView =(SearchView) searchItem.getActionView();
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;
}
RecyclerviwAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private List<MenuItem> MenuItemsList;
private List<MenuItem> MenuItemListFilter; // نسخة من الزيوت
private RecyclerViewOnItemClick recyclerViewOnItemClick;
public RecyclerViewAdapter(List <MenuItem> nMenuItemsList, RecyclerViewOnItemClick NrecyclerViewOnItemClick) {
this.MenuItemsList = nMenuItemsList;
this.recyclerViewOnItemClick = NrecyclerViewOnItemClick;
MenuItemListFilter = new ArrayList <>(MenuItemsList);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item,parent,false);
ViewHolder holder =new ViewHolder(view,recyclerViewOnItemClick);
return holder; }
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
MenuItem menuItem = MenuItemsList.get(position);
holder.image.setImageResource(menuItem.getImageResource());
holder.imageName.setText(menuItem.getOilName());
}
#Override
public int getItemCount() {
return MenuItemsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView image;
TextView imageName;
CardView parentLayout;
RecyclerViewOnItemClick recyclerViewOnItemClick;
public ViewHolder(#NonNull View itemView , RecyclerViewOnItemClick recyclerViewOnItemClick) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.RelativeLayout);
this.recyclerViewOnItemClick =recyclerViewOnItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
recyclerViewOnItemClick.onItemClick(getAdapterPosition());
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<MenuItem> filterList = new ArrayList <>();
if (charSequence ==null || charSequence.length()==0){
// if search text is empty add all original list values to filterlist
filterList.addAll(MenuItemListFilter);
}else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
for (MenuItem menuu : MenuItemListFilter){
if (menuu.getOilName().toLowerCase().contains(filterPattern)){
filterList.add(menuu);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
MenuItemsList.clear();
MenuItemsList.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
public interface RecyclerViewOnItemClick {
void onItemClick(int position);
}
}
Avtivity that i send data to it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_of_oil);
imageView= findViewById(R.id.image_name);
Pdetails =findViewById(R.id.deltail_Text1);
Pdetails2 =findViewById(R.id.deltail_Text2);
Pdetails3 =findViewById(R.id.deltail_Text3);
Pdetails4 =findViewById(R.id.deltail_Text4);
Pdetails5 =findViewById(R.id.deltail_Text5);
Pdetails6 =findViewById(R.id.deltail_Text6);
price = findViewById(R.id.price);
toolbar =findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
if (getSupportActionBar()!=null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle extra = getIntent().getExtras();
if (extra != null){
int image = extra.getInt("image");
String name = extra.getString("name");
String detail1 = extra.getString("details1");
String detail2 = extra.getString("details2");
String detail3 = extra.getString("details3");
String detail4 = extra.getString("details4");
String detail5 = extra.getString("details5");
String detail6 = extra.getString("details6");
String TpriceT = extra.getString("howToUse");
imageView.setImageResource(image);
toolbar.setTitle(name);
Pdetails.setText(detail1);
Pdetails2.setText(detail2);
Pdetails3.setText(detail3);
Pdetails4.setText(detail4);
Pdetails5.setText(detail5);
Pdetails6.setText(detail6);
price.setText(TpriceT);
}
}
Glad you solved the issue. Below is the adapter code for 2nd solution:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private List<MenuItem> MenuItemsList;
private List<Integer> filteredId;
private RecyclerViewOnItemClick recyclerViewOnItemClick;
public RecyclerViewAdapter(List<MenuItem> nMenuItemsList, RecyclerViewOnItemClick NrecyclerViewOnItemClick) {
this.MenuItemsList = nMenuItemsList;
this.recyclerViewOnItemClick = NrecyclerViewOnItemClick;
filteredId = new ArrayList<>();
setDefaultIds(filteredId);
}
private void setDefaultIds(List<Integer> dataList) {
dataList.clear();
for (int i = 0; i < MenuItemsList.size(); i++) dataList.add(i);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item, parent, false);
ViewHolder holder = new ViewHolder(view, recyclerViewOnItemClick);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
MenuItem menuItem = MenuItemsList.get(filteredId.get(position));
holder.image.setImageResource(menuItem.getImageResource());
holder.imageName.setText(menuItem.getOilName());
}
#Override
public int getItemCount() {
return filteredId.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView imageName;
CardView parentLayout;
RecyclerViewOnItemClick recyclerViewOnItemClick;
public ViewHolder(#NonNull View itemView, RecyclerViewOnItemClick recyclerViewOnItemClick) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.RelativeLayout);
this.recyclerViewOnItemClick = recyclerViewOnItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
recyclerViewOnItemClick.onItemClick(filteredId.get(getAdapterPosition()));
}
}
#Override
public Filter getFilter() {
return filter;
}
private Filter filter = new Filter() {
//run on background thread
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<Integer> filterList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
// if search text is empty add all original list values to filterlist
setDefaultIds(filterList);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
// Perform search on whole original list
MenuItem menuu;
for (int i = 0; i < MenuItemsList.size(); i++) {
menuu = MenuItemsList.get(i);
if (menuu.getOilName().toLowerCase().contains(filterPattern)) {
filterList.add(i);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
//run on UI thread
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredId.clear();
filteredId.addAll((List<Integer>) filterResults.values);
notifyDataSetChanged();
}
};
public interface RecyclerViewOnItemClick {
void onItemClick(int id);
}
}
I am trying to sort the list of custom objects and display in Recyclerview. After displaying the items in recyclerview. I am sorting the list in the Activity and calling adapter.notifyDataSetChanged() but its not working.
Code in MainActivity.java:
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
Adapter code:
public class BeerListAdapter extends RecyclerView.Adapter<BeerListAdapter.MyViewHolder> {
private static ClickListener clickListener;
private Context context;
private LayoutInflater inflater;
private List<BeerData> beerDataList;
private List<BeerData> copyList;
public BeerListAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
beerDataList = new ArrayList<>();
copyList = new ArrayList<>();
}
public void setList(List<BeerData> beerDataList) {
if (this.beerDataList.isEmpty()) {
this.beerDataList.addAll(beerDataList);
copyList.addAll(beerDataList);
}
notifyDataSetChanged();
}
public void filter(String query) {
beerDataList.clear();
if (query.isEmpty()) {
beerDataList.addAll(copyList);
} else {
for (BeerData beerData : copyList) {
if (beerData.getName().replaceAll("[\\s]", "").toLowerCase().contains(query.replaceAll("[\\s]", "").toLowerCase())) {
beerDataList.add(beerData);
}
}
}
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_beer_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.beerName.setText(beerDataList.get(position).getName());
holder.styleName.setText(beerDataList.get(position).getStyle());
holder.alcoholContent.setText("Alcohol Content: " + beerDataList.get(position).getAbv());
holder.quantity.setText(beerDataList.get(position).getQuantity().toString());
}
#Override
public int getItemCount() {
return beerDataList.size();
}
public void setOnItemClickListener(ClickListener clickListener) {
BeerListAdapter.clickListener = clickListener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView beerName, alcoholContent, styleName, quantity;
ImageView add, minus;
MyViewHolder(View itemView) {
super(itemView);
beerName = itemView.findViewById(R.id.beerName);
alcoholContent = itemView.findViewById(R.id.alcoholContent);
styleName = itemView.findViewById(R.id.beerStyle);
quantity = itemView.findViewById(R.id.quantity);
add = itemView.findViewById(R.id.add);
minus = itemView.findViewById(R.id.minus);
add.setOnClickListener(this);
minus.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
clickListener.onAddClick(getAdapterPosition(), v);
break;
case R.id.minus:
clickListener.onMinusClick(getAdapterPosition(), v);
break;
}
}
}
public interface ClickListener {
void onAddClick(int position, View v);
void onMinusClick(int position, View v);
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, LoginResultCallBack {
private static final String TAG = MainActivity.class.getSimpleName();
#Inject
MyApplication application;
LoginViewModel loginViewModel;
#BindView(R.id.beerListRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.progressBar)
ProgressBar progressBar;
private BeerListAdapter adapter;
private List<BeerData> beerDataList;
private Menu menu;
private String sortType = "unsorted";
private Disposable networkDisposable;
List<BeerData> originalList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
((MyApplication) getApplication()).getComponent().inject(this);
loginViewModel = ViewModelProviders.of(this,new LoginViewModelFactory(application,this)).get(LoginViewModel.class);
adapter = new BeerListAdapter(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new BeerListAdapter.ClickListener() {
#Override
public void onAddClick(int position, View v) {
addItem(position);
}
#Override
public void onMinusClick(int position, View v) {
removeItem(position);
}
});
}
public void fetchData() {
progressBar.setVisibility(View.VISIBLE);
loginViewModel.fetchData();
loginViewModel.result.observe(this, new Observer<NetworkResponse>() {
#Override
public void onChanged(#Nullable NetworkResponse networkResponse) {
progressBar.setVisibility(View.GONE);
assert networkResponse != null;
if (networkResponse.getPostData() != null) {
beerDataList = new ArrayList<>();
originalList = networkResponse.getPostData();
beerDataList = networkResponse.getPostData();
Log.e(TAG, "Response: " + networkResponse.getPostData().get(0).getAbv());
progressBar.setVisibility(View.GONE);
adapter.setList(networkResponse.getPostData());
} else {
Log.e(TAG, "Response: " + networkResponse.getError().getLocalizedMessage());
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Beer");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cart:
Log.e(TAG, "cart clicked");
break;
case R.id.sort:
if (beerDataList != null) {
if (sortType.equalsIgnoreCase("unsorted")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "ascend";
menu.getItem(2).setTitle(R.string.unsorted);
} else if (sortType.equalsIgnoreCase("ascend")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o2.getAbv().compareToIgnoreCase(o1.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "descend";
menu.getItem(2).setTitle(R.string.view_original);
} else {
Log.e(TAG,beerDataList.size()+" Size");
beerDataList.clear();
beerDataList.addAll(originalList);
adapter.notifyDataSetChanged();
sortType = "unsorted";
menu.getItem(2).setTitle(R.string.sort);
}
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
#Override
protected void onResume() {
super.onResume();
networkDisposable = ReactiveNetwork.observeNetworkConnectivity(application)
.subscribeOn(Schedulers.io())
.filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
.filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Connectivity>() {
#Override
public void accept(final Connectivity connectivity) {
// do something
if (connectivity.isAvailable()) {
fetchData();
} else {
Toast.makeText(MainActivity.this, R.string.internet_issue, Toast.LENGTH_LONG).show();
}
}
});
}
private void addItem(int position) {
int quantity = beerDataList.get(position).getQuantity();
quantity++;
beerDataList.get(position).setQuantity(quantity);
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_full));
adapter.notifyDataSetChanged();
}
private void removeItem(int position) {
if (beerDataList.get(position).getQuantity() > 0) {
int quantity = beerDataList.get(position).getQuantity();
quantity--;
if (quantity == 0)
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_empty));
beerDataList.get(position).setQuantity(quantity);
adapter.notifyDataSetChanged();
}
}
private void safelyDispose(Disposable... disposables) {
for (Disposable subscription : disposables) {
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}
#Override protected void onPause() {
super.onPause();
safelyDispose(networkDisposable);
}
#Override
public void onSuccess(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void showProgress() {
}
#Override
public void hideProgress() {
}
}
What am I doing wrong here ?
You're not passing the sorted list to your adapter. You're just calling notifyDataSetChanged() which just tells the adapter that there is new data in its class and to use the baerDataList that is currently set within the class to refresh the list. Try this in your main activity.
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.setBeerDataList(beerDataList);
And setBeerDataList() in your adapter class.
private List<BeerData> beerDataList;
public void setBeerDataList(List<BeerData> sortedBeerDataList){
this.beerDataList = sortedBeerDataList;
notifyDataSetChanged();
}
Put sort function in MainActivity to BeerListAdapter:
private void sortBeer() {
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
notifyDataSetChanged();
}
then call adapter.sortBeer() when do sort action
i have this recycler view and i get data from Retrofit API, the problem is when i tried to make filter in recycler , i search in the internet and all example is list of strings , but i have list of objects , how i can solve this case and create filter in the toolbar ? i will post my code and hope anyone to help , thank you
Activity
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);
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();
if(recyclerAdapter == null){
recyclerAdapter = new TodoRecyclerAdapter(this,results);
todoRecyclerView.setAdapter(recyclerAdapter);
}
else{
recyclerAdapter.setData(results);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("onFailure", t.toString());
}});}
#Override
public void OnDBUpdate() {
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();
if(recyclerAdapter == null){
recyclerAdapter = new TodoRecyclerAdapter(this,results);
todoRecyclerView.setAdapter(recyclerAdapter);
}
else{
recyclerAdapter.setData(results);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Log.d("onFailure", t.toString());
}});
}
#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) {
recyclerAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
return true;
}
});
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);
}}
and this is Adapter
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> {
static List<ToDo> todoResults;
static Context context;
List<ToDo>results;
ArrayList<ToDo> arraylist;
private List<String> mDefaultCheeses;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
}
#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);
}}
and this is menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.android.nigeriaexams.ui.SettingsFragment">
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/ic_search"
app:showAsAction="collapseActionView|always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:layout_width="wrap_content" />
Add a filter() method to your custom Adapter.
private ArrayList<ToDo> arraylist = null, toDoArrayList;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
this.toDoArrayList = new ArrayList<ToDo>();
this.toDoArrayList.addAll(objects);
}
public void filter(String filterString) {
filterString = filterString.toLowerCase(Locale.getDefault());
arraylist.clear();
if (filterString.length() == 0) {
arraylist.addAll(toDoArrayList);
}
else {
for (ToDo toDO : toDoArrayList) {
if(toDO.getYourSearchValue().toLowerCase(Locale.getDefault()).contains(filterString)) {
arraylist.add(toDO);
}
}
}
notifyDataSetChanged();
}
You can implement Filterable interface in adapter and can do like this
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> implements Filterable {
static List<ToDo> todoResults;
static Context context;
List<ToDo>results;
ArrayList<ToDo> arraylist;
private List<String> mDefaultCheeses;
private ToDoListFilter listFilter;
private List<ToDo> mData;
private List<ToDo> originalData;
public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
this.todoResults = results;
arraylist = new ArrayList<ToDo>();
arraylist.addAll(todoResults);
}
public List<ChatListData> getData() {
return mData;
}
public void setData(List<ChatListData> mData) {
this.mData = mData;
if (originalData == null) {
originalData = mData;
}
}
#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 Filter getFilter() {
if (listFilter == null)
listFilter = new ToDoListFilter(this,originalData);
return listFilter;
}
#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);
}
}
private class ToDoListFilter extends Filter {
private final TodoRecyclerAdapter listAdapter;
private final List<ToDo> originalData;
private List<ToDo> filteredData;
public ToDoListFilter(TodoRecyclerAdapter listAdapter, List<ToDo> originalData) {
this.listAdapter = listAdapter;
this.originalData = originalData;
this.filteredData = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredData.clear();
final FilterResults results = new FilterResults();
Log.d("performFiltering: " , constraint.toString());
if (TextUtils.isEmpty(constraint.toString())) {
filteredData.addAll(originalData);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final ToDo user : originalData) {
// set condition for filter here
if (user.getToUserName().toLowerCase().contains(filterPattern)) {
filteredData.add(user);
}
}
}
results.values = filteredData;
results.count = filteredData.size();
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
//listAdapter.getData().clear();
listAdapter.setData((List<ToDo>) filterResults.values);
listAdapter.notifyDataSetChanged();
}
}
}
And to call this
listAdapter.getFilter().filter(query);
For more check here
Hope it will solve your problem...
I have tried below code :
I think it will work.
public class SearchAdapter extends RecyclerView.Adapter implements Filterable {
private ItemFilter itemFilter;
private ArrayList<CommonModel> arrayList;//filtered emoji collection
private ArrayList<CommonModel> fullList;//Full emoji collection
private Context context;
public SearchAdapter(final Context context, final ArrayList<CommonModel> arrayList) {
this.arrayList = arrayList;
this.fullList = arrayList;
this.context = context;
itemFilter = new ItemFilter();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_search, parent, false);
final ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(KeyboardEmojiSearchAdapter.ViewHolder holder, int position) {
final CommonModel commonModel = arrayList.get(position);
Glide.with(context).load(commonModel.getDisplayImage()).asBitmap().into(holder.iv);
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public Filter getFilter() {
return itemFilter;
}
/**
* Holder class to hold grid item
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private ImageView iv;
public ViewHolder(View view) {
super(view);
iv = (ImageView) view.findViewById(R.id.row_search_iv);
}
}
/**
* Filter class allows filtering by tags from Emoji collection
*/
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults results = new FilterResults();
final ArrayList<CommonModel> newFilteredList = new ArrayList<>();
if (constraint.toString().trim().length() > 0) {
final String filterString = constraint.toString().toLowerCase();
final int count = fullList.size();
for (int i = 0; i < count; i++) {
for (int j = 0; j < fullList.get(i).getTagList().size(); j++) {
if (fullList.get(i).getTagList().get(j).toLowerCase().startsWith(filterString)) {
newFilteredList.add(fullList.get(i));
break;
}
}
}
} else {
newFilteredList.addAll(fullList);
}
results.values = newFilteredList;
results.count = newFilteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (ArrayList<CommonModel>) results.values;
notifyDataSetChanged();
}
}
Please refer below code.
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
gridAdapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});