JSON data is being displayed in the spinner for just a single item

My spinner is supposed to display all of the supplier's names from a JSON file. I managed to retrieve the JSON data, store it in an ArrayList, and display it. However, I encountered an issue where only one item is displayed - usually the most recently added one.

Below is the code snippet that implements the spinner functionality:

@Override
    protected void onPostExecute(JSONObject json){
        if(json != null){
            try{
                result = json.getJSONArray("supplier");
                if(!result.toString().equals("[]")) {
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject source = result.getJSONObject(i);
                        String suppliers = source.getString("SupplierName");
                        //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();
                        spinnerArray =  new ArrayList<String>();
                        spinnerArray.add(suppliers);

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);

                        spinSupplier.setAdapter(adapter);
                    }


                } else {
                    Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
                }

            } catch (Exception e) {
                e.fillInStackTrace();
            }
        } else if(json == null) {
            Toast.makeText(PurchaseOrder.this, "NULL", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
        }

    }

JSON Data:

{"supplier":[{"SupplierID":"1","SupplierName":"Nike","Address":"161","City":"Caloocan","Region":"NCR","PostalCode":"1114","Phone":"0917123456","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d58505c54517d50">[email protected]</a>"},{"SupplierID":"2","SupplierName":"Adidas","Address":"36 C","City":"Quezon City","Region":"NCR","PostalCode":"1115","Phone":"7493857","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11747c70787d74">[email protected]</a>"},{"SupplierID":"3","SupplierName":"NIEK","Address":"","City":"Quezon City","Region":"ARMM","PostalCode":"1104","Phone":"709-2227","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e6e1ede3e6e1ed">[email protected]</a>"}]}

Answer №1

To properly display the spinner with suppliers, make sure to set the adapter after populating the array with items like this:

@Override
        protected void onPostExecute(JSONObject json){
            if(json != null){
                try{
                    result = json.getJSONArray("supplier");
                    if(!result.toString().equals("[]")) {
                        supplierList = new ArrayList<String>();
                        for (int i = 0; i < result.length(); i++) {
                            JSONObject source = result.getJSONObject(i);
                            String suppliers = source.getString("SupplierName");
                            //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();
                            supplierList.add(suppliers);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                    PurchaseOrder.this, android.R.layout.simple_spinner_item, supplierList);

                            spinSupplier.setAdapter(adapter);

                    } else {
                        Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            } else if(json == null) {
                Toast.makeText(PurchaseOrder.this, "NULL", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
            }

        }

Answer №2

Here are two points to consider:

  1. The placement of the array initialization
    spinnerArray =  new ArrayList<String>();

It is recommended to have it outside and before the for loop.

  1. The positioning of the adapter setting
    spinSupplier.setAdapter(adapter);

You should place it outside and after the for loop.

Proposed Solution:

spinnerArray =  new ArrayList<String>();
   for (int i = 0; i < result.length(); i++) {
                        JSONObject source = result.getJSONObject(i);
                         String suppliers = source.getString("SupplierName");
                          //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();

                          spinnerArray.add(suppliers);


       }
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                            PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);
            spinSupplier.setAdapter(adapter);

Answer №3

Test out this example for loop:

Make sure to set the adapter after the for loop and create an array object before it.

spinnerArray =  new ArrayList<String>();
for (int i = 0; i < result.length(); i++) {
    JSONObject source = result.getJSONObject(i);
    String suppliers = source.getString("SupplierName");
   //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();

    spinnerArray.add(suppliers);
    }
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                        PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);

      spinSupplier.setAdapter(adapter);

Answer №4

To properly update your spinner with the new data, make sure to adjust the location of the setAdapter code and initialize your ArrayList correctly.

      @Override
protected void onPostExecute(JSONObject json){
    if(json != null){
        try{
            result = json.getJSONArray("supplier");
            if(!result.toString().equals("[]")) {
               spinnerArray =  new ArrayList<String>();
                for (int i = 0; i < result.length(); i++) {
                    JSONObject source = result.getJSONObject(i);
                    String suppliers = source.getString("SupplierName");
                    //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();

                    spinnerArray.add(suppliers);

                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                            PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);

                            //Ensure the list agrees with the adapter

                spinSupplier.setAdapter(adapter);

            } else {
                Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.fillInStackTrace();
        }
    } else if(json == null) {
        Toast.makeText(PurchaseOrder.this, "NULL", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(PurchaseOrder.this, "ERROR", Toast.LENGTH_SHORT).show();
    }

}

Answer №5

Ensure to define the spinnerArray variable outside of the for loop

spinnerArray =  new ArrayList<String>();

Remember to create the adapter after the for loop ends

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);

                        spinSupplier.setAdapter(adapter);

Answer №6

I suspect that the issue lies in your constant reinitialization of the ArrayList. Please review your code carefully to ensure this is not happening repeatedly.

if(!result.toString().equals("[]")) {
         for (int i = 0; i < result.length(); i++) {
              JSONObject source = result.getJSONObject(i);
              String suppliers = source.getString("SupplierName");
              //Toast.makeText(PurchaseOrder.this, "Suppliers: "+suppliers, Toast.LENGTH_SHORT).show();

              spinnerArray.add(suppliers);
              ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                PurchaseOrder.this, android.R.layout.simple_spinner_item, spinnerArray);

              spinSupplier.setAdapter(adapter);
         }

Please ensure you move the following line:

spinnerArray =  new ArrayList<String>(); 

Above this line:

if(!result.toString().equals("[]"))

If you make this adjustment, it should resolve the issue.

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

Retrieve the initial key from an object in javascript

Though seemingly simple, I'm stuck on finding the solution: Within my jquery object (displayed in console.log): { id_ship: "1", id_company: "1", code: "DE", // other properties... } My goal is to extract the first key from th ...

Is the encoding logical when used in Python for JSON or YAML files?

I attempted to store this dictionary in a json or yaml file: d = {'name': 'María Gómez', 'message': '¡Es una caña atómica!'} with open(file, 'wt', encoding='iso8859-1') as file: json.dump( ...

"Optimizing Long Polling for Maximum Efficiency: Tips for utilizing php, Jquery

Hey everyone, I'm looking to implement real-time flash message notifications for users when they receive a new private message in their inbox. What is the most effective way to achieve this using technologies like PHP 5.3, jQuery, and JSON? I prefer ...

ListView Adapter fails to display Android TimeStamp values

Whenever my ListView refreshes or reloads, the timestamp is consistently showing as Jan 17, 1970. Why does this keep happening? The value of my timestamp 1441339200 = 2015-09-04 Snippet of code for the timestamp CharSequence timeAgo = DateUtils ...

Obtain the dimensions of the outermost layer in a JSON file

Could you please help me extract the dimensions (600*600) of the outermost layer from the JSON below dynamically? { "path" : "shape\/", "info" : { "author" : "" }, "name" : "shape", "layers" : [ { ...

Converting complex JSON structures to Java objects with Jackson's dynamic nested parsing

i'm struggling with parsing json data I have a json string that contains nested elements and I need to convert it into a java object. The structure of the string is quite complex and dynamic, so I'm wondering how to efficiently handle this using ...

How can I understand the result if JSON data is getting returned as undefined? What is the solution to

I am currently dealing with a dataset that contains location data. I have successfully transformed this data into latitude and longitude values through the GetLocation method. However, upon returning to the html page, the data appears to be undefined. Can ...

Creating an object in AngularJS by merging data from three separate API calls

I am looking to develop a Jenkins dashboard using AngularJS. I am considering combining data from three different API calls to create an object that can be used in the HTML file with ng-repeat, but I'm not sure if this is the best approach. The desir ...

Searching for tables data by employing the Curl command

Seeking assistance with parsing data from a website. The JSON request runs successfully in the command line but encounters issues when attempting to execute it on Android: The request: "curl '' -H 'Host: billetterie.ctm.ma' -H &apo ...

A Guide to Replacing a json Field with Null and Inserting it into a PostgreSQL Database

I have thoroughly examined the available options discussed in this context, but I find that most of them do not adequately address my specific situation. In my scenario, I import this information into a database where the field is designated as SMALLINT. H ...

Module ‘gulp’ could not be located

Whenever I try to execute the ionic build android command, it keeps showing me an error message: WARNING: ionic.project has been updated to ionic.config.json, so you need to rename it. Oops! It seems like there's a missing module in your gulpfile: Mo ...

I am encountering the org.json.JSONException error message stating that there is no value for a specific item in my JSON array

Despite having "feels_like" in my JSON array, the error log is indicating that it is not present. CODE: protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject jsonObject = new JSONObject(s); ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

The promise catch method does not handle JSON parsing correctly

Utilizing Angular's Http to interact with my API has been successful for handling responses with a status of 200. The data is parsed correctly and outputted as expected within the first .then() block. However, when encountering an error with a status ...

Steps for accessing a specific key value from a hashmap with a freemarker template

In the code below, I am setting key values into a hashmap within the main function. How can I format the freemarker template to only read one specific key value instead of iterating through the entire list? import freemarker.template.TemplateException; ...

Is there a way to detect modifications in a JSON API using Django or Android?

I've integrated djangorestframework for my api and am currently developing an Android App that interacts with the api by fetching and posting data. I'm interested in finding a way to detect changes in json data from the api. For example, in a cha ...

Use jq to denote the current position within a loop

I am faced with a situation where I have two separate log files named log.json and messages.json. The log file is structured as follows: {"msg": "Service starting up!"} {"msg": "Running a job!"} {"msg": "Error detected!"} The messages file has the fol ...

Parsing large numbers in JSON data using the json_decode function

Facing an issue while decoding a json string The PHP version being used is 5.4.4-7 and the operating system is Debian amd64. Here is the JSON string: {"status":"success","account":{"buy_title":"KGP ID","birthday":0,"sex":0,"phone_number":"","avatar":"ht ...

Utilizing Python to extract data from a JSON file

I have been working on reading a JSON file in Python and have run into an issue where some top values are being skipped. I am currently debugging to identify the root cause of this problem. Here is the code snippet: data = json.load(open('pre.txt&apo ...

Retrieve targeted information from the Coin Market Cap API by extracting specific data values using an array

I am looking to retrieve the symbol and other details using the "name" from my array. $.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) { var crypto = [ "Ethereum", "Ripple", "Tron", ]; // used for arr ...