I wouldn't suggest putting asynctask like that.
public void onBindViewHolder(final ViewHolder holder, final int position) {
final ChatMessage msg = mMessagesList.get(position);
holder.messageTextView.setText(msg.getMessage());
new LongOperation(holder,msg.getMessage()).execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
private WeakReference<ViewHolder> holder;
private String message;
LongOperation(ViewHolder viewholder, String message){
holder = new WeakReference<ViewHolder>(viewholder);
this.message = message;
}
@Override
protected String doInBackground(String... str) {
//do all your background stuff here
return null;
}
@Override
protected void onPostExecute(String result) {
if(holder.get() != null){
holder.get().messageTextView.setText(message);
}
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
You use a weakreference to ensure that if the async task ends up being alive while your application is being killed off, the async task does not hold up the garbage collection.
Also I noticed that this async task is called Long Operation. You do not want to do long operations inside an async task. Async task by design is supposed to be used for short operations. Also, if your onBindViewHolder() gets called a lot (which is usually the case with any decently sized recyclerview), you will be creating a lot of async task which is really bad for performance. Reconsider what you are doing, there is almost always a better way of doing this.
You are probably better off creating a handler and a handler thread specially for this purpose (and doing post).
setText for viewholder inside asyncTask
letucrop 1,685 30th Jul, 2019
To share this paste please copy this url and send to your friends
RAW Paste Data
There are no comments yet.