Race Condition With UI Thread Issue.
This is the code i am working on. Here I cant update the UI until myOnResponse is finished.Because we are doing a doInBackgrnd, so my textresponse is empty. And Since onPostExecute
Solution 1:
I don't think that you have to use AsyncTask
.
You can do something like this :
YourTask.java
public class YourTask implements Runnable {
private Handler handler;
private TextView textView;
public YourTask(TextView textView){
this.textView = textView;
handler = new Handler();
}
@Override
public void run() {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
@Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
@Override
public void run() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
@Override
public void onFailure(Exception e) {
}
});
}
}
And now how to use it :
SomeActivity.java
...
textView = (TextView) findViewById(R.id.textView);
...
Thread thread = new Thread(new YourTask(textView));
thread.start();
...
Nevertheless if you want to do this action in Asynktask
just try this
private class ConversationTask extends AsyncTask<String, Void, Void> {
private Handler handler;
public ConversationTask(){
handler = new Handler();
}
@Override
protected Void doInBackground(String... params) {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
@Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
@Override
public void run() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
@Override
public void onFailure(Exception e) {
}
});
return null;
}
}
Hope it helps
Post a Comment for "Race Condition With UI Thread Issue."