Asynchronous Task paired with JSON, the onSuccess method fails to provide any returns

Here is my query: I'm facing an issue with the code in my AsyncTask function that fetches values from a JSONObject through a webservice. Despite successfully filling a List with data from the JSON in the onSuccess method, the "result" turns out to be null in the onPostExecute method of the AsyncTask.

private class FetchCategories extends AsyncTask<String, Void, List<Category>> {

        private int num_cat_subcat; // category count

        @Override
        protected List<Category> doInBackground(String... arg0) {
            AsyncHttpClient client = new AsyncHttpClient();
            client.get(arg0[0], null, new JsonHttpResponseHandler() {

                public void onSuccess(JSONObject data) {
                    try {
                        JSONObject response = data.getJSONObject("response");
                        JSONArray categories = response
                                .getJSONArray("categories");

                        // elements count
                        num_cat_subcat = categories.length();

                        for (int i = 0; i < categories.length(); i++) {
                            JSONObject item = (JSONObject) categories
                                    .getJSONObject(i);

                            if (item.getString("id").equalsIgnoreCase(
                                    "4d4b7105d754a06376d81259")) {
                                JSONArray subcategories = item
                                        .getJSONArray("categories");

                                // Category --> id, name, pluralName, shortName,
                                // icon_prefix, icon_suffix, primary, parentId
                                Category newItem = new Category(item
                                        .getString("id"), item
                                        .getString("name"), item
                                        .getString("pluralName"), item
                                        .getString("shortName"), null, null,
                                        null);
                                listCategories.add(newItem);
                                newItem = null;

                                if (subcategories.length() > 0) {
                                    // Count subcategories.
                                    num_cat_subcat += subcategories.length();

                                    for (int j = 0; j < subcategories.length(); j++) {
                                        JSONObject subitem = (JSONObject) subcategories
                                                .getJSONObject(j);

                                        Category newSubItem = new Category(
                                                subitem.getString("id"),
                                                subitem.getString("name"),
                                                subitem.getString("pluralName"),
                                                subitem.getString("shortName"),
                                                null, null, item
                                                        .getString("id"));
                                        listCategories.add(newSubItem);
                                        newSubItem = null;
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        // Handle exception
                        e.printStackTrace();
                    }
                }

                public void onFailure(Throwable arg0) {
                    // Handle failure
                }
            });
            return listCategories;
        }

        @Override
        protected void onPostExecute(List<Category> result) {
            Log.i("result", result.toString());

            for (int k = 0; k < result.size(); k++) {
                ALLOFTHEM += result.get(k).getId();
                if (k < result.size() - 1) {
                    ALLOFTHEM += ",";
                }
            }

        }

    }

Answer №1

When utilizing the loopj android-async-http library, there is no necessity to employ the AsyncTask class for retrieving data from a server within the doInBackground method and updating the UI in onPostExecute. This is due to the fact that the onSuccess method automatically runs on the UI Thread post background processing. You can achieve this without using AsyncTask by following this example:

 AsyncHttpClient client = new AsyncHttpClient();
 client.get("Insert URL Here", null, new JsonHttpResponseHandler() {
     @Override
     public void onSuccess(JSONObject data) {
          // Implement your ListView updates here
      }
    @Override
    public void onFailure(Throwable arg0, JSONObject arg1) {
        // Handle any failures

         super.onFailure(arg0, arg1);

    }
  });

Answer №2

onPostExecuted gets triggered once the doInBackground method completes its execution. If the retrieve operation of AsyncHttpClient is non-blocking, then onPostExecuted will be invoked before onSuccess processes the outcome

Answer №3

When onPostExecuted is called before onSuccess parses the result, make sure to include a display statement in your loop or troubleshoot the code by debugging it.

    Log.e("Test", item.getString("id"));//include this inside the for Loop

Additionally, add this line before starting your for loop:

   listCategories = new List<Category>();

Hopefully, this advice proves helpful.

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

Posting data in ASP.NET Core WebAPI can only be done through the POST method

One of the projects I have worked on involves creating non-core web API projects to interact with mobile apps. For instance, I established a controller named Data with a method called Search as illustrated below. This project is set up to handle JSON data ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology ...

JSONKit: generating a string in JSON format

Is it possible to convert NSDictionary's and NSArrays to JSON format using JSON Kit? If so, how can this be done? ...

The status is currently not defined when attempting to retrieve JSON data and display it on individual pages for each piece of data

I have written some code where I am trying to display the attributes of a selected product from my product page based on its ID. For example, when a product is clicked, it should redirect to a URL like /#/product/2 and display all the attributes of the pro ...

Is it possible to utilize Python to execute a function on a JSON data point?

Currently, I am working on parsing a JSON file where I need to perform an operation that involves subtracting 100 from the yardLine key in any element with a value of "ORE" in the key named "homeAbbr". The outcome can either update the original yardLine ke ...

Issues Persist with Updating mySQL Database using PHP

I've been attempting to insert location data into a MySQL database using my PHP server from the TripTracker Android App. However, despite trying different approaches in PHP, I have not been successful so far. Any assistance would be much appreciated. ...

"Error: Unable to determine the type id during the deserialization process" encountered while attempting to deserialize a subclass

I am currently working on integrating JsonSubTypes into my project and I would like to implement a graceful handling mechanism for unrecognized subtypes. The version of Jackson that I am using is 2.9.7, and upgrading is not an option due to dependencies on ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Encountering a 415 Unsupported Media Type exception while processing a multipart request in Spring Boot REST with a combination of JSON and

I am encountering an issue with uploading a multi-part file along with a JSON object in Postman while using Spring Boot version 1.5.2.RELEASE. I keep getting a 415 Unsupported Media Type exception. Below is my controller class: @RestController @RequestMap ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

Exploring the method of extracting data from a JSON response containing various objects

I am working with a REST API that returns multiple objects within a single JSON response. My goal is to extract specific data from all objects in the response using Python 2.7. How can I efficiently retrieve the "key", "name", and "emailAddress" for each ...

Load JSON file in ExtJs using Ext.Ajax.request method: A step-by-step guide

I am exploring a new approach to loading a json file in ExtJs. In the past, I used jQuery to achieve this functionality as shown in the code snippet below: Ext.define('app.store.Students', { extend: 'Ext.data.Store', model: &ap ...

An issue occurred when attempting to convert the XML response to Json format

Trying to convert XML response to JSON. I am making a request to an API endpoint that sends back XML data. After receiving the data, I successfully convert it to a json string. However, when attempting to deserialize the json string, I encounter an excepti ...

The JSON.parse function encounters an error in Chrome, but functions properly in Firefox

While this code snippet functions as expected on Firefox, it encounters an error on Chrome. How can this discrepancy be explained? VM317:1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () Script.js $(document).ready(function(){ $( ...

Looping through JSON objects using for loop

I am trying to implement a for loop with the following json data. The console.log function is working properly, but when I use it in the javascript function, it does not work as expected. I want the for loop to be functional within the javascript function ...

Tips for activating debugging in Electron Main and Renderer with VSCode while utilizing npm-run-all

Utilizing npm-run-all to execute both npm start and npm electron ., I am seeking guidance on setting up debugging with VSCode. Currently, my settings are as follows, but upon initiating debugging, I only receive: C:\Program Files\nodejs\npm ...

iOS6: Using POST method to send JSON data from an iPhone to a REST API

I have encountered an issue while trying to send data in JSON format to a REST API. The web service does not return any data when sending a parameter and instead shows the error message: Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The op ...

How can complex POST parameters be structured in a RESTful API?

For my current project, I am working on developing an application utilizing node.js along with express. This application involves a feature that allows users to subscribe to lists of items. Each subscription includes specific options such as minimum scores ...