Help guys to figure it out, I just won’t understand what the error is

Code:

Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://maps.googleapis.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); APIService service = retrofit.create(APIService.class); Call<RouteResponse> call = service.getRoute(from,to,true,"ru"); call.enqueue(new Callback<RouteResponse>() { @Override public void onResponse(Call<RouteResponse> call, Response<RouteResponse> response) { Log.e("Тут", "Тут"); // Декодируем маршрут в точки LatLng List<LatLng> mPoints = PolyUtil.decode(response.body().getPoints()); Log.e("Размер",String.valueOf(mPoints.size())); //Строим полилинию Log.e("Размер",String.valueOf(mPoints.size())); PolylineOptions polylineOptions = new PolylineOptions(); polylineOptions.width(4f).color(R.color.colorBlack); LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder(); for(int i = 0;i<mPoints.size();i++){ polylineOptions.add((LatLng)mPoints.get(i)); latLngBuilder.include((LatLng)mPoints.get(i)); } map.addPolyline(polylineOptions); int size = getResources().getDisplayMetrics().widthPixels; LatLngBounds latLngBounds = latLngBuilder.build(); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(latLngBounds,size,size,25); map.moveCamera(cameraUpdate); } @Override public void onFailure(Call<RouteResponse> call, Throwable t) { } 

Don't look at the code, here response.body returns null, how to fix it?

Log

  FATAL EXCEPTION: main java.lang.NullPointerException at com.example.danilshik.testapplication.fragments.ShopInMapWay$1.onResponse(ShopInMapWay.java:163) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) D/dalvikvm: GC_CONCURRENT freed 1044K, 7% free 15770K/16903K, paused 12ms+10ms, total 46ms D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 33ms D/dalvikvm: GC_FOR_ALLOC freed 1012K, 11% free 15779K/17543K, paused 8ms, total 8ms W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4 Selected remote version of com.google.android.gms.googlecertificates, version >= 4 E/dalvikvm: Could not find class 'android.os.UserManager', referenced from method ts.a W/dalvikvm: VFY: unable to resolve const-class 274 (Landroid/os/UserManager;) in Lts; D/dalvikvm: VFY: replacing opcode 0x1c at 0x0010 I/dalvikvm: Could not find method android.os.UserManager.isUserUnlocked, referenced from method ts.a W/dalvikvm: VFY: unable to resolve virtual method 1154: Landroid/os/UserManager;.isUserUnlocked ()Z D/dalvikvm: VFY: replacing opcode 0x6e at 0x0023 

APIService

 @GET("maps/api/directions/json") Call<RouteResponse> getRoute( @Query(value = "origin", encoded = false) String position, @Query(value = "destination",encoded = false) String dectination, @Query("sensor") boolean sensor, @Query("language") String language ); 

RouteResponce

 public class RouteResponse { public List<Route> routes; public String getPoints(){ return routes.get(0).overviewPolyline.points; } class Route{ OverviewPolyline overviewPolyline; } class OverviewPolyline{ String points; } } 

Json

 { "geocoded_waypoints": [ { "geocoder_status": "OK", "place_id": "ChIJs4CrATw62UMRKg9NqObeA2I", "types": [ "street_address" ] }, { "geocoder_status": "OK", "place_id": "ChIJcQYIThU62UMRmhKGs-q_q70", "types": [ "route" ] } ], "routes": [ { "bounds": { "northeast": { "lat": 54.7380729, "lng": 55.9732509 }, "southwest": { "lat": 54.7329662, "lng": 55.9581493 } }, "copyrights": "Картографические данные © 2018 Google", "legs": [ { "distance": { "text": "1,7 км", "value": 1690 }, "duration": { "text": "8 мин.", "value": 470 }, "end_address": "ул. Ивана Якутова, Уфа, Респ. Башкортостан, Россия", "end_location": { "lat": 54.73732889999999, "lng": 55.9581493 }, "start_address": "ул. Мингажева, 160/1, Уфа, Респ. Башкортостан, Россия, 450005", "start_location": { "lat": 54.7348831, "lng": 55.9732509 }, "steps": [ { "distance": { "text": "20 м", "value": 20 }, "duration": { "text": "1 мин.", "value": 6 }, "end_location": { "lat": 54.7347061, "lng": 55.9732059 }, "html_instructions": "Направляйтесь на <b>юг</b>", "polyline": { "points": "_lamIygstI`@F" }, "start_location": { "lat": 54.7348831, "lng": 55.9732509 }, "travel_mode": "DRIVING" }, { "distance": { "text": "67 м", "value": 67 }, "duration": { "text": "1 мин.", "value": 36 }, "end_location": { "lat": 54.73477699999999, "lng": 55.972175 }, "html_instructions": "Поверните <b>направо</b> в сторону <b>ул. Мингажева</b>", "maneuver": "turn-right", "polyline": { "points": "}jamIqgstIEjBG`B" }, "start_location": { "lat": 54.7347061, "lng": 55.9732059 }, "travel_mode": "DRIVING" }, { "distance": { "text": "91 м", "value": 91 }, "duration": { "text": "1 мин.", "value": 46 }, "end_location": { "lat": 54.734899, "lng": 55.9708943 }, "html_instructions": "Поверните <b>налево</b> в сторону <b>ул. Мингажева</b>", "maneuver": "turn-left", "polyline": { "points": "kkamIcastIB@DB@@@@?B@@?H?D?FAJQvAI|@Iv@" }, "start_location": { "lat": 54.73477699999999, "lng": 55.972175 }, "travel_mode": "DRIVING" }, { "distance": { "text": "0,2 км", "value": 223 }, "duration": { "text": "1 мин.", "value": 64 }, "end_location": { "lat": 54.7329662, "lng": 55.9699862 }, "html_instructions": "Поверните <b>налево</b> на <b>ул. Мингажева</b>", "maneuver": "turn-left", "polyline": { "points": "clamIayrtIn@RLFdCv@xB~@bA^" }, "start_location": { "lat": 54.734899, "lng": 55.9708943 }, "travel_mode": "DRIVING" }, { "distance": { "text": "0,8 км", "value": 758 }, "duration": { "text": "2 мин.", "value": 141 }, "end_location": { "lat": 54.7349762, "lng": 55.9589906 }, "html_instructions": "Поверните <b>направо</b> на <b>ул. Революционная</b>", "maneuver": "turn-right", "polyline": { "points": "a`amImsrtIAf@OfACb@SpBc@pGG`AI~@Ef@a@hFKrAOvBI|@QhBALIz@]rDKnAe@`FKxCIdAOXINIJCBSTA??@KHUJ" }, "start_location": { "lat": 54.7329662, "lng": 55.9699862 }, "travel_mode": "DRIVING" }, { "distance": { "text": "0,4 км", "value": 369 }, "duration": { "text": "2 мин.", "value": 99 }, "end_location": { "lat": 54.7380729, "lng": 55.9594288 }, "html_instructions": "На круге сверните на <b>2-й</b> съезд на <b>ул. Цюрупы</b>", "maneuver": "roundabout-right", "polyline": { "points": "slamIunptICCAACAG?GAG@G@MFCBABCFCNAHAJo@d@OTICSEwE}Ai@SOEoA]KE}@[UI" }, "start_location": { "lat": 54.7349762, "lng": 55.9589906 }, "travel_mode": "DRIVING" }, { "distance": { "text": "0,1 км", "value": 101 }, "duration": { "text": "1 мин.", "value": 31 }, "end_location": { "lat": 54.73719089999999, "lng": 55.9590615 }, "html_instructions": "Выполните <b>разворот</b>", "maneuver": "uturn-left", "polyline": { "points": "}_bmImqptITH|@ZJDnA\\" }, "start_location": { "lat": 54.7380729, "lng": 55.9594288 }, "travel_mode": "DRIVING" }, { "distance": { "text": "61 м", "value": 61 }, "duration": { "text": "1 мин.", "value": 47 }, "end_location": { "lat": 54.73732889999999, "lng": 55.9581493 }, "html_instructions": "Поверните <b>направо</b> на <b>ул. Ивана Якутова</b><div style=\"font-size:0.9em\">Пункт назначения будет слева</div>", "maneuver": "turn-right", "polyline": { "points": "mzamIcoptI[tD" }, "start_location": { "lat": 54.73719089999999, "lng": 55.9590615 }, "travel_mode": "DRIVING" } ], "traffic_speed_entry": [], "via_waypoint": [] } ], "overview_polyline": { "points": "_lamIygstI`@FEjBG`BB@FD@D@Xg@xE|@ZdCv@xB~@bA^Af@SjBw@bKQ`CcA|Mg@pFi@bGe@`FKxCIdAOXSZYZa@TEE[AUHEFGVCTo@d@OT]IaGqB_Bc@iAa@UITHhA`@nA\\[tD" }, "summary": "ул. Революционная", "warnings": [], "waypoint_order": [] } ], "status": "OK" } 

Request:

 https://maps.googleapis.com/maps/api/directions/json?sensor=true&language=ru&origin=54.73489544, 55.97310594&destination=54.737,55.958 
  • Well, even despite the code, knowing that the response.body empty, you can conclude that you are either doing a wrong request, i.e. the server does not understand you, or problems with the connection. I think, in either case, you should work out the onFailure method instead of onResponse , do your logs work onResponse ? put logs in onFailure - Turalllb
  • It is also possible that the RouteResponse class RouteResponse not fit your json, and it is worthwhile to attach json too. In this case, onFailure will also work - Turalllb
  • Added JSON to code - danilshik
  • The problem is that I used the code from the example. But unfortunately, retrofit 1.7 was used, I updated the code, but spoiled something for the hike - danilshik
  • So then all the same work out onFailure ? put logs in this method and see what is printed - Turalllb

1 answer 1

For any server response, successful or not, Retrofit calls onResponse .
onFailure is called when an exception occurs on the client (parsing error, no network, etc.).
Therefore, in onResponse you need to check the answer to success:

 public void onResponse(Call<RouteResponse> call, Response<RouteResponse> response) { if (response.isSuccessful()) { // выполняем полезную работу } else { // иначе смотрим что не так и/или выполняем действия при неудаче // для отладки просто выводим в лог Log.e(TAG, String.format("Error response: %d %s", response.code(), response.message()); ResponseBody errorBody = response.errorBody(); if (errorBody != null) { try { Log.e(TAG, "Error body:\n" + errorBody.string()); } catch (IOException e) { e.printStackTrace(); } } } } 

Now you can see in the logs that the server is responding and correct.