【发布时间】:2019-02-25 17:08:52
【问题描述】:
当我按下骑手应用程序中的呼叫驱动程序按钮时。它在驱动程序应用程序上显示通知,但它崩溃了,因为它给出了调用空指针错误的错误。 在这一行出现空对象引用错误
(JSONObject jsonObject = new JSONObject(response.body().toString());)
这是我的 CustomerCall 课程
private void getDirection(double lat, double lng) {
String requestAPI = null;
try{
requestAPI = "https://maps.googleapis.com/map/api/directions/json?"+
"mode=driving&"+
"transit_routing_preference=less_driving&"+
"origin="+ Common.mLastLocation.getLatitude()+","+Common.mLastLocation.getLongitude()+"&"+
"destination="+lat+","+lng+"&"+
"key="+getResources().getString(R.string.google_direction_api);
Log.d( "Sunny",requestAPI ); //print url for debug
mService.getPath( requestAPI )
.enqueue( new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
//after get routes,just get 1st element route
JSONObject object = routes.getJSONObject(0);
//after get 1st element, we need array with name "legs"
JSONArray legs = object.getJSONArray("legs");
//and get 1st element of legs array
JSONObject legsObject = legs.getJSONObject(0);
//Now get Distance
JSONObject distance = legsObject.getJSONObject("distance");
txtDistance.setText(distance.getString("text"));
//get time
JSONObject time = legsObject.getJSONObject("duration");
txtTime.setText(time.getString("text"));
//get address
String address = legsObject.getString("end_address");
txtAddress.setText(address);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText( CustomerCall.this, ""+t.getMessage(), Toast.LENGTH_SHORT ).show();
}
} );
}catch (Exception e)
{
e.printStackTrace();
}
}
这里出现Logcat错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shk.callingloader, PID: 12668
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.shk.callingloader.CustomerCall$1.onResponse(CustomerCall.java:90)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
【问题讨论】:
-
CustomerCall.java 中的第 90 行是哪一行?你的回复有正文吗?
标签: java android json nullpointerexception response