-5

I have a problem similar to this one Android studio 3.0 shows Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference so i did this.

private void getDirection() {
    currentPosition = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());

    String requestAPI = null;
    try{
        requestAPI = "https://maps.googleapis.com/maps/api/directions/json?" +
                "mode=driving&" +
                "transit_routing_preference=less_driving&" +
                "origin=" + currentPosition.latitude + "," + currentPosition.longitude + "&" +
                "destination"+destination+"&"+"key="+getResources().getString(R.string.google_direction_api);

        Log.d("TriBER",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 jsonArray = jsonObject.getJSONArray("routes");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject route = jsonArray.getJSONObject(i);
                                    JSONObject poly = route.getJSONObject("overview_polyline");
                                    String polyline = poly.getString("points");
                                    polyLineList = decodePoly(polyline);

                                    //Adjusting bounds
                                    LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                    for (LatLng latLng : polyLineList)
                                        builder.include(latLng);
                                    LatLngBounds bounds = builder.build();
                                    CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 2);
                                    mMap.animateCamera(mCameraUpdate);

                                    polylineOptions = new PolylineOptions();
                                    polylineOptions.color(Color.GRAY);
                                    polylineOptions.width(5);
                                    polylineOptions.startCap(new SquareCap());
                                    polylineOptions.endCap(new SquareCap());
                                    polylineOptions.jointType(JointType.ROUND);
                                    polylineOptions.addAll(polyLineList);
                                    greyPolyline = mMap.addPolyline(polylineOptions);

                                    blackPolylineOptions = new PolylineOptions();
                                    blackPolylineOptions.color(Color.BLACK);
                                    blackPolylineOptions.width(5);
                                    blackPolylineOptions.startCap(new SquareCap());
                                    blackPolylineOptions.endCap(new SquareCap());
                                    blackPolylineOptions.jointType(JointType.ROUND);
                                    blackPolyline = mMap.addPolyline(blackPolylineOptions);

                                    mMap.addMarker(new MarkerOptions()
                                            .position(polyLineList.get(polyLineList.size() - 1))
                                            .title("Pickup Location"));

                                    //Animation
                                    ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
                                    polyLineAnimator.setDuration(2000);
                                    polyLineAnimator.setInterpolator(new LinearInterpolator());
                                    polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                        @Override
                                        public void onAnimationUpdate(ValueAnimator animation) {
                                            List<LatLng> points = greyPolyline.getPoints();
                                            int percentValue = (int) animation.getAnimatedValue();
                                            int size = points.size();
                                            int newPoints = (int) (size * (percentValue / 100.0f));
                                            List<LatLng> p = points.subList(0, newPoints);
                                            blackPolyline.setPoints(p);
                                        }
                                    });
                                    polyLineAnimator.start();
                                    carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
                                            .flat(true)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));

                                    handler = new Handler();
                                    index = -1;
                                    next = 1;
                                    handler.postDelayed(drawPathRunnable, 3000);


                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                    }


                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        Toast.makeText(Welcome.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

But when i press the GO Button, Toast "Error" is popping out. it is supposed to draw route from current location to the destination. can someone teach me the right thing to do? thank you

my logcat

 Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
                                                                         at com.clone.uber.uberclone.Welcome$4.onResponse(Welcome.java:240)
                                                                         at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:135)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5912)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                         at com.android.internal.os.ZygoteInit.main
shindou ai
  • 11
  • 5

1 Answers1

0

response.body() may be call only once in the code .

So you can add return to the response.body() .Then you can deal with your response .

You can try like this .

change

if (response.body() != null) {
    try {
        JSONObject jsonObject = new JSONObject(response.body().toString());

to

String res = response.body().string();
// or String response = response.body().toString();
if (response != null) {
    try {
        JSONObject jsonObject = new JSONObject(res);
        ...
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
  • "Cannot resolved method String" if i did that. can you please delete the if statement? im not really sure about it, i just did this https://stackoverflow.com/questions/47679610/android-studio-3-0-shows-attempt-to-invoke-virtual-method-java-lang-string-java – shindou ai Jan 31 '18 at 06:19
  • You can check again . – KeLiuyue Jan 31 '18 at 06:24
  • same error sir. can i contact you through your email account? – shindou ai Jan 31 '18 at 06:34
  • I use it .It worked ok .I change the name of `response` to `res` .You can try . – KeLiuyue Jan 31 '18 at 06:38
  • yes sir it worked the error "Cannot resolved method String" is gone now but the "Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference" when i clicked the GO BUTTON comes back. – shindou ai Jan 31 '18 at 06:44
  • I change to the `string` .S is a lowercase . And also you can use `toString` . – KeLiuyue Jan 31 '18 at 06:46
  • i did. I mean when running in the real device the error pops. can we use gmail chat now? – shindou ai Jan 31 '18 at 06:52
  • Sorry , i did not have too much time now . – KeLiuyue Jan 31 '18 at 07:00