1

I have to use directions() function in an AsyncTask to avoid network processing on the UI thread.i'm unable to do this thing. MY code is

    public class MainActivity extends MapActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MapView mapView = (MapView) findViewById(R.id.mapview); //or you can declare it directly with the API key
        Route route = directions(new GeoPoint((int)(26.2*1E6),(int)(50.6*1E6)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
        RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
        mapView.getOverlays().add(routeOverlay);
        mapView.invalidate();
    }

    private Route directions(final GeoPoint start, final GeoPoint dest) {
        Parser parser;
        //https://developers.google.com/maps/documentation/directions/#JSON <- get api
        String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
        final StringBuffer sBuf = new StringBuffer(jsonURL);
        sBuf.append("origin=");
        sBuf.append(start.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(start.getLongitudeE6()/1E6);
        sBuf.append("&destination=");
        sBuf.append(dest.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(dest.getLongitudeE6()/1E6);
        sBuf.append("&sensor=true&mode=driving");
        parser = new GoogleParser(sBuf.toString());
        Route r =  parser.parse();
        return r;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

}
Raptor
  • 53,206
  • 45
  • 230
  • 366
Mukul Bansal
  • 31
  • 1
  • 7

3 Answers3

1

Perhaps like this?

public class MainActivity extends MapActivity {

    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mapView = (MapView) findViewById(R.id.mapview); //or you can declare it directly with the API key
        // You can execute it at onCreate or whenever you want, for example: in a click event
        new AsyncRoutes().execute();
    }

    private Route directions(final GeoPoint start, final GeoPoint dest) {
        Parser parser;
        //https://developers.google.com/maps/documentation/directions/#JSON <- get api
        String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
        final StringBuffer sBuf = new StringBuffer(jsonURL);
        sBuf.append("origin=");
        sBuf.append(start.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(start.getLongitudeE6()/1E6);
        sBuf.append("&destination=");
        sBuf.append(dest.getLatitudeE6()/1E6);
        sBuf.append(',');
        sBuf.append(dest.getLongitudeE6()/1E6);
        sBuf.append("&sensor=true&mode=driving");
        parser = new GoogleParser(sBuf.toString());
        Route r =  parser.parse();
        return r;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    private class AsyncRoutes extends AsyncTask<Void, Integer, Route> {

        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {

            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setMessage("Obtaining routes...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Route doInBackground(Void... params) {

            Route route = directions(new GeoPoint((int)(26.2*1E6),(int)(50.6*1E6)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
            return route;
        }

        @Override
        protected void onPostExecute(Route route) {         

            RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
            mapView.getOverlays().add(routeOverlay);
            mapView.invalidate();

            pDialog.dismiss();
        }
    }

}
  • thanks.I'm using below link for driving directions in android there they said just to use direction() function in asynctask but still the app was unfortunately stopped..can u pl help me. http://stackoverflow.com/questions/11745314/why-retrieving-google-directions-for-android-using-kml-data-is-not-working-anymo/11745316#11745316 – Mukul Bansal Mar 13 '13 at 05:10
  • Then, please provide the LogCat output to know where the problem might be. –  Mar 13 '13 at 05:12
  • the log cat shows this 03-13 10:43:15.129: E/Index 0 out of range [0..0)(18918): Google JSON Parser - http://maps.googleapis.com/maps/api/directions/json?origin=26.2,50.6&destination=26.3,50.7&sensor=true&mode=driving 03-13 10:43:15.182: E/AndroidRuntime(18918): FATAL EXCEPTION: main – Mukul Bansal Mar 13 '13 at 05:15
  • I think the error is in the google JSON parser link http://maps.googleapis.com/maps/api/directions/json?origin=26.2,50.6&destination=26.3,50.7&sensor=true&mode=driving Can you provide the way to correct this – Mukul Bansal Mar 13 '13 at 05:22
0

This is the basic structure of an AsyncTask

public class TalkToServer extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... params) {
    //do your work here
        return something;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
           // do something with data here-display it or send to mainactivity
}

you can do your network stuff and/or stuff that you have in directions in doInBackground() and update UI on the other methods. You can also put the directions method as a private method of your AsyncTask

Then you would call this from your MainActivity like

TalkToServer networkStuff = new TalkToServer(); //could pass params to a constructor here such as context
networkStuff.execute();

If the AsyncTask isn't an inner class of your MainActivity then you will need a constructor to receive the context from your MainActivity if you want to do UI stuff

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • thanks.I'm using below link for driving directions in android there they said just to use direction() function in asynctask but still the app was unfortunately stopped..can u pl help me. http://stackoverflow.com/questions/11745314/why-retrieving-google-directions-for-android-using-kml-data-is-not-working-anymo/11745316#11745316 – Mukul Bansal Mar 13 '13 at 05:48
  • Yes, follow what I provided in the answer and post any/all error messages you get. Make the `AyncTask` an inner class of your `MainActivity` then either put the contents of `directions` in the `doInBackground()` or simply call the `directions` from `do"inBackground()` and make `directions` a method in your `AsyncTask class` – codeMagic Mar 13 '13 at 12:49
0

Here is what I think they mean when they say you can use an AsyncTask:

public class MainActivity extends MapActivity {

private MapView mapView; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mapView = (MapView) findViewById(R.id.mapview); //or you can declare it directly with the API key
    RouteTask routeTask = new RouteTask(new GeoPoint((int)(26.2*1E6),(int)(50.6*1E6)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6));
    routeTask.execute("");
}

private Route directions(final GeoPoint start, final GeoPoint dest) {
    Parser parser;
    //https://developers.google.com/maps/documentation/directions/#JSON <- get api
    String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
    final StringBuffer sBuf = new StringBuffer(jsonURL);
    sBuf.append("origin=");
    sBuf.append(start.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(start.getLongitudeE6()/1E6);
    sBuf.append("&destination=");
    sBuf.append(dest.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(dest.getLongitudeE6()/1E6);
    sBuf.append("&sensor=true&mode=driving");
    parser = new GoogleParser(sBuf.toString());
    Route r =  parser.parse();
    return r;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

class RouteTask extends AsyncTask<String, Void, String> {
    private GeoPoint start;
    private GeoPoint dest;
    private Route route;

    public RouteTask(GeoPoint start, GeoPoint dest) {
        this.start = start;
        this.dest = dest;
    }

    protected String doInBackground(String... strings) {
        //runs the directions method in a background thread.
        route = directions(start, dest);
        return "Started";
    }

    @Override
    protected void onPostExecute(String s) {
        //Updates the UI on the main/UI thread (post execute is called on the main/UI thread).
        RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
        mapView.getOverlays().add(routeOverlay);
        mapView.invalidate();
    }
}

}

This will run the directions method on a background thread and update the map on the main/UI thread. AS a general practice for all programing languages you should do UI work on the thread that draws to the screen (main/UI thread in this case).

This should do what you need it to.

James Jones
  • 1,486
  • 1
  • 12
  • 22
  • thanks.I'm using below link for driving directions in android there they said just to use direction() function in asynctask but still the app was unfortunately stopped..can u pl help me. http://stackoverflow.com/questions/11745314/why-retrieving-google-directions-for-android-using-kml-data-is-not-working-anymo/11745316#11745316 – Mukul Bansal Mar 13 '13 at 05:47