1

I m getting this error when i click a button in Activity i m developing a Application in Android studio and getting error about json and i m not sure how to handle this error

Error Detail

Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference at com.example.tourista.DataParser.getAllnearbyPlaces(DataParser.java:62) at com.example.tourista.DataParser.parse(DataParser.java:100)

private List<HashMap<String,String>> getAllnearbyPlaces (JSONArray jsonArray)
{

//Line There i m getting Error

    int counter = jsonArray.length();

    List<HashMap<String,String>> NearbyPlacesList = new ArrayList<>();
    HashMap<String,String> NearbyplaceMap = null;

    if (jsonArray != null) {

        for (int i = 0; i < counter; i++) {
            try {
                NearbyplaceMap = getSingleNearbyPlace((JSONObject) jsonArray.get(i));
                NearbyPlacesList.add(NearbyplaceMap);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
    return NearbyPlacesList;
}

public List<HashMap<String,String>>  parse(String JSONdata)
{
    JSONArray jsonArray= null;
    JSONObject jsonObject;


    try
    {
        jsonObject =new JSONObject(JSONdata);
        jsonArray = jsonObject.getJSONArray("results");
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    return getAllnearbyPlaces(jsonArray);

}
Aleksey Potapov
  • 3,683
  • 5
  • 42
  • 65

3 Answers3

0

Your error is for this line : int counter = jsonArray.length();

if you have a null object you can't call any method of that

your jsonArray is null so you can't call jsonArray.length()

you should put int counter = jsonArray.length(); bellow if (jsonArray != null) {

hadi mohammadi
  • 321
  • 1
  • 2
  • 10
0

For this specific case

jsonArray = jsonObject.getJSONArray("results") probably throws a JSONException so your array is never initialized and remains null. Look in your logs and you will probably see some red lines of text with the error.

To learn more about Nullpointerexceptions read:

What is a NullPointerException, and how do I fix it?

Edward van Raak
  • 4,841
  • 3
  • 24
  • 38
  • Hey Edward van Raak, can you help me answer this other question that I have? https://stackoverflow.com/questions/67985251/speech-to-text-failed-not-able-to-find-the-problem – Ahtisham Ahmed Jun 25 '21 at 05:44
0

You need to provide more code. Who is calling the getAllnearbyPlaces (JSONArray jsonArray)?

When this class is called you are passing a null JSONArray

iliasPs
  • 15
  • 8