Change variable in a Task

0

I'm using this method to read an html page, and it's making a Toast with the result. But I wanted it to return the read value, or put it in some variable, but I did not succeed.

private class GrabURL extends AsyncTask<String, Void, Void> {
    private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private ProgressDialog Dialog = new ProgressDialog(getActivity());

    protected void onPreExecute() {
        Dialog.setMessage("Carregando. Aguarde...");
        Dialog.show();
    }

    protected Void doInBackground(String... urls) {
        try {
            HttpGet httpget = new HttpGet(urls[0]);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            Error = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            Error = e.getMessage();
            cancel(true);
        }

        return null;
    }

    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
        if (Error != null) {
            Toast.makeText(getActivity(), Error, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getActivity(), "Source: " + Content, Toast.LENGTH_LONG).show();
            retorno = Content; // Essa variavel retorno é onde queria setar.
        }
    }

}
    
asked by anonymous 04.07.2014 / 00:43

2 answers

1

Remembering that for you to use onPostExecute you must pass the result type on the inheritance.

1) Assuming it is a String, it is the third parameter:

extends AsyncTask<String, Void, String> 

2) YourInBackground function should return the type of this result, in this case a String.

 protected String doInBackground(String... urls) {


         String result = "";

        return result ;
    }

3) Your onPostExecute function must be signed to receive a String as a parameter:

protected void onPostExecute(String result)
    
04.07.2014 / 03:46
1

It's a matter of timing . The variable retorno may even be receiving the value of Content , but the part of the code that is reading the value of retorno must be trying to access it before AsyncTask finish executing and therefore before it has the desired value. Remember: you can not start executing the AsyncTask and expecting the value to be returned immediately to you, because AsyncTask takes time to execute. For this there is the onPostExecute() method, which is executed just after doInBackground() has been completed and the requested data is ready and available.

What use will you make of retorno ? Save it to the bank in Shared Preferences, or display it in% on screen? Whatever it is, the suggestion is to do it in the TextView method itself, which is when it is with the value you want.

    
04.07.2014 / 01:18