From Android JSON array to a list of items

In my android app, I have encountered an issue while trying to parse a JSONArray into an ArrayList. The PHP script returns the expected results correctly, but when attempting to add the results to the ArrayList in Java, a null pointer exception occurs at resultsList.add(map)

public void agencySearch(String tsearch)    {
        // Setting the URL for the Search by Town
        String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
        // Building parameters for the search
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("City", tsearch));

        // Getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);

        for (int i = 0; i < json.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            try {
                JSONObject c = (JSONObject) json.get(i);
                //Fill map
                Iterator iter = c.keys();
                while(iter.hasNext())   {
                    String currentKey = (String) iter.next();
                    map.put(currentKey, c.getString(currentKey));
                }
                resultsList.add(map);

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

            }

        };

        MainActivity.setResultsList(resultsList);

    }

Answer №1

Here is a suggestion that might assist you:

public void agencySearch(String searchTerm)    {
        // Defining the URL for searching by city
        String searchUrl = "http://www.infinitycodeservices.com/get_agency_by_city.php";
        // Creating parameters for the search
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("City", searchTerm));

        // Retrieving JSON data from the specified URL
        JSONArray jsonResult = jParser.getJSONFromUrl(searchUrl, params);

       ArrayList<HashMap<String, String>> resultsList = new  ArrayList<HashMap<String, String>>();

        for (int i = 0; i < jsonResult.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();

            try {
                JSONObject obj = jsonResult.getJSONObject(position);
                //Populate the map
               Iterator<String> iter = obj.keys();
                while(iter.hasNext())   {
                    String currentKey = it.next();
                    map.put(currentKey, obj.getString(currentKey));
                }
                resultsList.add(map);

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

            }

        };

        MainActivity.setResultsList(resultsList);

    }

Answer №2

It is recommended to utilize a custom method that converts your JSONArray into a List instead of manually iterating and constructing the List.

Instructions on how to call this method :

try {
     ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>) convertToList(json);
} catch (JSONException e) {
     e.printStackTrace();
}

Method to convert JSON array into List :

private List convertToList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    int size = array.length();
    for (int i = 0; i < size; i++) {
        list.add(parseJson(array.get(i)));
    }
    return list;
}

Method to convert JSON into Object :

private Object parseJson(Object json) throws JSONException {
    if (json == JSONObject.NULL) {
        return null;
    } else if (json instanceof JSONObject) {
        return mapFromJson((JSONObject) json);
    } else if (json instanceof JSONArray) {
        return convertToList((JSONArray) json);
    } else {
        return json;
    }
}

Method to convert JSON into Map :

public Map<String, String> mapFromJson(JSONObject object) throws JSONException {
    Map<String, String> map = new HashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, parseJson(object.get(key)).toString());
    }
    return map;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to toast the values of an array retrieved from a getter within my object?

My data in the format of a JSON Array looks like this and I am attempting to display the user_review_ids values - 63,59,62 using a toast message. However, instead of getting the actual values, I keep receiving what seems to be a reference to them, such as ...

What is the process for importing XML file data into ArangoDB?

<InputParameters> <Textbox> <Text>1234</Text> <Text>5678</Text> <Text>90AB</Text> </Textbox> </InputParameters> If you need to import the data from this XML file i ...

How can I set up mixare with JSON data?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban"; $q=mysqli_query($connection, $query); // Assume $connection is the MySQL connection variable //echo $query; while($row=mysqli_fetch_assoc( ...

Tips for transferring functions to Selenium's JavaScript executor?

Consider this scenario where I have a JavaScript function like the one below: function someFunction(callback) { callback() } If I want to invoke this function from Selenium, I can easily pass normal arguments such as strings, arrays, integers, maps, an ...

What is the best way to transfer information from a service to my controller?

Currently, I am experimenting with the Ionic framework and learning AngularJS simultaneously. I have been working on implementing $q and asynchronous calls but facing some challenges. My goal is to parse a JSON file using GetJsonSpecials, pass it to GetDat ...

Checking for the presence of a pseudo element using selenium

Is it possible to detect the presence of a pseudo element like ::after or ::before? I am looking to simply determine if it exists, returning true or false. Unfortunately, traditional methods like: browser.driver.findElements(by.id('id')).size ...

Issue with GSON serialization resulting in incorrect JSON output

Need some help with serializing an object of this format using GSON https://i.stack.imgur.com/Luhqz.png Below is the code I am currently using: public String encode(Object object){ return this.gson.toJson(object); } The issue lies in the output tha ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

Handling POST Requests in a Java Servlet

Currently, I am working on a servlet project in Eclipse that involves receiving POST requests from clients. The goal is to perform text splitting tasks and utilize the Google Geolocation API to retrieve relevant data for user display. While this functiona ...

The implementation of the necessary cerberus rule is contingent upon specific conditions

I am facing a challenge with a large JSON document, where certain fields need to be mandatory based on the values of other fields. For example: document = {'is_realty_address': False, 'postcode': 111111} In this case, the postcode fie ...

Encountering a syntax error when using a JSONP callback in AngularJS

Assistance Needed some.factory('homeService', ['$http', function($http){ return { getEvents : function(url) { return $http.jsonp(url); } } }]); Instructions homeService. ...

Manipulate a JSON object with JavaScript

Struggling to find a solution on my own. In my hidden field, I have some JSON data stored. To retrieve this data, I'm using the following syntax: $(document).ready(function() { var data = $("#result").text(); var j = JSON.parse(data); j.my_item.to ...

Add an array of keys and corresponding values into an existing array at a specified index

I am currently working with a multidimensional array in PHP, specifically an array of arrays. I need to insert additional keys and values after each existing key => value pair. Is there a method for accomplishing this? $scores= array(); $scores[] = a ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

Decoding a massive JSON file in PHP with json_decode

Currently, I am faced with the challenge of decoding a very large json file that is 222mb in size. It has come to my attention that I cannot simply use json_decode with file_get_contents() as it would require a significant amount of memory and currently r ...

Tips for transmitting JSON containing a byte array to a web API or Postman

I am seeking guidance on how to send data to both a Web API Postman for Web API While I can easily make simple GET Requests to my Web API using Postman, I am unsure about how to send a Byte Array. In Postman, I understand that it involves a PUT request. ...

Using TypeScript to Load JSON Data from a Folder

I'm a newcomer to TypeScript and encountering an issue. My task involves dynamically loading objects from a directory that houses multiple JSON files. The file names are generated through an export bash script populating the resource directory. I wan ...

Want to effortlessly retrieve a JSONObject from a "file.txt" or "file.json" file that is already residing in the system? Discover how to easily extract the JSON data without any hassle

Imagine I am trying to create a JSONObject from a file named "file.txt" or "file.json" located in my android asset folder. How can this be achieved? The desired outcome should look something like this: JSONObject json = new JSONObject(jsontxt); I hav ...

Using Java in Selenium WebDriver to pick a link at random

I am trying to randomly select a link from a page. I added an alert to confirm if the element is present. The page displayed 'a is displayed' but I encountered the following error on eclipse: Element is not currently visible and so may not be int ...

What is the most effective method for parsing JSON data that constantly changes?

Consider a scenario where you have a method that takes in two string arguments: public int Method(string expression, string variables) { ... } The string "expression" should contain a math expression (e.g. "1 + 2") that needs to be eva ...