Issue
Basically i wanted to use an asynctask to set text for one textview but i have no clue how to do it this is what i did so far
public void onBindViewHolder(final ViewHolder holder, final int position) {
final ChatMessage msg = mMessagesList.get(position);
holder.messageTextView.setText(msg.getMessage());
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... str) {
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
I want to have the setText for the messageTextView inside the asyncTask instead of in the onBindViewHolder and thanks!
Solution
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).
Answered By - Steven
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.