Updates part of RecyclerView
I have a recycling View that contains
The description of the comment and the vote count when I pressed I need to count to increase this is what it currently looks like
But the problem is that the vote does increase when I press it, but it doesn’t update until I close that fragment and reopen it
What actually happens is that when I press vote, it makes an API call that executes some logic and sends it to android, which has a certain number of votes for the specific item that was clicked or voted on
How can I
update that particular record so I can see the change without reopening the View
Code:
CommentItem.java
public CommentItem(String id, String description, String voteCount)
{
this.id = id;
this.description= description;
this.voteCount = voteCount;
}
getters and setters
CommentItemAdapter.java
...
private OnItemClickListener mlistener;
/*Interfaces*/
public interface OnItemClickListener{
void VoteUpClick(int position);
void VoteDownClick(int position);
...
}
...
Comment on fragment .java
@Override
public void VoteUpClick(final int position) {
final CommentItem clickeedItem =
mitemList.get(position);
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String errorMsg = jObj.getString("msg");
Toast.makeText(getContext(), errorMsg,
Toast.LENGTH_SHORT).show();
} else {
String msg= jObj.getString("msg");
Toast.makeText(getContext(), msg,
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("voteType", "up");
params.put("commentID", clickeedItem.getId().toString());
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Solution
If I get it right, just adapter.notifyDataSetChanged()
will update your list. But there’s a better way to use DiffUtils
in recyclerView. That is, compare the old and new lists, only update the changed items, and do not change the entire data set.
Take a look
https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00
Other methods are to get a viewHolder reference from the Activity/Or Fragment via recyclerView.findViewHolderForAdapterPosition(position)
when onItemClick occurs. Then change the View through this View