我有一个按钮,当按下该按钮时,它会计算出乘车费用和其他活动的意图,但是当按下时,会出现系统错误:
System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
查找了此错误的其他实例,并尝试了解决方法,但似乎不适用于我。就Android而言,我是菜鸟。
按钮
else if (btnStartTrip.getText().equals("DROP OFF HERE")) {
// arriving at destination with customer ....
calculateCashFee(pickupLocation, Common.mLastLocation);
calculateCashFee
错误在这行,第二次尝试,抓住:
JSONObject jsonObject = new JSONObject(response.body().toString());
private void calculateCashFee(final Location pickupLocation, Location mLastLocation) {
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&transit_routing_preference=less_driving" +
"&origin="+ pickupLocation.getLatitude() + ","+ pickupLocation.getLongitude() +
"&tap_destination=" + mLastLocation.getLatitude() + ", " + mLastLocation
.getLongitude() + "&key=" + getResources().getString(R.string.google_directions_api);
mService.getPath(requestApi).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try {
// Extract json
// Root Object
JSONObject jsonObject = new JSONObject(response.body().toString()); // System error
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
// Get Distance
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
// Only take number string to parse
Double distance_value = Double.parseDouble(distance_text
.replaceAll("[^0-9\\\\.]+", ""));
// Get Time
JSONObject timeObject = legsObject.getJSONObject("duration");
String time_text = timeObject.getString("text");
// Only take number string to parse
Double time_value = Double.parseDouble(time_text
.replaceAll("[^0-9\\\\.]+", ""));
sendDropOffNotification(customerId);
Intent intent = new Intent(DriverTracking.this,
DriverTripDetail.class);
intent.putExtra("start_address", legsObject
.getString("start_address"));
intent.putExtra("end_address", legsObject
.getString("end_address"));
// intent.putExtra("time", String.valueOf(time_value)); ---> not using
intent.putExtra("distance", String.valueOf(distance_value));
intent.putExtra("total", Common.formulaPrice(
distance_value));
intent.putExtra("location_start", String.format(Locale.CANADA,
"%f, %f", pickupLocation.getLatitude(),
pickupLocation.getLongitude()));
intent.putExtra("location_end", String.format(Locale.CANADA,
"%f, %f", Common.mLastLocation.getLatitude(),
Common.mLastLocation.getLongitude()));
startActivity(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverTracking.this, "" + t.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
我在名为“模块”的文件夹中还有其他相关的代码
DirectionFinder
private class DownloadRawData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance
.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration
.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"),
jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"),
jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
答案 0 :(得分:0)
实际上,您的responsebody
可能为null,如果您尝试将toString()
设为null对象,则会抛出错误。
将其放入以下条件
if(response.body() != null){
// put here you complete code
JSONObject jsonObject = new JSONObject(response.body().toString());
}
您也可以尝试在try catch
块中添加代码以防止崩溃。
答案 1 :(得分:0)
在阅读代码时,目标位置似乎不包含“ .getLongitude()”。现在可以正常工作了。