E / AndroidRuntime:致命异常:主要 处理:com.example.max.mymaprouting,PID:7236 java.lang.NullPointerException:尝试在空对象引用上调用接口方法'int java.util.List.size()' at com.example.max.mymaprouting.MapsActivity $ ParserTask.onPostExecute(MapsActivity.java:131) at com.example.max.mymaprouting.MapsActivity $ ParserTask.onPostExecute(MapsActivity.java:104) 在android.os.AsyncTask.finish(AsyncTask.java:636) 在android.os.AsyncTask.access $ 500(AsyncTask.java:177) 在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:653) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:135) 在android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) 在java.lang.reflect.Method.invoke(Method.java:372) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
即:
for (int i = 0; i < routes.size(); i++) {
List<HashMap<String, String>> path = routes.get(i);
MapsActivity和其他java代码段(所有需要的导入都已实现):
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap;
private static final LatLng HOME = new LatLng(52.448720, 35.451194);
private static final LatLng OFFICE = new LatLng(45.516205, 30.436827);
private static final LatLng RANDOM = new LatLng(45.510144, 31.451873);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mMap = fragment.getMap();
mMap.setMyLocationEnabled(true);
MarkerOptions options = new MarkerOptions();
options.position(HOME);
options.position(OFFICE);
options.position(RANDOM);
mMap.addMarker(options);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
addMarkers();
}
private String getMapsApiDirectionsUrl() {
String waypoints = "waypoints=optimize:true|"
+ HOME.latitude + "," + HOME.longitude
+ "|" + "|" + OFFICE.latitude + ","
+ OFFICE.longitude + "|" + RANDOM.latitude + ","
+ RANDOM.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 (mMap != null) {
mMap.addMarker(new MarkerOptions().position(OFFICE)
.title("Office"));
mMap.addMarker(new MarkerOptions().position(HOME)
.title("home, sweet home"));
mMap.addMarker(new MarkerOptions().position(RANDOM)
.title("Random point"));
}
}
private class ReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
Http http = new Http();
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]);
JSONParser parser = new JSONParser();
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;
ArrayList<LatLng> points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
for (int i = 0; i < routes.size(); i++) {
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);
}
}
mMap.addPolyline(polyLineOptions);
}
}
}
HTTP
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URL;
import android.util.Log;
public class Http {
public String readUrl(String mapsApiUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(mapsApiUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
data = buffer.toString();
reader.close();
} catch (Exception e) {
// Log.d("Exception while reading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}}
JSONParser
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
public class JSONParser {
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps
.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat",
Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng",
Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}}
如何解决?求助。
答案 0 :(得分:0)
,您的路线可能为空。你应该在继续逻辑之前检查空指针异常。
if (routes != null) {
// do your stuffs
}