Error in get route in Maps - android

I try to get the route between 3 locals but always return a error, this error:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at $ParserTask.onPostExecute(Mapa.java:195)
at $ParserTask.onPostExecute(Mapa.java:169)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
this is the code where I have the error:
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> 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);
}
polyLineOptions.addAll(points);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
I have 2 more classes to parse to JSON

Why have you initialised as null and in do in Background method?
List<List<HashMap<String, String>>> routes = null;
You can try removing the null declaration and put it in the class declaration and not in the Asynctask
Please have a look at this tutorial for more information.

Related

Find Places Nearby in Google Maps using Google Places API

http://javapapers.com/android/find-places-nearby-in-google-maps-using-google-places-apiandroid-app/
This Android tutorial is to learn about using Google Places API to find places nearby in Google maps. Ones the app runs then and click the button it wont pass the googlePlacesJson values and there by it returns null.
12-14 15:06:16.266 6095-6095/com.example.tony_.test_no E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tony_.test_no, PID: 6095
java.lang.NullPointerException
at com.example.tony_.test_no.PlacesDisplayTask.onPostExecute(PlacesDisplayTask.java:42)
at com.example.tony_.test_no.PlacesDisplayTask.onPostExecute(PlacesDisplayTask.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
12-14 15:06:17.938 6095-6095/com.example.tony_.test_no D/Process: killProcess, pid=6095
Please check code below
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
JSONObject googlePlacesJson;
GoogleMap googleMap;
#Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
googleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
googleMap.addMarker(markerOptions);
}
}
}

update value of holder textview in AsyncTask

I'm using google direction API to get the duration between my location and nearby places and it's working. But, I face problem in setting the duration value where the value is in onPostExecute.I tried to make duration global but it does not work. By the way, my textview is in ViewHolder class.
public class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
String distance = "";
String duration = "";
// Parsing the data in non-ui thread
#Override
public List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> 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
public void onPostExecute(List<List<HashMap<String, String>>> result) {
/*ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();*/
if(result.size()<1){
Toast.makeText(context, "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
}
}
//holder.val.setText("value"+duration);
Toast.makeText(context,"Duration:"+duration ,Toast.LENGTH_LONG).show();
}

Google Map crash on Android app

Someday the code crash...
My AndroidManifiest is correct even mi API credentials, my internet conecction works fine.
I am using Android Studio , the SDK are installed too.
Here is the Logcat
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at info.androidhive.slidingmenu.VanWhi$ParserTask.onPostExecute(VanWhi.java:139)
at info.androidhive.slidingmenu.VanWhi$ParserTask.onPostExecute(VanWhi.java:113)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And this is the Fragment
public class VanWhi extends FragmentActivity {
private static final LatLng VANCOUVER = new LatLng( 49.281612, -123.115464);
private static final LatLng WHISLER = new LatLng( 50.116966, -122.956546);
GoogleMap googleMap;
final String TAG = "PathGoogleMapActivity";
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vanwhi);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.setMyLocationEnabled(true);
MarkerOptions options = new MarkerOptions();
options.position(VANCOUVER);
options.position(WHISLER);
googleMap.addMarker(options);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(VANCOUVER,
6));
addMarkers();
}
private String getMapsApiDirectionsUrl() {
String waypoints = "waypoints=optimize:true|"
+ "|" + "|" + VANCOUVER.latitude + ","
+ VANCOUVER.longitude + "|" + WHISLER.latitude + ","
+ WHISLER.longitude;
String sensor = "sensor=false";
String params = waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
private void addMarkers() {
if (googleMap != null) {
googleMap.addMarker(new MarkerOptions().position(VANCOUVER)
.title("VANCOUVER"));
googleMap.addMarker(new MarkerOptions().position(WHISLER)
.title("WHISTLER"));
}
}
private class ReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> 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);
}
polyLineOptions.addAll(points);
polyLineOptions.width(8);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
}
It is from info.androidhive.slidingmenu and not from the Fragment you sent.
It's a nullpointer exception from a null List<>
you don't check if routes != null and path != null before your loops, maybe the json deserialisation failed, so those lists are nul

Android ProgressDialog stops spinning before the task is completed

I am using progress dialog in my Asynctask class on onpreExecte() method, and dismissing the dialog in onPostExecute while google makes the routes of the map. My problem is the wheel in dialog is stopping after 2-3 seconds but my background process is still working.
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MapaViagem.this);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Traçando Rotas");
dialog.setMessage("Aguarde...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> 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);
}
polyLineOptions.addAll(points);
polyLineOptions.width(4);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
You must put all the "procesing" code inside the doInBackground, that means all the code you have inside the onPostExcecute. Only the things that modify the UI should be in the onPostExcecute (like for example show a message to the user, change text of a TextView, etc.), else you will get your UI stucked.
I had the same problem and resolved it this way.
Hope it helps

Android Google Maps. Polylines not drawn correctly

I am trying to draw a costume route on a Google map. The route is displayed but I get some extra polylines in it:
As you can see the route is really messed up can anyone tell me how can I fix this issue?
I am drawing the lines using this method:
// Executes in UI thread, after the parsing process
protected void onPostExecute(List<List<HashMap<String, String>>> result)
{
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++)
{
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++)
{
HashMap<String,String> 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(7);
lineOptions.color(Color.GREEN);
}
// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);
}
and I am putting the coordinates of the segments using this code:
public List<List<HashMap<String,String>>> parse(Variant variant)
{
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
try
{
/** Traversing all routes */
for(int i=0;i < variant.route.length; i++)
{
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j < variant.route[i].segments.length; j++)
{
/** Traversing all points */
for(int l=0;l < variant.route[i].segments[j].coordinate.length; l++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(variant.route[i].segments[j].coordinate[l].latitude));
hm.put("lng", Double.toString(variant.route[i].segments[j].coordinate[l].longitude));
path.add(hm);
}
}routes.add(path);
}
}catch (Exception e){
}
return routes;
}
}

Categories

Resources