title: Draw route direction path on Google Map api v2
body: <p>I am trying to draw a bus route on my map by drawing direction routes between all the bus stops that the bus drives by. </p>
  
  <p>I've got a list (markerPoints) with the LatLng objects for all the bus stops, and tries to run a loop for all points, where I for each point recieve a direction route between the bus stop at the current position of the loop and the next one.</p>
  
  <p>The problem is that I sometimes get Nullpointerexeption error when running this code. It usually works the first time I run it, then crashes the next time. however, if I change the loop so that it only runs one time, and hence only get one direction route, it is working... </p>
  
  <p>Could anyone help me find a solution for my problem, or point out what I am doing wrong?</p>
  
  <p><strong>My Method with the loop calling the async mathods for receiving direction route</strong></p>
  
  <pre><code>public void DrawRoutePath(){
      //Start on "Torget" because of issues with route path in city center
      for (int i = 0; i &lt; (markerPoints.size()-1); i++) { 
                  LatLng origin = markerPoints.get(i);
                  LatLng dest = markerPoints.get(i+1);
  
                  // Getting URL to the Google Directions API
                  String url = getDirectionsUrl(origin, dest);                
  
                  DownloadTask task = new DownloadTask();
                  // Start downloading json data from Google Directions API
                  task.execute(url);
      }
  }
  </code></pre>
  
  <p><strong>These are my methods for getting directions async:</strong></p>
  
  <pre><code>private String getDirectionsUrl(LatLng origin,LatLng dest){
  
      // Origin of route
      String str_origin = "origin="+origin.latitude+","+origin.longitude;
  
      // Destination of route
      String str_dest = "destination="+dest.latitude+","+dest.longitude;      
  
  
      // Sensor enabled
      String sensor = "sensor=false";         
  
      // Building the parameters to the web service
      String parameters = str_origin+"&amp;"+str_dest+"&amp;"+sensor;
  
      // Output format
      String output = "json";
  
      // Building the url to the web service
      String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
  
  
      return url;
  }
  
  /** A method to download json data from url */
  private String downloadUrl(String strUrl) throws IOException{
      String data = "";
      InputStream iStream = null;
      HttpURLConnection urlConnection = null;
      try{
              URL url = new URL(strUrl);
  
              // Creating an http connection to communicate with url 
              urlConnection = (HttpURLConnection) url.openConnection();
  
              // Connecting to url 
              urlConnection.connect();
  
              // Reading data from url 
              iStream = urlConnection.getInputStream();
  
              BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  
              StringBuffer sb  = new StringBuffer();
  
              String line = "";
              while( ( line = br.readLine())  != null){
                      sb.append(line);
              }
  
              data = sb.toString();
  
              br.close();
  
      }catch(Exception e){
              Log.d("Exception while downloading url", e.toString());
      }finally{
              iStream.close();
              urlConnection.disconnect();
      }
      return data;
   }
  
  
  
  // Fetches data from url passed
  private class DownloadTask extends AsyncTask&lt;String, Void, String&gt;{         
  
      // Downloading data in non-ui thread
      @Override
      protected String doInBackground(String... url) {
  
          // For storing data from web service
          String data = "";
  
          try{
              // Fetching the data from web service
              data = downloadUrl(url[0]);
          }catch(Exception e){
              Log.d("Background Task",e.toString());
          }
          return data;        
      }
  
      // Executes in UI thread, after the execution of
      // doInBackground()
      @Override
      protected void onPostExecute(String result) {           
          super.onPostExecute(result);            
  
          ParserTask parserTask = new ParserTask();
  
          // Invokes the thread for parsing the JSON data
          parserTask.execute(result);
  
      }       
  }
  
  /** A class to parse the Google Places in JSON format */
  private class ParserTask extends AsyncTask&lt;String, Integer, List&lt;List&lt;HashMap&lt;String,String&gt;&gt;&gt; &gt;{
  
      // Parsing the data in non-ui thread        
      @Override
      protected List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; doInBackground(String... jsonData) {
  
          JSONObject jObject; 
          List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; routes = null;                     
  
          try{
              jObject = new JSONObject(jsonData[0]);
              DirectionsJSONParser parser = new DirectionsJSONParser();
  
              // Starts parsing data
              routes = parser.parse(jObject);    
          }catch(Exception e){
              e.printStackTrace();
          }
          return routes;
      }
  
      // Executes in UI thread, after the parsing process
      @Override
      protected void onPostExecute(List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; result) {
          ArrayList&lt;LatLng&gt; points = null;
          PolylineOptions lineOptions = null;
          MarkerOptions markerOptions = new MarkerOptions();
  
          // Traversing through all the routes
          for(int i=0;i&lt;result.size();i++){
              points = new ArrayList&lt;LatLng&gt;();
              lineOptions = new PolylineOptions();
  
              // Fetching i-th route
              List&lt;HashMap&lt;String, String&gt;&gt; path = result.get(i);
  
              // Fetching all the points in i-th route
              for(int j=0;j&lt;path.size();j++){
                  HashMap&lt;String,String&gt; point = path.get(j);                 
  
                  double lat = Double.parseDouble(point.get("lat"));
                  double lng = Double.parseDouble(point.get("lng"));
                  LatLng position = new LatLng(lat, lng); 
  
                  points.add(position);                       
              }
  
              // Adding all the points in the route to LineOptions
              lineOptions.addAll(points);
              lineOptions.width(5);
              lineOptions.color(Color.RED);   
  
          }
  
          // Drawing polyline in the Google Map for the i-th route
          mMap.addPolyline(lineOptions);                          
      }           
  }   
  </code></pre>
  
  <p><strong>Error log from logcat</strong></p>
  
  <pre><code>04-22 20:03:18.911: E/AndroidRuntime(10471): FATAL EXCEPTION: main
  04-22 20:03:18.911: E/AndroidRuntime(10471): java.lang.NullPointerException
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at maps.z.ac.&lt;init&gt;(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at maps.z.bi.a(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at maps.z.bi.b(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at maps.z.ag.addPolyline(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.google.android.gms.maps.internal.IGoogleMapDelegate$Stub.onTransact(IGoogleMapDelegate.java:137)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.Binder.transact(Binder.java:326)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addPolyline(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.google.android.gms.maps.GoogleMap.addPolyline(Unknown Source)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.mso.master.MyMapFragment$ParserTask.onPostExecute(MyMapFragment.java:469)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.mso.master.MyMapFragment$ParserTask.onPostExecute(MyMapFragment.java:1)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.AsyncTask.finish(AsyncTask.java:631)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.Handler.dispatchMessage(Handler.java:99)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.os.Looper.loop(Looper.java:137)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at android.app.ActivityThread.main(ActivityThread.java:4931)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at java.lang.reflect.Method.invokeNative(Native Method)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at java.lang.reflect.Method.invoke(Method.java:511)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
  04-22 20:03:18.911: E/AndroidRuntime(10471):    at dalvik.system.NativeStart.main(Native Method)
  </code></pre>