I am able to get data in firebase collection but it does not query that data in recycler view. Recyclerview does not showing anything
This is the comment_list class.
public class comment_list {
public comment_list(String comments) {
this.comments = comments;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
String comments;
}
This is comment_adapter class
public class comment_adapter extends FirestoreRecyclerAdapter<comment_list, comment_adapter.comment_holder> {
public comment_adapter(#NonNull FirestoreRecyclerOptions<comment_list> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull comment_holder holder, int position, #NonNull comment_list model) {
holder.commment_on_post.setText(model.getComments());
}
#NonNull
#Override
public comment_holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_recycler_dsign, parent, false);
return new comment_holder(v);
}
public class comment_holder extends RecyclerView.ViewHolder{
TextView commment_on_post;
public comment_holder(#NonNull View itemView) {
super(itemView);
commment_on_post = itemView.findViewById(R.id.commenttextview);
}
}
This is Comments class. In this I am able to get data in firebase collection but it is not query that data in recycler view.
public class Comments extends AppCompatActivity {
ImageView profileimage;
EditText addcommenttext;
TextView postcommenttext;
FirebaseFirestore db;
RecyclerView comment_recycler_view;
comment_adapter adaptercomment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
profileimage = findViewById(R.id.Addcommentprofileimage);
addcommenttext = findViewById(R.id.addcommenttext);
postcommenttext = findViewById(R.id.postcomment);
comment_recycler_view = findViewById(R.id.commentsrecycler);
postcommenttext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addcommenttext.equals("")) {
Toast.makeText(Comments.this, "Comment can't be empty", Toast.LENGTH_SHORT).show();
} else {
String commentText = addcommenttext.getText().toString();
CollectionReference commentref = FirebaseFirestore.getInstance() .collection("CommentDetails");
commentref.add(new comment_list(commentText));
FirebaseFirestore fbfs = FirebaseFirestore.getInstance();
CollectionReference commentrefs = fbfs.collection("CommentDetails");
Query query = commentrefs;
FirestoreRecyclerOptions<comment_list> options = new FirestoreRecyclerOptions.Builder<comment_list>()
.setQuery(query, comment_list.class)
.build();
adaptercomment = new comment_adapter(options);
comment_recycler_view.setHasFixedSize(true);
comment_recycler_view.setLayoutManager(new LinearLayoutManager(getApplication()));
comment_recycler_view.setAdapter(adaptercomment);
finish();
Toast.makeText(Comments.this, "Commented", Toast.LENGTH_SHORT).show();
}
}
});
}
First of all, let's reconfigure your Comments activity class. It would be recommended to initialise the recycle adapter in your onCreate method and not in the overridden onClick method. With the current set up, a new comment_adapter is initialised every time the onClick listener is triggered. It's best that we set-up only one. Here's how things look after the changes (I've added comments for clarity):
NOTE: I have renamed classes, variables and methods to use java and android conventions for clarity. Learning these will help you a lot in being able to read others code and save you a lot of headaches with your own code.
public class CommentsActivity extends AppCompatActivity {
FirebaseFirestore db;
CommentAdapter commentAdapter;
ImageView profileImageView;
EditText commentEditText;
RecyclerView commentRecyclerView;
Button addCommentButton; // Replaces the text view you are using
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
profileImageView = findViewById(R.id.add_comment_profile_image);
commentEditText = findViewById(R.id.comment_edit_text);
addCommentButton = findViewById(R.id.add_comment_button);
commentRecyclerView = findViewById(R.id.comments_recycle_view);
// Enables firestore debugging which will help a lot when trying to troubleshoot
FirebaseFirestore.setLoggingEnabled(true);
// We are now setting up our query directly within the OnCreate method.
db = FirebaseFirestore.getInstance();
Query query = db.collection("CommentDetails").orderBy("timestamp").limit(50);
FirestoreRecyclerOptions<Comment> options = new FirestoreRecyclerOptions.Builder<Comment>()
.setQuery(query, Comment.class)
.build();
// Setting up the recycle adapter in onCreate
commentAdapter = new CommentAdapter(options);
commentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
commentRecyclerView.setAdapter(commentAdapter);
// Set up your onClickListener just as before.
addCommentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Note that the previous null check is unsuccessful. Previously, the object instance
// was being checked, and not the contents of the edit text. This resolves that issue. (:
if (commentEditText.toString().isEmpty()) {
Toast.makeText(CommentsActivity.this, "Comment can't be empty", Toast.LENGTH_SHORT).show();
} else {
String commentText = commentEditText.getText().toString();
CollectionReference commentColRef = FirebaseFirestore.getInstance().collection("CommentDetails");
commentColRef.add(new Comment(commentText));
Toast.makeText(CommentsActivity.this, "Commented", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
commentAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
commentAdapter.stopListening();
}
}
You will notice the addition of two new methods: onStart and onStop. Within these methods we start and stop the query listeners attached to the FirestoreRecyclerAdapter. It will be really helpful to refer to the FirebaseUI for Cloud Firestore read-me.
It is important to note in the code above I also renamed your data model from comment_list to Comment. The reason for this, is that an instance of this class only stores the state of one comment. It does not store a list of comments. I think it might cause confusion when you are trying to debug your code. In the case of using FirebaseUI, the actual list of comments (the comments list) which is bound to your recycle view is built for you by the FirebaseUI code, in the form of an array of Comment class instances.
In order to understand clearly how this is done, it might be useful to spend a couple of hours implementing a simple recycle view and adapter that is not connected to Firestore. That way a greater understanding as to how FirebaseUI is doing things can be developed. There are docs on that here.
Finally - here is a replacement to the comment_list class:
public class Comment {
String comment;
#ServerTimestamp Date timestamp;
// A zero argument constructor is required by firestore.
public Comment() {
}
public Comment(String comment) {
this.comment = comment;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
The only difference here is there is a zero-args (no argument) constructor, which is required by firestore.
A word to the wise - I haven't seen your view model item layout (comment_recycler_dsign), but just check that the root layout does not have a height of "match_parent". This is a common mistake. It is a good idea to check this first if you see only one recycle item being rendered.
Place a listener
fire base will automatically call once the upload is complete
firestore.collection("").add(Any()).addOnCompleteListener {
// do all your work here
}
I am new to android development, in fact its my first application. I have created a dynamic layout in my project based on Json. Each object includes an "id" key and some more string keys. every object in my json should be transformed to a cardview inside a recylcerview and each cardview has a button.
My problem is handling these dynamic buttons. Is it possible to determine which button was clicked?
View.id is an integer, and you shouldn't set arbitrary values to it if the View is generated dinamically, what you can use though is View.tag. So you can assign the id defined in the JSON to tag and then check the tag value when the View is clicked. E.g.
val view1 = View(context)
view1.tag = "id from JSON 1"
view1.setOnClickListener(this::onViewClicked)
val view2 = View(context)
view2.tag = "id from JSON 2"
view2.setOnClickListener(this::onViewClicked)
// ...
private fun onViewClicked(view: View){
val jsonId = view.tag as? String
// ...
}
If your min sdk level at least 17, another option would be to generate ids dinamically with View.generateViewId() and store them in a Map together with your JSON ids
Use a Tag to differentiate the buttons. Add OnClickListener to all Button and set different String tag to button.
button.setOnClickListener(this);
Add ClickListener
#Override
public void onClick(View view){
String tag = (String)view.getTag();
if(tag.equals(tag1)){
// action here
}
//.......
.....
}
Yeah pretty straight, all you have to do is to give them a unique id
I assume you must have a JSON array for dynamic buttons creation.
sample code
public Button createButton(Context context,String text,int buttonNo){
//here set the properties
Button bt = new Button(context);
bt.setText(text);
bt.setId(buttonNo);
bt.setTag(buttonNo);
bt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//handle the button click, unique id , you can use to differentiate
int id = view.getId();
}
});
return bt;
}
call this above method in for loop or as many times you want to create.
you can also set a tag as mentioned above to store more information.
Finally I put the OnClickListener in onBindViewHolder event inside my customAdapter class as below:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> implements View.OnClickListener {
private Context context;
private List<MyData> my_data;
public CustomAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.match_date.setText(my_data.get(position).getMatch_date());
holder.home_name.setText(my_data.get(position).getHome_name());
holder.away_name.setText(my_data.get(position).getAway_name());
holder.button.setId(my_data.get(position).getId());
holder.button.setTag(my_data.get(position).getStringId());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int intHomeGoals = Integer.parseInt(holder.edtHomeGoals.getText().toString());
int intAwayGoals = Integer.parseInt(holder.edtAwayGoals.getText().toString());
if (intHomeGoals == intAwayGoals)
{
Toast.makeText(context, "00000", Toast.LENGTH_SHORT).show();
}
}
});
Glide.with(context).load(my_data.get(position).getHome_logo()).into(holder.home_logo);
Glide.with(context).load(my_data.get(position).getAway_logo()).into(holder.away_logo);
}
I need to call a new activity, when a button inside one of my recyclerview row elements is called. Each row item in the list contains 4 buttons, one of which needs to open a new activity which will be used to edit the data in that row.
Here is the code for my button so far:
public void onBindViewHolder(CounterLayoutAdapter.ViewHolder holder, final
int position) {
final Counter counter = counterList.get(position);
//counter is a class which holds the data that will be displayed on one
//row
String comment = counter.getComment();
String name = counter.getCounterName();
int number = counter.getCurrentValue();
//LocalDate modifyDate = counter.getLastModifyDate();
Button up = holder.itemView.findViewById(R.id.buttonUp);
Button down = holder.itemView.findViewById(R.id.buttonDown);
Button reset = holder.itemView.findViewById(R.id.buttonReset);
Button edit = holder.itemView.findViewById(R.id.buttonEdit);
Button delete = holder.itemView.findViewById(R.id.buttonDelete);
// code for 4 other buttons goes here
//
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
Since I need the activity that I open to return user inputted data for me, I am using startActivityForResult. However, as far as I can tell, this will only work inside an actual activity class.
So then I tried passing the mainactivity context to my CounterLayoutAdapter class, where all of my button code is. However, the OnBindViewHolder method still cannot access it there. So I tried to pass the context to OnBindViewHolder, but that doesn't work either, as it won't override the abstract class if i do that..
So, how on earth can I call a new activity here?
Alternatively, if there is some other way to get user input into 4 fields and return that input back to the adapter, without calling an activity, that would work as well.
EDIT: viewholder and layout inflation
public static class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
private TextView name;
private TextView comment;
private TextView number;
//private TextView date;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
comment = itemView.findViewById(R.id.textComment);
name = itemView.findViewById(R.id.textName);
number = itemView.findViewById(R.id.editTextNum);
//date = itemView.findViewById(R.id.textDate);
}
#Override
public void onClick(View view) {}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView =
LayoutInflater.from(parent.getContext()).inflate(R.layout
.row_layout, parent, false);
return new ViewHolder(inflatedView);
}
You can call startActivityForResult() in adapter class.
Get context in adapter like Context context=holder.up.getContext();
then in your button's OnClickListener do this.
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,ActivityYouWantToStart.class);
//Pass any extras if you want to.
((Activity)context).startActivityForResult(intent,REQUEST_CODE);
}
});
Then in your activity (which contain this recyclerView) override onActivityResult like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {//same REQUEST_CODE you used in adapter
if (resultCode == RESULT_OK) {
//Do your thing and get the data you want.
adapter.onDataReady(Data data);//where adapter is your recycler adapter,
//and data is whatever data you want to pass to adapter
//(Data you got from the activityResult, do not confuse it with onActivityResult's parameter 'Intent data')
}
}
}
Finally in your Recycler Adapter class, define onDataReady() function like
public void onDataReady(Data data){
//Update RecyclerView with new data
}
Hope this helps. I once did this, and it works for me. Let me know if you have any problem.
As you see , you do not have to findViewById in onBindViewHolder.
public void onBindViewHolder(CounterLayoutAdapter.ViewHolder holder, final
int position) {
final Counter counter = counterList.get(position);
//counter is a class which holds the data that will be displayed on one
//row
String comment = counter.getComment();
String name = counter.getCounterName();
int number = counter.getCurrentValue();
//LocalDate modifyDate = counter.getLastModifyDate();
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
Then you should init edit in ViewHolder constructor.
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
comment = itemView.findViewById(R.id.textComment);
name = itemView.findViewById(R.id.textName);
number = itemView.findViewById(R.id.editTextNum);
//date = itemView.findViewById(R.id.textDate);
// init four button
edit = itemView.findViewById(R.id.buttonEdit)
}
I'm currently following this tutorial to implement a shared element transition between view (cards) in RecyclerView and activity but I'm not sure how can I do it since I'm using an onClickListener on MyRecyclerAdapter class to start a new activity.
Just new in development, hope you can help me about it.
MyRecyclerAdapter.java
public class MyRecyclerAdapter extends RecyclerView.Adapter<PaletteViewHolder> {
private Context context;
private List<Palette> palettes;
public MyRecyclerAdapter(Context context, List<Palette> palettes) {
this.palettes = new ArrayList<Palette>();
this.palettes.addAll(palettes);
this.context = context;
}
#Override
public PaletteViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_view, viewGroup, false);
itemView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ScrollingActivity.class);
intent.putExtra("P25", "Longanissa");
context.startActivity(intent);
}
});
return new PaletteViewHolder(itemView);
}
#Override
public void onBindViewHolder(PaletteViewHolder paletteViewHolder, int i) {
Palette palette = palettes.get(i);
paletteViewHolder.titleText.setText(palette.getName());
paletteViewHolder.contentText.setText(palette.getHexValue());
paletteViewHolder.card.setCardBackgroundColor(palette.getIntValue());
}
#Override
public int getItemCount() {
return palettes.size();
}
animateIntent method:
public void animateIntent(View view) {
// Ordinary Intent for launching a new activity
Intent intent = new Intent(this, YourSecondActivity.class);
// Get the transition name from the string
String transitionName = getString(R.string.transition_string);
// Define the view that the animation will start from
View viewStart = findViewById(R.id.card_view);
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(this,
viewStart, // Starting view
transitionName // The String
);
//Start the Intent
ActivityCompat.startActivity(this, intent, options.toBundle());
You need to set the transition name of the view inside the onBindViewHolder. It needs to be different of the others viewHolder so get a way to make it different and unique (using palette.getName() if palette names are unique for example or use i).
Then you need to start the activity inside on click using the provided view:
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(context, v, v.getTransitionName());
context.startActivity(intent, options.toBundle());
I don't understand why you need animateIntent method. Hope it still helps
I have a RecyclerView with an TextView text box and a cross button ImageView. I have a button outside of the recyclerview that makes the cross button ImageView visible / gone.
I'm looking to remove an item from the recylerview, when that items cross button ImageView is pressed.
My adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener {
private ArrayList<String> mDataset;
private static Context sContext;
public MyAdapter(Context context, ArrayList<String> myDataset) {
mDataset = myDataset;
sContext = context;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false);
ViewHolder holder = new ViewHolder(v);
holder.mNameTextView.setOnClickListener(MyAdapter.this);
holder.mNameTextView.setOnLongClickListener(MyAdapter.this);
holder.mNameTextView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mNameTextView.setText(mDataset.get(position));
}
#Override
public int getItemCount() {
return mDataset.size();
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
Toast.makeText(sContext, holder.mNameTextView.getText(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onLongClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
mDataset.remove(holder.getPosition());
notifyDataSetChanged();
Toast.makeText(sContext, "Item " + holder.mNameTextView.getText() + " has been removed from list",
Toast.LENGTH_SHORT).show();
}
return false;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mNumberRowTextView;
public TextView mNameTextView;
public ViewHolder(View v) {
super(v);
mNameTextView = (TextView) v.findViewById(R.id.nameTextView);
}
}
}
My layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:id="#+id/layout">
<TextView
android:id="#+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
android:background="#drawable/greyline"/>
<ImageView
android:id="#+id/crossButton"
android:layout_width="16dp"
android:layout_height="16dp"
android:visibility="gone"
android:layout_marginLeft="50dp"
android:src="#drawable/cross" />
</LinearLayout>
How can I get something like an onClick working for my crossButton ImageView? Is there a better way? Maybe changing the whole item onclick into a remove the item? The recyclerview shows a list of locations that need to be edited. Any technical advice or comments / suggestions on best implementation would be hugely appreciated.
I have done something similar.
In your MyAdapter:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView mCardView;
public TextView mTextViewTitle;
public TextView mTextViewContent;
public ImageView mImageViewContentPic;
public ImageView imgViewRemoveIcon;
public ViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextViewTitle = (TextView) v.findViewById(R.id.item_title);
mTextViewContent = (TextView) v.findViewById(R.id.item_content);
mImageViewContentPic = (ImageView) v.findViewById(R.id.item_content_pic);
//......
imgViewRemoveIcon = (ImageView) v.findViewById(R.id.remove_icon);
mTextViewContent.setOnClickListener(this);
imgViewRemoveIcon.setOnClickListener(this);
v.setOnClickListener(this);
mTextViewContent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(view, getPosition());
}
return false;
}
});
}
#Override
public void onClick(View v) {
//Log.d("View: ", v.toString());
//Toast.makeText(v.getContext(), mTextViewTitle.getText() + " position = " + getPosition(), Toast.LENGTH_SHORT).show();
if(v.equals(imgViewRemoveIcon)){
removeAt(getPosition());
}else if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
Edit:
getPosition() is deprecated now, use getAdapterPosition() instead.
first of all, item should be removed from the list!
mDataSet.remove(getAdapterPosition());
then:
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(), mDataSet.size()-getAdapterPosition());
if still item not removed use this magic method :)
private void deleteItem(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
holder.itemView.setVisibility(View.GONE);
}
Kotlin version
private fun deleteItem(position: Int) {
mDataSet.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, mDataSet.size)
holder.itemView.visibility = View.GONE
}
The Problem
RecyclerView was built to display data in an efficient and responsive manner.
Usually you have a dataset which is passed to your adapter and is looped through to display your data.
Here your dataset is:
private ArrayList<String> mDataset;
The point is that RecyclerView is not connected to your dataset, and therefore is unaware of your dataset changes.
It just reads data once and displays it through your ViewHolder, but a change to your dataset will not propagate to your UI.
This means that whenever you make a deletion/addition on your data list, those changes won't be reflected to your RecyclerView directly. (i.e. you remove the item at index 5, but the 6th element remains in your recycler view).
A (old school) solution
RecyclerView exposes some methods for you to communicate your dataset changes, reflecting those changes directly on your list items.
The standard Android APIs allow you to bind the process of data removal (for the purpose of the question) with the process of View removal.
The methods we are talking about are:
notifyItemChanged(index: Int)
notifyItemInserted(index: Int)
notifyItemRemoved(index: Int)
notifyItemRangeChanged(startPosition: Int, itemCount: Int)
notifyItemRangeInserted(startPosition: Int, itemCount: Int)
notifyItemRangeRemoved(startPosition: Int, itemCount: Int)
A Complete (old school) Solution
If you don't properly specify what happens on each addition, change or removal of items, RecyclerView list items are animated unresponsively because of a lack of information about how to move the different views around the list.
The following code will allow RecyclerView to precisely play the animation with regards to the view that is being removed (And as a side note, it fixes any IndexOutOfBoundExceptions, marked by the stacktrace as "data inconsistency").
void remove(position: Int) {
dataset.removeAt(position)
notifyItemChanged(position)
notifyItemRangeRemoved(position, 1)
}
Under the hood, if we look into RecyclerView we can find documentation explaining that the second parameter we pass to notifyItemRangeRemoved is the number of items that are removed from the dataset, not the total number of items (As wrongly reported in some others information sources).
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* #param positionStart Previous position of the first item that was removed
* #param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
Open source solutions
You can let a library like FastAdapter, Epoxy or Groupie take care of the business, and even use an observable recycler view with data binding.
New ListAdapter
Google recently introduced a new way of writing the recycler view adapter, which works really well and supports reactive data.
It is a new approach and requires a bit of refactoring, but it is 100% worth switching to it, as it makes everything smoother.
here is the documentation, and here a medium article explaining it
Here are some visual supplemental examples. See my fuller answer for examples of adding and removing a range.
Add single item
Add "Pig" at index 2.
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
Remove single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
Possibly a duplicate answer but quite useful for me. You can implement the method given below in RecyclerView.Adapter<RecyclerView.ViewHolder>
and can use this method as per your requirements, I hope it will work for you
public void removeItem(#NonNull Object object) {
mDataSetList.remove(object);
notifyDataSetChanged();
}
I tried all the above answers, but inserting or removing items to recyclerview causes problem with the position in the dataSet. Ended up using delete(getAdapterPosition()); inside the viewHolder which worked great at finding the position of items.
The problem I had was I was removing an item from the list that was no longer associated with the adapter to make sure you are modifying the correct adapter you can implement a method like this in your adapter:
public void removeItemAtPosition(int position) {
items.remove(position);
}
And call it in your fragment or activity like this:
adapter.removeItemAtPosition(position);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<cardview_widgets> list;
public MyAdapter(Context context, List<cardview_widgets> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(this.context).inflate(R.layout.fragment1_one_item,
viewGroup, false);
return new MyViewHolder(view);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtValue;
TextView txtCategory;
ImageView imgInorEx;
ImageView imgCategory;
TextView txtDate;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txtValue= itemView.findViewById(R.id.id_values);
txtCategory= itemView.findViewById(R.id.id_category);
imgInorEx= itemView.findViewById(R.id.id_inorex);
imgCategory= itemView.findViewById(R.id.id_imgcategory);
txtDate= itemView.findViewById(R.id.id_date);
}
}
#NonNull
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.txtValue.setText(String.valueOf(list.get(i).getValuee()));
myViewHolder.txtCategory.setText(list.get(i).getCategory());
myViewHolder.imgInorEx.setBackgroundColor(list.get(i).getImg_inorex());
myViewHolder.imgCategory.setImageResource(list.get(i).getImg_category());
myViewHolder.txtDate.setText(list.get(i).getDate());
myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
list.remove(myViewHolder.getAdapterPosition());
notifyDataSetChanged();
return false;
}
});
}
#Override
public int getItemCount() {
return list.size();
}}
i hope this help you.
if you want to remove item you should do this:
first remove item:
phones.remove(position);
in next step you should notify your recycler adapter that you remove an item by this code:
notifyItemRemoved(position);
notifyItemRangeChanged(position, phones.size());
but if you change an item do this:
first change a parameter of your object like this:
Service s = services.get(position);
s.done = "Cancel service";
services.set(position,s);
or new it like this :
Service s = new Service();
services.set(position,s);
then notify your recycler adapter that you modify an item by this code:
notifyItemChanged(position);
notifyItemRangeChanged(position, services.size());
hope helps you.
String str = arrayList.get(position);
arrayList.remove(str);
MyAdapter.this.notifyDataSetChanged();
To Method onBindViewHolder Write This Code
holder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor del=dbAdapter.ExecuteQ("delete from TblItem where Id="+values.get(position).getId());
values.remove(position);
notifyDataSetChanged();
}
});
Incase Anyone wants to implement something like this in Main class instead of Adapter class, you can use:
public void removeAt(int position) {
peopleListUser.remove(position);
friendsListRecycler.getAdapter().notifyItemRemoved(position);
friendsListRecycler.getAdapter().notifyItemRangeChanged(position, peopleListUser.size());
}
where friendsListRecycler is the Adapter name
you must to remove this item from arrayList of data
myDataset.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
notifyItemRangeChanged(holder.getAdapterPosition(), getItemCount());
//////// set the position
holder.cancel.setTag(position);
///// click to remove an item from recycler view and an array list
holder.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int positionToRemove = (int)view.getTag(); //get the position of the view to delete stored in the tag
mDataset.remove(positionToRemove);
notifyDataSetChanged();
}
});
make interface into custom adapter class and handling click event on recycler view..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(Contact contact);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(mContectList.get(position));
}
});
}
after define adapter and bind into recycler view called below code..
adapter.setOnItemClickListner(new CommentsAdapter.onItemClickListner() {
#Override
public void onClick(Contact contact) {
contectList.remove(contectList.get(contectList.indexOf(contact)));
adapter.notifyDataSetChanged();
}
});
}
In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this
mdataset.remove(holder.getadapterposition());
In the activity:
mAdapter.updateAt(pos, text, completed);
mAdapter.removeAt(pos);
In the your adapter:
void removeAt(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, list.size());
}
void updateAt(int position, String text, Boolean completed) {
TodoEntity todoEntity = list.get(position);
todoEntity.setText(text);
todoEntity.setCompleted(completed);
notifyItemChanged(position);
}
in 2022, after trying everything the whole internet given below is the answer
In MyViewHolder class
private myAdapter adapter;
inside MyViewHolder function initalise adapter
adapter = myAdapter.this
inside onclick
int position = getAdapterPosition()
list.remove(position);
adapter.notifyItemRemoved(position);