I am applying a delete function to my notes app, but when I delete something, it doesnt changes on the screen until I do some action that reloads it, like creating a new note, or accesing a note and the exiting it (even the one deleted). Only then, the deleted note will disappear, even though I clearly used the reload function. Here is my adapter, where I have the problem.
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteViewHolder> {
public static class NoteViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView nameTextView;
public NotesAdapter adapter = new NotesAdapter();
public NoteViewHolder(View view) {
super(view);
this.containerView = view.findViewById(R.id.note_row);
this.nameTextView = view.findViewById(R.id.note_row_name);
this.containerView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
final Note note = (Note) containerView.getTag();
PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.delete) {
Toast.makeText(view.getContext(), "Note deleted", Toast.LENGTH_SHORT).show();
MainActivity.database.noteDao().delete(note.id);
adapter.reload;
return true;
} else {
return false;
}
}
});
popupMenu.inflate(R.menu.delete_menu);
popupMenu.show();
return true;
}
});
this.containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Note note = (Note) containerView.getTag();
Intent intent = new Intent(v.getContext(), NoteActivity.class);
intent.putExtra("id", note.id);
intent.putExtra("content", note.content);
context.startActivity(intent);
}
});
}
}
private List<Note> notes = new ArrayList<>();
#Override
public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.note_row, parent, false);
return new NoteViewHolder(view);
}
#Override
public void onBindViewHolder(NoteViewHolder holder, int position) {
Note current = notes.get(position);
holder.containerView.setTag(current);
holder.nameTextView.setText(current.content);
}
#Override
public int getItemCount() {
return notes.size();
}
public void reload() {
notes = MainActivity.database.noteDao().getAll();
notifyDataSetChanged();
}
}
Please help me, I ve working on this for days now, and I am stuck at a simple problem
Reload data after the database has been updated. Invoke reload() after deleting a note:
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getItemId() == R.id.delete) {
Toast.makeText(view.getContext(), "Note deleted", Toast.LENGTH_SHORT).show();
MainActivity.database.noteDao().delete(note.id);
reload(); // reload data
return true;
} else {
return false;
}
}
});
Related
I want to filter recyclerView items, my code is working well in terms of displaying filtered items but when I am clicking on those items it's clicking on previous items though those items are not visible. I thought the problem is on item clickListener implementation but I have tried two recylcerview onitemClickListener implementation but both of them aren't working.
Can You Please Help? Thanks In Advance.
Here is the filter code in Recyclerview Adapter.
public void updateList(List<ProductInfo> list){
mProductList = list;
notifyDataSetChanged();
}
Here is the Clicklistener on Recyclerview in Activity.
mProductAdapter = new AdapterTest(mProductInfos, new AdapterTest.ClickListener(){
#Override
public void onPositionClicked(View v, int position) {
ProductInfo productInfo = mProductInfos.get(position);
Intent intent = new Intent(VegetableActivity.this, DescriptionActvity.class);
intent.putExtra(MainActivity.EXTRA_OBJECT, productInfo);
startActivity(intent);
}
#Override
public void onLongClicked(View v, int position) {
}
});
And This is the Adapter Class.
public class AdapterTest extends RecyclerView.Adapter<AdapterTest.MyviewHolder> {
private List<ProductInfo> mProductList;
private ClickListener listener;
public class MyviewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mProductName, mProductPrice, mProductRating;
private ImageView mProductImage;
private WeakReference<ClickListener> listenerRef;
public MyviewHolder(View itemView, ClickListener listener) {
super(itemView);
listenerRef = new WeakReference<>(listener);
mProductName = itemView.findViewById(R.id.product_name);
mProductPrice = itemView.findViewById(R.id.product_price);
//mProductRating = itemView.findViewById(R.id.product_rating);
mProductImage = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
// if(view.getId() == decreaseView.getId()){
// Toast.makeText(view.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
// }else {
// Toast.makeText(view.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
// }
listenerRef.get().onPositionClicked(view, getAdapterPosition());
}
#Override
public boolean onLongClick(View view) {
return false;
}
}
public AdapterTest(List<ProductInfo> productList, ClickListener listener){
mProductList = productList;
this.listener = listener;
}
#Override
public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.vegetable_layout, parent, false);
return new MyviewHolder(itemView, listener);
}
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
ProductInfo productInfo = mProductList.get(position);
holder.mProductName.setText(productInfo.getProductName());
holder.mProductPrice.setText(productInfo.getProductPrice());
//holder.mProductRating.setText(productInfo.getProductRating());
Picasso.get()
.load(productInfo.getProductImage())
.into(holder.mProductImage);
}
#Override
public int getItemCount() {
return mProductList.size();
}
public interface ClickListener {
void onPositionClicked(View v, int position);
void onLongClicked(View v, int position);
}
public void updateList(List<ProductInfo> list){
mProductList = list;
notifyDataSetChanged();
}
}
you can move below code segement to onCLick evenet of the recycle item
Intent intent = new Intent(VegetableActivity.this, DescriptionActvity.class);
intent.putExtra(MainActivity.EXTRA_OBJECT, productInfo);
startActivity(intent);
you donot need the onPositionClicked listener for that and you can remove ProductInfo productInfo = mProductInfos.get(position); as well. I have no clear idea about what u doing. but let say u want to nevigate to another page when u click on recycle item. u can add it like below
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
ProductInfo productInfo = mProductList.get(position);
holder.mProductName.setText(productInfo.getProductName());
holder.mProductPrice.setText(productInfo.getProductPrice());
//holder.mProductRating.setText(productInfo.getProductRating());
Picasso.get()
.load(productInfo.getProductImage())
.into(holder.mProductImage);
//new code - start here
holder.anyuielementInItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Do things you want
}
});
//
}
I have an activity with a RecyclerView and a button that is disabled at first. The elements of the RV are selectable, and I want the button to be enabled only after an element was selected. I tried to set addOnItemTouchListener on the recyclerview, the problem is that it is also called when scrolling through the list.
Here is my Adapter:
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
private ArrayList<ClusterItem> mListOfClusters;
private OnItemClickListener mListener;
//index
int row_index = -1; //Default no row chosen
public interface OnItemClickListener{
//delete
void onDeleteCluster(int position);
//edit
void onEditCluster(int position);
//select
void onClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){mListener = listener;}
public static class ClusterListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mClusterName;
public TextView mClusterMembers;
public ImageView mDeleteCluster;
public ImageView mEditCluster;
//This
private OnItemClickListener itemClickListener;
public void setItemClickListener(OnItemClickListener listener){
this.itemClickListener = listener;
}
public ClusterListViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mClusterName = itemView.findViewById(R.id.tv_clusters_name_cluster_list);
mClusterMembers = itemView.findViewById(R.id.tv_clusters_members_cluster_list);
mDeleteCluster = itemView.findViewById(R.id.iv_delete_cluster);
mEditCluster = itemView.findViewById(R.id.iv_edit_cluster);
mDeleteCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onDeleteCluster(position);
}
}
}
});
mEditCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onEditCluster(position);
}
}
}
});
//used for highlighting item
itemView.setOnClickListener(this);
}
//This
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
public CLusterListAdapter(ArrayList<ClusterItem> listOfClusters ){ mListOfClusters = listOfClusters;}
#NonNull
#Override
public ClusterListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chose_your_cluster_list_item, viewGroup, false);
ClusterListViewHolder clusterListViewHolder = new ClusterListViewHolder(view, mListener);
return clusterListViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ClusterListViewHolder clusterListViewHolder, int i) {
ClusterItem currentCluster = mListOfClusters.get(i);
clusterListViewHolder.mClusterName.setText(currentCluster.getClustersName());
clusterListViewHolder.mClusterMembers.setText(currentCluster.getClustersMembers());
clusterListViewHolder.mClusterMembers.setSelected(true);
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
SpTAGs.selectedClusterPosition = position;
}
});
//Set highlight color
if(row_index == i) {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#E64A19"));
}else {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}
#Override
public int getItemCount() {
return mListOfClusters.size();
}
}
And here is how I applied the addOnItemTouch
clusterRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
selectButton.setEnabled(true);
Log.v("MyTAG", "Touch");
return false;
}
#Override
public void onTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
});
Any idea how to obtain this? Thank you!
Have a callback from the Adapter to the activity. Enable your button there.
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
...
interface Listener {
void onItemClick(int position);
}
}
Invoke this on item click
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
listener.onItemClick(position); // notify the listener (activity) of the click
SpTAGs.selectedClusterPosition = position;
}
});
In activity:
clusterRecyclerView.addOnItemTouchListener( ... );
clusterRecyclerView.setListener((int position) -> {
// logic to enable button goes here
});
you don't need to use the addOnItemTouchListener here.
just create a methode inside the activity like this
public void VisibleButton(){
yourButton.setVisibility(View.VISIBLE);
/**....*/
}
and just call the methode
VisibleButton()
from your adapter,from where you want your button to be visible, just like this
((YourActivityName)your_ACtivity_Context).VisibleButton();
Hello I am trying to implement multi select in recycler view android for showing an icon when clicked on that particular view, I have tried the below code and is working fine for that particular position, however there are other several views that too are getting updated, so please check and let me know what am I missing
Here is my adapter code:
public class ContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
Context context;
ArrayList<String> alContactName, alContactEmail, alContactNumber;
ArrayList<Boolean> alFromLinkedIn;
int mergeFlag=0;
private static SparseBooleanArray selectedItems;
ArrayList<Integer> alSelectedPositions;
public ContactsAdapter(Context context, ArrayList<String> alContactName, ArrayList<String> alContactEmail, ArrayList<String> alContactNumber, ArrayList<Boolean> alisFromLinkedIn) {
//Include one more variable for checking type i.e linked in or normal contact
super();
this.context = context;
this.alContactName = alContactName;
this.alContactEmail = alContactEmail;
this.alContactNumber = alContactNumber;
this.alFromLinkedIn = alisFromLinkedIn;
alSelectedPositions=new ArrayList<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_merge_contact, parent, false);
return new ContactsHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alSelectedPositions.add(position);
notifyDataSetChanged();
}
});
if(alSelectedPositions.get(position)==position){
((ContactsHolder) holder).imgMerge.setVisibility(View.VISIBLE);
}
else {
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
check updated code. I have modified the #tahsinRupam code.
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(alSelectedPositions.size>0)
{
for(int i=0;i<a1SelectedPositions.size;i++)
{
//if you want to cleasr previous details of array
if(a1SelectedPositions.contains(position))
alSelectedPositions.remove(position);
else
alSelectedPositions.add(position);
}
}
else
{
alSelectedPositions.add(position);
notifyDataSetChanged();
}
});
//update the position on scroll
for(int i=0;i<a1SelectedPositions.size;i++)
{
if(alSelectedPositions.get(i)==position){
((ContactsHolder)holder).imgMerge.setVisibility(View.VISIBLE);
}
else {
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Recently I had to implement a multi select RecyclerView, below I attached a simplified code snippet for a clean way to implement multi-select feature in RecyclerView:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> implements IMultiSelectableList<Item> {
boolean selectionMode = false;
HashSet<Item> selectedItems;
ArrayList<Item> mItems;
public ItemAdapter(ArrayList<Item> Items) {
super();
selectedItems = new HashSet<>();
mItems = Items;
}
public void enterSelectionModeWithItem(int selectedItemPosition){
if(selectedItemPosition >= 0 && selectedItemPosition < mItems.size())
selectedItems.add(mItems.get(selectedItemPosition));
selectionMode = true;
notifyDataSetChanged();
}
public void clearSelectionMode() {
selectionMode = false;
selectedItems.clear();
notifyDataSetChanged();
}
public class ItemHolder extends RecyclerView.ViewHolder{
ImageView mImage;
public ItemHolder(View itemView) {
super(itemView);
mImage = itemView.findViewById(R.id.image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if(!selectionMode){
int selectedPosition = getAdapterPosition();
Item selectedItem = mItems.get(selectedPosition);
enterSelectionModeWithItem(selectedItem);
return true;
}
return false;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectedPosition = getAdapterPosition();
Item selectedItem = mItems.get(selectedPosition);
//Capture Clicks in Selection Mode
if(selectionMode){
if(selectedItems.contains(selectedItem)){
selectedItems.remove(selectedItem);
mImage.setImageResource(R.drawable.ic_checkbox_blank_circle_outline_grey600_48dp);
} else {
selectedItems.add(selectedItem);
mImage.setImageResource(R.drawable.ic_checkbox_marked_circle_grey600_48dp);
}
}
}
});
}
public void setupView(Item item){
if(selectionMode){
if(selectedItems.contains(item)){
mImage.setImageResource(R.drawable.ic_checkbox_marked_circle_grey600_48dp);
} else {
mImage.setImageResource(R.drawable.ic_checkbox_blank_circle_outline_grey600_48dp);
}
}
}
#Override
public ItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_item, parent, false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemAdapter.ItemHolder holder, int position) {
holder.setupView(mItems.get(position));
}
#Override
public int getItemCount() {
return mItems != null ? mItems.size() : 0;
}
}
, I use an image to show selection like Gmail app but feel free to use whatever works for you (background color, font style, etc).
P.S: I designed a callback interface for a simple selection interactions, if it helps I can attach it too! Cheers!
You've to do some specific things:
Initialize an int type array (type can be different) and assign 0 value to all it's elements.
int[] selectedPos = null;
public ContactsAdapter(Context context, ArrayList<String> alContactName, ArrayList<String> alContactEmail, ArrayList<String> alContactNumber, ArrayList<Boolean> alisFromLinkedIn) {
//Include one more variable for checking type i.e linked in or normal contact
super();
this.context = context;
this.alContactName = alContactName;
this.alContactEmail = alContactEmail;
this.alContactNumber = alContactNumber;
this.alFromLinkedIn = alisFromLinkedIn;
alSelectedPositions=new ArrayList<>();
for(int i = 0 ; i < alContactName.size() ; i++)
selectedPos[i] = 0;
}
Store the selected positions in selectedPos.
Then, check if the position is selected and set visibility accordingly:
In onBindViewHolder() add the following code:
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPos[position] = 1;
notifyDataSetChanged();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// Checking if the position was selected
if(selectedPos[position] == 1)
((ContactsHolder) holder).imgMerge.setVisibility(View.VISIBLE);
else
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
I have resolved my issue here is the code if it could help someone:
#Override
public ContactsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_merge_contact, parent, false);
final ContactsHolder holder = new ContactsHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getAdapterPosition() != RecyclerView.NO_POSITION) {
mSelectedItemPosition = holder.getAdapterPosition();
//notifyItemChanged(holder.getAdapterPosition());
notifyDataSetChanged();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(ContactsHolder holder, int position) {
try {
if (mSelectedItemPosition == position) {
if (mergeFlag != 1) {
holder.imgMerge.setVisibility(View.VISIBLE);
mergeFlag = 1;
selectdParentId = contactsModels.get(position).alContactIdList;
} else{
//holder.relDone.setVisibility(View.GONE);
if (!selectdParentId.equals(contactsModels.get(position).alContactIdList)) {
holder.relDone.setVisibility(View.VISIBLE);
alChildId.add(contactsModels.get(position).alContactIdList);
} else {
holder.imgMerge.setVisibility(View.VISIBLE);
}
}
} else {
holder.imgMerge.setVisibility(View.GONE);
holder.relDone.setVisibility(View.GONE);
}
}
I have a RecyclerView with search bar in my android app. When I search in it and click on an item, it shows wrong data.
I know why it happens but I don't know how to fix it. I have tried many things but still I have the problem.
Here is the code of my Adapter.
RecyclerView.Adapter<hisAdapter.hisViewHolder> {
private ArrayList<hisItem> mhislist;
public onItemClickListener mListener;
public interface onItemClickListener {
void onItemClick(int position);
}
public void setOnitemClickLIstener(onItemClickListener lIstener) {
mListener = lIstener;
}
public class hisViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView1;
public TextView mTextView2;
public TextView card_num;
public hisViewHolder(View itemView) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.textView1);
mTextView2 = itemView.findViewById(R.id.textView2);
card_num = itemView.findViewById(R.id.number);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
}
}
public hisAdapter(ArrayList<hisItem> hisList){
mhislist = hisList;
}
#Override
public hisViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.his_item, parent, false);
hisViewHolder hvh = new hisViewHolder(v);
return hvh;
}
#Override
public void onBindViewHolder(hisViewHolder holder, int position) {
hisItem currentItem = mhislist.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
holder.card_num.setText(currentItem.getText3());
}
#Override
public int getItemCount() {
return mhislist.size();
}
public void filterList(ArrayList<hisItem> filteredList){
mhislist = filteredList;
notifyDataSetChanged();
}
}
This is the MainActivity where I have a search functionality code and click handler.
editTextt.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) { }
#Override
public void afterTextChanged(Editable editable) {
filter(editable.toString());
}
});
}
public void filter(String text) {
ArrayList<hisItem> filteredList = new ArrayList<>();
for (hisItem item : hisList) {
if (item.getText1().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, singleActivity.class);
hisItem clickeditem = hisList.get(position);
String pos = String.valueOf(position);
intent.putExtra(CARD_NUM ,pos );
intent.putExtra(HEAD_LINE,clickeditem.getText1());
intent.putExtra(REAL_NUM,clickeditem.getText3());
startActivity(intent);
}
Please let me know if there's anything I need to add in my question. I am available to provide those. Thanks.
You can solve the issue in two different ways. You might consider changing the function in your MainActivity. Because what you are doing in your onItemClick function is wrong. You are getting the item from the hisList when some items from this hisList are already filtered out. So you need to get the items from your filteredList in this case. This can be easily achieved by declaring the filteredList as a global variable in your MainActivity.
// Declaring the filteredList as a public variable that can be accessed from anywhere in this class.
public ArrayList<String> filteredList = new ArrayList<>();
#Override
public void onItemClick(int position) {
Intent intent = new Intent(this, singleActivity.class);
// Get the item from the filteredList which is the updated one.
hisItem clickeditem = filteredList.get(position);
String pos = String.valueOf(position);
intent.putExtra(CARD_NUM ,pos );
intent.putExtra(HEAD_LINE,clickeditem.getText1());
intent.putExtra(REAL_NUM,clickeditem.getText3());
startActivity(intent);
}
However, the second way is to integrate the onClick behaviour in your adapter. I prefer this as this is simple and this is not prone to error. It will be always handling the list passed to the adapter. So there is no other headache.
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Intent intent = new Intent(context, singleActivity.class);
hisItem clickeditem = mhislist.get(position);
String pos = String.valueOf(position);
intent.putExtra("CARD_NUMBER", pos);
intent.putExtra("HEAD_LINE", clickeditem.getText1());
intent.putExtra("REAL_NUMBER", clickeditem.getText3());
startActivity(intent);
}
});
Hope that helps.
Use this code it will solve your problem definitely!!
private ArrayList<Employee> filteredList = new ArrayList<Employee>();
private void filter(String text) {
filteredList.clear();
for (Employee item : mEmployeeList) {
if (item.getVehicle_number().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
myadapter.filterList(filteredList);
}
#Override
public void onItemClick(int position) {
Intent ediIntent = new Intent(this, Edit_Activity.class);
if(filteredList.size() > 0) {
Employee clickedItem = filteredList.get(position);
} else {
Employee clickedItem = mEmployeeList.get(position);
}
...
}
I have a list of tasks in recyclerview. Each task item has a check box to show if the task is completed or pending.
Now I want to show two sections in my list. One for checked items and another for unchecked items.
I have gone through this library to add the sections.
https://github.com/afollestad/sectioned-recyclerview
But how can I divide the items in list on the basis of they are checked or not?
Also I want to add the task into another section if checked or unchecked , i.e onClick.
If task is unchecked, and if I check it, it should get added to the completed section and vise versa.
I have a recyclerview now with swipe layout. Following is the adapter.
adapetr:
public class IAdapter extends RecyclerSwipeAdapter<IAdapter.ItemViewHolder> , SectionedRecyclerViewAdapter<IAdapter.ItemViewHolder> {
public ArrayList<Task> items;
Context conext;
public int _mId;
List<Task> itemsPendingRemoval = new ArrayList<>();
public IAdapter(Context context, ArrayList<Task> item) {
this.conext=context;
this.items=item;
}
#Override
public int getSectionCount() {
return 2;
}
#Override
public int getItemCount(int section) {
return items.size();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
Task task;
CheckBox cb;
SwipeLayout swipeLayout;
TaskTableHelper taskTableHelper;
ItemViewHolder(final View itemView) {
super(itemView);
taskTableHelper= new TaskTableHelper(itemView.getContext());
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
cb = (CheckBox) itemView.findViewById(R.id.checkbox);
}
}
#Override
public void onBindViewHolder(final ItemViewHolder itemViewHolder,final int i) {
itemViewHolder.cb.setText(items.get(i).getTitle());
itemViewHolder.task = items.get(i);
int taskId = itemViewHolder.task.getId();
itemViewHolder.task = itemViewHolder.taskTableHelper.getTask(taskId);
int status = itemViewHolder.task.getStatus();
if(status == 0)
{
itemViewHolder.cb.setTextColor(Color.WHITE);
}
else {
itemViewHolder.cb.setChecked(true);
itemViewHolder.cb.setTextColor(Color.parseColor("#B0BEC5"));
}
itemViewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
itemViewHolder.cb.setTextColor(Color.parseColor("#B0BEC5"));
itemViewHolder.task.setStatus(1);
itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);
}
else
{
itemViewHolder.cb.setTextColor(Color.WHITE);
itemViewHolder.task.setStatus(0);
itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);
}
}
});
final Task item = items.get(i);
itemViewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right,itemViewHolder.swipeLayout.findViewById(R.id.bottom_wrapper_2));
itemViewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
itemViewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(conext, "DoubleClick", Toast.LENGTH_SHORT).show();
}
});
itemViewHolder.swipeLayout.findViewById(R.id.trash2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(itemViewHolder.swipeLayout);
items.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, items.size());
mItemManger.closeAllItems();
itemViewHolder.taskTableHelper.deleteTask(item);
_mId = item.getAlertId();
cancelNotification();
Toast.makeText(view.getContext(), "Deleted " + itemViewHolder.cb.getText().toString() + "!", Toast.LENGTH_SHORT).show();
}
});
itemViewHolder.swipeLayout.findViewById(R.id.done).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemViewHolder.task.setStatus(1);
itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);
itemViewHolder.cb.setChecked(true);
Toast.makeText(conext, "Task Completed.", Toast.LENGTH_SHORT).show();
}
});
itemViewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean mEditMode;
int id = item.getId();
int priority = item.getTaskPriority();
String title = item.getTitle();
String alertDate = item.getAlertDate();
String alertTime = item.getAlertTime();
String dueDate = item.getDueDate();
String dueTime = item.getDueTime();
_mId = item.getAlertId();
int listId = item.getList();
mEditMode = true;
Intent i = new Intent(conext, AddTaskActivity.class);
i.putExtra("taskId", id);
i.putExtra("taskTitle", title);
i.putExtra("taskPriority", priority);
i.putExtra("taskAlertTime", alertTime);
i.putExtra("taskAlertDate", alertDate);
i.putExtra("taskDueDate", dueDate);
i.putExtra("taskDueTime", dueTime);
i.putExtra("taskListId", listId);
i.putExtra("EditMode", mEditMode);
i.putExtra("AlertId",_mId);
conext.startActivity(i);
}
});
mItemManger.bindView(itemViewHolder.itemView, i);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup,int position) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ItemViewHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void remove(int position) {
Task item = items.get(position);
if (itemsPendingRemoval.contains(item)) {
itemsPendingRemoval.remove(item);
}
if (items.contains(item)) {
items.remove(position);
notifyItemRemoved(position);
}
}
public void cancelNotification()
{
AlarmManager alarmManager = (AlarmManager)conext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(conext, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(conext,_mId, intent, 0);
alarmManager.cancel(pendingIntent);
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
}
Can anyone help please?
Thank you..
You can add "sections" to your recyclerview with the library SectionedRecyclerViewAdapter.
First create a Section class to group your tasks:
class TaskSection extends StatelessSection {
String title;
List<Task> list;
public TaskSection(String title, List<Task> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // number of items of this section
}
public int addTask(Task task) {
return list.add(task;
}
public int removeTask(Task task) {
return list.remove(task;
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position).getTitle());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with the list of data
TaskSection compSection = new TaskSection("Completed", compList);
TaskSection pendSection = new TaskSection("Pending", pendList);
// Add your Sections to the adapter
sectionAdapter.addSection(compSection);
sectionAdapter.addSection(pendSection);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
Now if you want to send a task from "Pending" section to "Completed":
pendSection.removeTask(task);
compSection.addTask(task);
sectionAdapter.notifyDataSetChanged();
Regarding to the SwipeLayout, don't extend RecyclerSwipeAdapter, extend SectionedRecyclerViewAdapter and implement the SwipeLayout in ItemViewHolder / onBindItemViewHolder as you have done.