2

How to recover a string from AsyncTask?

 3 years ago
source link: https://www.codesd.com/item/how-to-recover-a-string-from-asynctask.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to recover a string from AsyncTask?

advertisements

I have the following class:

public class getURLData extends AsyncTask<String, Integer, String>{

@Override
protected String doInBackground(String... params) {
    String line;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(params[0]);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        line = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (MalformedURLException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (IOException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    }
    return line;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
}

}

And I am trying to call it like this:

String output = null;
output = new getURLData().execute("http://www.domain.com/call.php?locationSearched=" + locationSearched);

But the output variable isn't getting data, instead I am getting an error:

Type mismatch: cannot convert from AsyncTask<String,Integer,String> to String


The method execute returns the AynscTask itself, you need to call get:

output =
    new getURLData()
        .execute("http://www.domain.com/call.php?locationSearched=" + locationSearched)
        .get();

However, if you do that you just turned your async task into a sync one, as get waits if needed for the result to be avilable.

Reference: AsyncTask.get


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK