• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Getting the result of modified variable from doInBackground()

I need to pass value of distance obtained from doInBackground() to another activity in android programming. I tried creating object of this class in the activity class and then calling like obj.distance but it did not worked out.I would appreciate any help.

Code:
public class DistanceActivity extends AsyncTask<String, Void,String> {
public static String distance;

[USER=1021285]@override[/USER]
protected String doInBackground(String... urls) {
   URL a = null;

   try {
       a = new URL(urls[0]);
       HttpURLConnection c1 = null;
       c1 = (HttpURLConnection) a.openConnection();
       c1.setRequestMethod("GET");
       c1.connect();
       int responseCode = c1.getResponseCode();
       System.out.println("Response Code : " + responseCode);
       BufferedReader br = null;
       br = new BufferedReader(new InputStreamReader(c1.getInputStream()));
       StringBuilder sb = new StringBuilder();
       String s, s1 = "";
       while ((s1 = br.readLine()) != null) {
           sb.append(s1);
       }
       String jsonStr = sb.toString();
       System.out.println("JSONstr : " + jsonStr);
       distance = parseJSON(jsonStr);

   } catch (MalformedURLException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   }
   System.out.println("DISTANCE = " + distance);
   //return (Double.parseDouble(String.valueOf(d)));
   return distance;
}

private String parseJSON(String s) {
   String d = "";
   try {
       JSONObject ob = new JSONObject(s);
       JSONArray jarray = ob.getJSONArray("destination_addresses");
       d = ob.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").get("value").toString();
       System.out.println("Inside parser Distance=" + d);
   } catch (JSONException e) {
       e.printStackTrace();
   }
   return d;
}
 
Last edited by a moderator:
I can override onPostExecute(). But how to send value of distance to another activity where I want to use it for some further calculations?
 
Thank you for your reply, I am actually trying to send data from a non-activity class to an activity class. So I cannot use intent to send data through bundle. Please, let me know if you know any other method.
 
What do you mean "a non-activity class". Any code in an Android application, from any class, is executed in the context of an Activity.
I think if you included more of your code, we would see the full picture.
 
The class" DistanceActivity extends AsyncTask<String, Void,String>" from the above code cannot extend activity as it extends AsyncTask. Below is my MainActivity which is the other part of the project.
I need to pass the value of distance calculated from doInBackground() of DistanceActivity to MainActivity for further use. I tried creating an interface and pass the value but it is only visible inside setDouble method.
I am posting the whole project below.

Code:
public class MainActivity extends Activity implements DistanceActivity.Geo {
    double d, lat, lng, glat, glng;
    double distance;
    ProgressDialog pd;
    MainActivity ob = new MainActivity();
    TextView tv;

    [USER=1021285]@override[/USER]
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv1);

        lat = 47.925075;
        lng = -97.086174;
        glat = 47.9216244;
        glng = -97.0808849;
        //new DistanceActivity(MainActivity.this).execute("https://maps.googleapis.com/maps/api/distancematrix/json?origins=47.925075,-97.086174&destinations=47.9216244,-97.0808849&mode=driving&key="mykey"&sensor=true");
        new DistanceActivity(MainActivity.this).execute("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + lat + "," + lng + "&destinations=" + glat + "," + glng + "&mode=driving&key=AIzaSyA4a5UB8oXsymY6awOSHTtJPfhQUTGvcUw&sensor=true");

    }

    [USER=1021285]@override[/USER]
    public void setDouble(String result) {
        distance = Double.parseDouble(result);
        //tv.setText("Distance = "+distance);

    }
}

-------------------------------
Code:
public class DistanceActivity extends AsyncTask<String, Void,String> {
    public static String distance;
    Context mContext;
    Geo geo1;
    public DistanceActivity(Context mContext) {
        this.mContext = mContext;
        geo1= (Geo) mContext;
    }
    [USER=1021285]@override[/USER]
    protected String doInBackground(String... urls) {
        URL a = null;

        try {
            a = new URL(urls[0]);
            HttpURLConnection c1 = null;
            c1 = (HttpURLConnection) a.openConnection();
            c1.setRequestMethod("GET");
            c1.connect();
            int responseCode = c1.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(c1.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String s, s1 = "";
            while ((s1 = br.readLine()) != null) {
                sb.append(s1);
            }
            String jsonStr = sb.toString();
            System.out.println("JSONstr : " + jsonStr);
            distance = parseJSON(jsonStr);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("DISTANCE = " + distance);
        //return (Double.parseDouble(String.valueOf(d)));
        return distance;
    }

    private String parseJSON(String s) {
        String d = "";
        try {
            JSONObject ob = new JSONObject(s);
            JSONArray jarray = ob.getJSONArray("destination_addresses");
            d = ob.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").get("value").toString();
            System.out.println("Inside parser Distance=" + d);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return d;
    }
    protected void onPostExecute(String aDouble) {
        super.onPostExecute(aDouble);
           geo1.setDouble(aDouble);

    }


    interface Geo{
        public void setDouble(String result);
       // double distance = 0;
    }

}
 
Last edited by a moderator:
Having the MainActivity class implement an interface with a callback method (setDouble) is the correct strategy.

Can you please post the exact error you are currently seeing?
 
I am not getting any runtime error. But when I try to use "tv.setText("Distance = "+distance);" inside onCreate()
of MainActivity it is showing Distance=null. Some how I want to make distance value visible inside onCreate(). Because I want to use it for further calculations. Is there any way I can do this? I tried creating object of DistanceActivity and access it like "obj.Distance" and show it inside onCreate() with "tv.setText("Distance = "+distance);" ,but it is still showing Distance=null.
 
distance is null inside onCreate() because your AsyncTask has not yet made the call to your remote service and retrieved the data.

You know what AsyncTask does right? It creates a background thread, which runs in parallel to your main thread - that's the one running the code inside onCreate().

You will only be able to set the tv TextField with a proper value after the AsyncTask code has set that value by calling setDouble()
 
Thank you very much for your clarification. I am developing an app where I want to use the above code.In that program I have a distance method that takes longitude and latitude of two locations and returns the distance between them. I tried merging the above two programs into one to avoid the problem of sending distance and make it available to onCreate() . But I am getting "NetworkOnMainThreadException". Can you please tell me how can I make a single fuction perform all networking operations,calculate distance and return distance to be used by other method? As you can see in the above code I am creating the thread on onCreate() and getting the result inside setDouble() . Can you please suggest any method where I can use a single method to perform both the tasks ?My purpose in the app is to further use distance not just to show it using tv.Textview().
 
NetworkOnMainThreadException means exactly that - you're doing some network operation in the thread which executes the code of your main UI thread.
That's why we normally put such functionality into an AsyncTask, or otherwise create a background thread to do it.

I don't think the code you are showing reflects the current state of your project. You need to include the full stack trace of this error, and show the correct code which corresponds to the stack trace, before any further advice can be given.
 
Back
Top Bottom