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
publicclassYourTaskimplementsRunnable {
privateHandler handler;
privateTextView textView;
publicYourTask(TextView textView){
this.textView = textView;
handler = newHandler();
}
@Overridepublicvoidrun() {
MessageRequest newMessage = newMessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(newServiceCallback<MessageResponse>() {
@OverridepublicvoidonResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(newRunnable() {
@Overridepublicvoidrun() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
@OverridepublicvoidonFailure(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
privateclassConversationTaskextendsAsyncTask<String, Void, Void> {
privateHandler handler;
publicConversationTask(){
handler = newHandler();
}
@OverrideprotectedVoiddoInBackground(String... params) {
MessageRequest newMessage = newMessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(newServiceCallback<MessageResponse>() {
@OverridepublicvoidonResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(newRunnable() {
@Overridepublicvoidrun() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
@OverridepublicvoidonFailure(Exception e) {
}
});
returnnull;
}
}
Hope it helps
Post a Comment for "Race Condition With Ui Thread Issue."