Rafael K
Rafael K

Reputation: 171

Distance Matrix API AsyncTask Java

I have been trying to get the walking duration and distance between two locations using Distance Matrix API. I want to store this results (Distance and Duration) in variables that I will be able to access from other classes/activities.

I managed to get time and duration using AsyncTask, but when I try to store them in a variable in PostExecute method, they are always unassigned when accessing from a method or class outside of the PostExecute method. I now, understand how AsyncTask works and that is asynchronous. I tried to implement interfaces and then try to access the data but still I was not able to.

GeoTask is an inner class in my Map class.

public class GeoTask extends AsyncTask<String, Void, String> {
    ProgressDialog pd;
    Context mContext;

    SelectTime selectTime;



    //constructor is used to get the context.
    public GeoTask(Context mContext) {
        this.mContext = mContext;

    }

    public GeoTask() {
    }

    //This function is executed before before "doInBackground(String...params)" is executed to dispaly the progress dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        selectTime=new SelectTime();
        pd=new ProgressDialog(mContext);
        pd.setMessage("Loading");
        pd.setCancelable(false);
        pd.show();
    }
    //This function is executed after the execution of "doInBackground(String...params)" to dismiss the dispalyed progress dialog and call "setDouble(Double)" defined in "MainActivity.java"
    @Override
    protected void onPostExecute(String aDouble) {
        super.onPostExecute(aDouble);
        if(aDouble!=null)
        {
            setDouble(aDouble);
        }
        else
            Toast.makeText(mContext, "Error4!Please Try Again with proper values", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            URL url=new URL(params[0]);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.connect();
            int statuscode=con.getResponseCode();
            if(statuscode==HttpURLConnection.HTTP_OK)
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb=new StringBuilder();
                String line=br.readLine();
                while(line!=null)
                {
                    sb.append(line);
                    line=br.readLine();
                }
                String json=sb.toString();
                Log.d("JSON",json);
                JSONObject root=new JSONObject(json);
                JSONArray array_rows=root.getJSONArray("rows");
                Log.d("JSON","array_rows:"+array_rows);
                JSONObject object_rows=array_rows.getJSONObject(0);
                Log.d("JSON","object_rows:"+object_rows);
                JSONArray array_elements=object_rows.getJSONArray("elements");
                Log.d("JSON","array_elements:"+array_elements);
                JSONObject  object_elements=array_elements.getJSONObject(0);
                Log.d("JSON","object_elements:"+object_elements);
                JSONObject object_duration=object_elements.getJSONObject("duration");
                JSONObject object_distance=object_elements.getJSONObject("distance");

                Log.d("JSON","object_duration:"+object_duration);
                return object_duration.getString("value")+","+object_distance.getString("value");

            }
        } catch (MalformedURLException e) {
            Log.d("error", "error1");
        } catch (IOException e) {
            Log.d("error", "error2");
        } catch (JSONException e) {
            Log.d("error","error3");
        }


        return null;
    }


}

In Map class, the setDouble method:

   public void setDouble(String result) {
    String res[] = result.split(",");
    Double m = Double.parseDouble(res[0]) / 60;
    Double d = Double.parseDouble(res[1])/1000;


    minutes=m
    distance=d


}

The minutes and distance variables initialisation

private double minutes;

public double getMinutes() {
    return minutes;
}

private double distance;

public double getDistance() {
    return distance;
}

and the execution:

 LatLng destinationLatLng = getLatLngFromAddress(destinationPassed);

    currentOrigin = getAddressFromLatLng(currentLat,currentLong);


    String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentOrigin + "&destinations=" + destinationPassed + "&mode=walking&language=fr-FR&avoid=tolls&key=API_KEY";
    Log.d("url string",url);
    geoTask.execute(url);

Furthermore, I try to access the minutes and distance variables using the get methods in another class and I get the value 0.0 returned all the time, even after the PostExecution is completed (I tested that it completed using Logs)

1)How can I achieve what I want? Access the distance and duration returned by the API in different classes? It is essential for the app that I am doing to achieve that.

2)If I cant achieve what I want using AsyncTask and this method, is there any way to use Distance Matrix API without using AsyncTask?

Upvotes: 2

Views: 147

Answers (1)

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13343

Probably you should replace in your

String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentOrigin + "&destinations=" + destinationPassed + "&mode=walking&language=fr-FR&avoid=tolls&key=API_KEY";

line API_KEY characters by your valid Distance API key.

Take a look at this guide to get information how to obtain valid API key.

Upvotes: 1

Related Questions