代码之家  ›  专栏  ›  技术社区  ›  LizG

无效的API地址崩溃

  •  -1
  • LizG  · 技术社区  · 7 年前

    System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
    

    查找了这个错误的其他实例并尝试了解决方法,但似乎对我不起作用。就安卓而言,我是个傻瓜。

    按钮

    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);
        }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Nirav Bhavsar    7 年前

    实际上你的 responsebody 可能是空的,如果你试图 toString()

    把它放在下面的条件下

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

    您也可以尝试在内部添加代码 try catch

        2
  •  0
  •   LizG    7 年前

    读取代码时,目标似乎不包含“.getLongitude()”。现在工作正常了。