caibirdcnb caibirdcnb - 3 months ago 7
Android Question

How to do or do nothing base on AsyncTask result?

Experts,

My goal is simple, input an address, click a button to test a URL, if not get the expected result, a toast info and then do nothing. If get expect result, continue the program.

Since I can not use URL in UI thread, I used AsyncTask, the problem is: though I know the result from AsyncTak, how to inform activity to do or do nothing?
What I want is a statement inside the OnClickListener like this:

if (result is not expected) return; else continue do things.


I cannot write above statement in onPostExecute, it will return onPostExecute(), not onClickLIstener().

Another is: even if I can pass the result to activity(namely to onClickLIstener()), when the result arrives, probably UI thread already run some other codes, but they shouldn't before knowing the result.

In short, I need the URL result to decide how to run remaining codes, therefore cannot use async task, what should I do?

Thanks.

Below is the example code:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

new XXX().execute(code);
});

}


class XXX extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strArr) {
XXXXX;
}

protected void onPostExecute(String result) {
XXXXX;
}
}

Answer

This should be easy. Try this approach:

Since you already have your AsyncTask as an inner class in your activity, you can easily return a result in onPostExecute() then check if request was successful or not.

Now, here is the final part: create a method in your activity like this:

private void executeOnAsyncSuccess(){
   //place the code here you want to run
}

Now you can call it inside onPostExecute() easily!

You can also do this using Events but this approach should just work!

I hope this helps!

Comments