What is the best way to load all Arraylists from the model function?

I am integrating the FlexibleAdapter library to retrieve data from a JSON API in my android studio project.

public void createHolderSectionsDatabase(int size, int headers) {
    databaseType = DatabaseType.MODEL_HOLDERS;
    HeaderHolder header = null;
    mItems.clear();
    int lastHeaderId = 0;
    for (int i = 0; i < size; i++) {
        header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
        mItems.add(newItemHolder(i + 1, header));
    }
}

private HeaderHolder newHeaderHolder(int i) {
    HeaderModel model = new HeaderModel("H" + i);
    model.setTitle("Header " + i);
    return new HeaderHolder(model);
}

private ItemHolder newItemHolder(int i, HeaderHolder header) {
    ItemModel model = new ItemModel("I" + i);
    model.setTitle("Holder Item " + i);
    model.setSubtitle("Subtitle " + i);
    return new ItemHolder(model, header);
}

The code above handles the loading of data by iterating over model items. However, I want to modify it to work with a JSON API like:

How can I update the code to achieve this transformation?

/*      for (int i = 0; i < size; i++) {
            header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
            mItems.add(newItemHolder(i + 1, header));
        }*/

For example:

    listArrayFromJSON = getArrayJSON(); //retrieve JSON with GSON request
    mItems.addAll(ListArrayFromJSON,header); //do not add`

Answer №1

If you're not familiar with the structure of your json string, you can make changes to the question or draw inspiration from below

public class DataContainer{
     private ArrayList<ItemContainer> itemsList; //name of json object
     private ArrayList<HeaderContainer> headerList; //name of json object

     public Arraylist<ItemContainer> getItemsList(){
        return itemsList;
     }

     public Arraylist<HeaderContainer> getHeaderList(){
        return headerList;
     }
}

DataContainer container = new Gson().fromJson(jsonString, DataHolder.class);
itemContainers.addAll(container.getItemsList());
headerContainers.addAll(container.getHeaderList());

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

What is the correct way to select a button with Xpath?

<td class="tdDiv"> <div class="divElem"> <ul class="ulElem"> <li role="presentation" class="ng-star-inserted"> <button type="button" tabindex="0" class="& ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Mastering the Art of Extracting HTML Text from JSON Files

I'm facing an issue in my react app where I can't read the HTML tags used in the content of a JSON file. Here's a snippet of the JSON file: [{ "_id": 9, "title":"Text 9", "subheader":"Dummy header 9", "im ...

Unable to convert JSON data to char array due to a NumberFormatException while using editText

I am attempting to parse JSON on Android, and after parsing the JSON, I want to convert the inputted ID in Edittext to a char array. However, I am encountering a NumberFormatException. I don't think this is a silly question, but where could the prob ...

Extracting Data from JSON Objects Using PHP

array(85) { [0]=> object(stdClass)#9 (18) { ["offer_id"]=> string(8) "12345678" ["offer_name"]=> string(39) "Offer Name" ["offer_desc"]=> string(209) "Offer Description" ["call_to_action"]=> string(57) "Of ...

Creating a mobile application for iPhone 4 that utilizes a sqlite database

I have been working on an app that involves storing JSON data in a SQLite3 database by creating and inserting the data programmatically. Everything is functional, but I am looking to improve the user experience by accessing the data from the local databa ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

Sending a cURL POST request to a Node.js express server running on an NGINX server resulted in a 502 error response

I am attempting to send a POST request to one of my node API routes. Strangely, only one of them seems to be working properly. I'm not certain whether this is an issue with NGINX, Node.js, or a combination of both. I have double-checked everything and ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

Tips for effectively incorporating NSOperation Queue in objective c

I have encountered an issue with the code below. I am utilizing NSOperationQueue to fetch post data from the server during the login process. My aim is to retrieve a response from the server 8 times. However, the implementation of NSOperationQueue seems to ...

Managing JSON data with tab fragments on android devices

I am a beginner in the world of Android development and I am currently working on accessing JSON data for my project. The app consists of two tabs within a viewpager - the first tab displays information about events while the second tab contains a custom l ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

Creating multiple Google markers based on addresses retrieved from a database using PHP

I have a requirement to display multiple Google markers on a map based on addresses stored in a database. I have already successfully loaded an XML file to retrieve latitude and longitude coordinates, but now I need assistance on how to create multiple m ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

json output odd results when writing decimal strings with leading zeros

Explaining my issue is a challenge because I can't create a simple example that replicates the error I'm encountering. However, I can describe the scenario. The following basic code snippet functions correctly: import json data = ("0.5 cup corn ...

Steps to create a dropdown select option using an AJAX call: When the data is fetched, it generates an array

How can I dynamically populate a dropdown with data from an array using jQuery and AJAX? <html> <script> $(document).ready(function() { $("#class_name").change(function(){ var class_id=$("#class_name").val(); ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

Evaluating the performance of a Heroku free server under stress conditions

I'm currently working on an Android app that has a backend hosted on a Heroku free server. The current response time for serving requests is 2 seconds. I'm curious to know how many users it can handle simultaneously. I've searched through v ...

What is the reason for needing to use utf8_decode prior to inserting a UTF8 string into MySQL?

I encountered a perplexing issue that I was able to resolve by experimenting with different options. However, the solution doesn't quite make sense to me... Here's the scenario: I am receiving JSON data from Facebook encoded in UTF-8. My databas ...