0

I am a beginner in android development. I keep getting the Caused by: java.lang.NullPointerException error. I have already used optJSONObject(0) method and with a if statement results_object.has("formatted_address"). Is there a way to ignore the error exception?

public String convertLatLngToAddress(JSONObject lat_lng) throws JSONException {
    Double lat = lat_lng.getDouble("lat");
    Double lng = lat_lng.getDouble("lng");

    String link = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=false";
    String address_in_string = urlToStringBuffer(link);
    JSONObject address_object = new JSONObject(address_in_string);
    JSONArray results = address_object.optJSONArray("results");
    JSONObject results_object = results.optJSONObject(0);
    if(results_object.has("formatted_address") && !results_object.isNull("formatted_address")) { // 
        String address = results_object.optString("formatted_address");
        return address;
    } else {
        return "";
    }
}    

JSON

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Pkwy",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4224764,
               "lng" : -122.0842499
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238253802915,
                  "lng" : -122.0829009197085
               },
               "southwest" : {
                  "lat" : 37.4211274197085,
                  "lng" : -122.0855988802915
               }
            }
         },
         "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

log

01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 W/dalvikvm: threadid=10: thread exiting with uncaught exception (group=0xa615e908)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:  Caused by: java.lang.NullPointerException
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at com.example.peter.fypv1.Model.Route.convertLatLngToAddress(Route.java:114)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at com.example.peter.fypv1.MainActivity$JSONTask.doInBackground(MainActivity.java:182)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at com.example.peter.fypv1.MainActivity$JSONTask.doInBackground(MainActivity.java:100)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
01-14 17:35:40.227 6249-6272/com.example.peter.fypv1 E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856) 
01-14 17:35:41.755 6249-6272/? I/Process: Sending signal. PID: 6249 SIG: 9
Cœur
  • 37,241
  • 25
  • 195
  • 267
h p2ter
  • 25
  • 5
  • It seems that `JSONObject results_object = results.optJSONObject(0);` is returning null, hence you cannot call "has" on a null object. – Thomas R. Jan 14 '16 at 09:54
  • @Thomas R. thank you so much, you are right, i have exceeded the rate-limit for this API. so the json array is different. – h p2ter Jan 14 '16 at 10:16

4 Answers4

2

Use The following code:

JSONArray results = address_object.optJSONArray("results");
//then get the all objects insid this array
 for(int i=0;i<results.length;i++){
     JsonObjects jsonObjects=results.getJsonObjects(i);
   // then access all child data using this jsonObject}

You can also use here the method like has("param-name") and isNull("param-name") for validations.

Always check the length of JsonArray before using it.

Hope It will help you!

Aman Goel
  • 3,351
  • 1
  • 21
  • 17
1
JSONObject results_object = results.optJSONObject(0);

You never ever get item from array before checking the array size like this:

JSONArray results = address_object.optJSONArray("results");
if(results.length()>0){
     JSONObject results_object = results.optJSONObject(0);
}

When you want to go through all items of result

JSONArray results = address_object.optJSONArray("results");
for(int i=0;i<results.length() ;i++){
     JSONObject results_object = results.optJSONObject(i);
}
Sharjeel
  • 15,588
  • 14
  • 58
  • 89
1

This is what you should write:

public String convertLatLngToAddress(JSONObject lat_lng) throws JSONException {
        Double lat = lat_lng.getDouble("lat");
        Double lng = lat_lng.getDouble("lng");

        String link = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=false";
        String address_in_string = urlToStringBuffer(link);
        JSONObject address_object = new JSONObject(address_in_string);
        JSONArray results = address_object.optJSONArray("results");
        JSONObject results_object = results.optJSONObject(0);
        if(results_object != null) {
            if(results_object.has("formatted_address") && !results_object.isNull("formatted_address")) { // 
                String address = results_object.optString("formatted_address");
                return address;
            }
        }
    }

you have first to check if the object is not equal to null befor calling any method to it.

I hope this will solve your problem :)

Youcam39
  • 102
  • 5
0

From the documentation here

I would say that your

results.optJSONObject(0)

returns null. Since the parameter is a String you likely want to do

results.optJSONObject("results")

However, this might not return a JSONObject (see documentation) but a JSONArray which would also result in a NullPointerException. To get the array use optJSONArray(String key).

And because null is returned you cannot do a has() on the result.

m00hk00h
  • 507
  • 2
  • 7
  • 21