¿Cómo puedo pasar argumentos a AsyncTask y devolver resultados a una variable de campo de otra clase?

Tengo un problema con asynctask in android Java. it's the same problem as this : variable devuelve nulo fuera de asynctask android my asynctask get data from a url , to get direction of google maps ! This is where I call my code , inside onrespondre => myvaraible have data but outside the variable is null.

    public void onResponse(String status, Document doc, final GoogleDirection gd) {
    mMap.addMarker(new MarkerOptions()
            .position(
                    new LatLng(myLocation.getLatitude(), myLocation
                            .getLongitude()))
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
    mMap.addMarker(new MarkerOptions().position(Position).icon(
            BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
    MyVariable = gd.getTotalDurationValue(doc);
}

this is the class :

    private class RequestTask extends AsyncTask<String, Void, Document> {
    protected Document doInBackground(String... url) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url[0]);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();

            return builder.parse(in);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(Document doc) {
        super.onPostExecute(doc);

        if (mDirectionListener != null) {
            mDirectionListener.onResponse(getStatus(doc), doc,
                    GoogleDirection.this);
        }
    }

    private String getStatus(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("status");
        Node node1 = nl1.item(0);

        if (isLogging) {
            Log.i("GoogleDirection", "Status : " + node1.getTextContent());
        }

        return node1.getTextContent();
    }
}

preguntado el 28 de mayo de 14 a las 14:05

what is null? can you be more specific? -

for example , I declare an object : Integer test; when I affect to my variable test getDistanceValue , my variable test have now a data (let's say it's 8) but if I'm outside of the asynctask , my variable test is null (no data) -

your variable will remain null until the thread inwhich your variable is assigned a value finishes -

@IllegalArgument How I can know how much time the thread takes to finish ? because if I don't solve this problem I can't get the distance or duration in my field variable. -

in your onpostexecute method of your asynctask -

2 Respuestas

La conjetura getter setters are very basic. But for people who don't know:

A separate class for the getter setter

public class getterSetter{

String test;

public getterSetter()
{
    super();
    test= "";
}

public String getStatus()
{
    return test;
}
public setStatus(String input)
{
    test= input;
}
}

En su Asynctask:

protected void onPostExecute(Document doc) {
        super.onPostExecute(doc);
        setStatus(getStatus(doc));
        if (mDirectionListener != null) {
            mDirectionListener.onResponse(doc,
                    GoogleDirection.this);
        }

Y en tu onResponse método:

public void onResponse(Document doc, final GoogleDirection gd) {

String status = getStatus();
mMap.addMarker(new MarkerOptions()
        .position(
                new LatLng(myLocation.getLatitude(), myLocation
                        .getLongitude()))
        .icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.addMarker(new MarkerOptions().position(Position).icon(
        BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
MyVariable = gd.getTotalDurationValue(doc);
}

contestado el 19 de mayo de 15 a las 12:05

@PiyushGupta: when editing, please note that inline code spans (like this) shouldn't be used for highlighting, only for code in sentences. Also, please try and improve the post as much as possible when editing as posts are bumped in the process. Thanks! - qantas 94 pesado

Esto es lo que puedes hacer:

Define a getter - setter for the variable that you want. In your onPostExecute method, set the value of your variable and when you have to retrieve it, get the value from the getter. You may use a separate class for the getter - setter.

contestado el 19 de mayo de 15 a las 11:05

you should provide an example or some code snippet if you really need to help out the community. - Nomesh DeSilva

When you'r posting your answer then you should keep in mind that if you have already posted a answer then you should edit your answer rather than post a second answer. Enjoy !!@ - Piyush

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.