无效的 API 地址崩溃



我有一个按钮,按下时,会计算乘车费并打算进行另一项活动,但是当按下时,会出现系统错误:

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);

计算现金费用

错误在此行上,第二次尝试,捕获:

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();
}
}

我在名为"模块"的文件夹中还有其他相关代码

测向仪

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);
}

实际上您的responsebody可能是空的,如果您尝试将toString()变为空对象,那么它将抛出错误。

把它放在以下条件下

if(response.body() != null){
// put here you complete code
JSONObject jsonObject = new JSONObject(response.body().toString());
}

您也可以尝试将代码添加到块try catch以防止崩溃。

读取代码时,似乎目标不包含".getLongitude(("。 它现在工作正常。

最新更新