Yoshi
Yoshi

Reputation: 341

load data from JSON ArrayList into spinner

I can't seem to figure this out, since im just a beginner with this android stuff.

My app gets the customer names from my WebAPI via JSON.

Now I am trying to load it into a spinner, but how can I load my JSON arraylist in there?

I tried loading custTable in it but its shows "com.jetron.jetronbuitendienst.CustomerDetailsTable....." in the spinner now.

My Code:

  package com.jetron.jetronbuitendienst;

import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Gegevens extends Main {

    String Naam;
    Spinner spCustomers;
    private ArrayList<CustomerDetailsTable> Klanten;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gegevens);
        new AsyncLoadCustDetails().execute();
        spCustomers = (Spinner) findViewById(R.id.spKlanten);

    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */

    protected class AsyncLoadCustDetails extends
            AsyncTask<Void, JSONObject, ArrayList<CustomerDetailsTable>> {
        ArrayList<CustomerDetailsTable> custTable = null;

        @Override
        protected ArrayList<CustomerDetailsTable> doInBackground(Void... params) {
            // TODO Auto-generated method stub

            RestAPI api = new RestAPI();
            try {

                JSONObject jsonObj = api.GetCustomerDetails();

                JSONParser parser = new JSONParser();

                custTable = parser.parseCustomerDetails(jsonObj);

                Log.d("Customers: ", jsonObj.toString());

            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("AsyncLoadCustDetails", e.getMessage());

            }

            return custTable;
        }

        @Override
        protected void onPostExecute(ArrayList<CustomerDetailsTable> result) {
            // TODO Auto-generated method stub

// Application of the Array to the Spinner
            ArrayAdapter<CustomerDetailsTable> spinnerArrayAdapter = new ArrayAdapter<CustomerDetailsTable>(getApplicationContext(),   android.R.layout.simple_spinner_item, custTable);
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
            spCustomers.setAdapter(spinnerArrayAdapter);
        }

    }
}

This is the jsonObj: D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}

Upvotes: 1

Views: 1166

Answers (3)

Kostas Drak
Kostas Drak

Reputation: 3260

Well Since you are getting this:

D/Customers:: {"Successful":true,"Value":[{"Naam":"Google"},{"Naam":"Apple"},{"Naam":"AVN"},{"Naam":"Bemd"}]}

That implies that you are having an array that is called Value. So what you can do is this:

declare public variables :

private JSONObject jsonChildNode;
private JSONArray jsonMainNode;
private String name;

and then modify your code as:

try {
       JSONObject jsonObj = api.GetCustomerDetails();
       JSONParser parser = new JSONParser();
       custTable = parser.parseCustomerDetails(jsonObj);
       Log.d("Customers: ", jsonObj.toString());
       jsonMainNode = jsonObj.optJSONArray("Value");
       for (int i = 0; i < jsonMainNode.length(); i++) {
          jsonChildNode = jsonMainNode.getJSONObject(i);
          name = jsonChildNode.optString("Naam");
       }
       //and then you can add the name to a List<String> which will contain all the values of each item in the Value JSON Array.
    } catch (Exception e) {
       // TODO Auto-generated catch block
       Log.d("AsyncLoadCustDetails", e.getMessage());

    }

Hope it helps!!!

Upvotes: 1

fuxi chu
fuxi chu

Reputation: 424

Check API reference here.

ArrayAdapter uses the Object.toString() to fill the view.

Here in the code, with the Object CustomerDetailsTable does not override the toString() function, So it just print the name of the class.

Upvotes: 1

Aditya Vyas-Lakhan
Aditya Vyas-Lakhan

Reputation: 13555

That worked for me

class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {

              ArrayAdapter<String> adaptercountry ;
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                }
                protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
                    ServiceHandler sh = new ServiceHandler();

                    // Making a request to url and getting response
                    data = new ArrayList<HashMap<String, String>>();
                    String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);

                    Log.d("Response: ", "> " + jsonStr);

                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node your array 
                            country_list = jsonObj.getJSONArray(COUNTRY_LIST);

                            // looping through All Contacts
                            for (int i = 0; i < country_list.length(); i++) {
                                JSONObject c = country_list.getJSONObject(i);

                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(OP_ID, c.getString(OP_ID));
                                map.put(OP_NAME,c.getString(OP_NAME));



                                data.add(map);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                    return data;
                }


                protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

                    super.onPostExecute(result);


                    String[] arrConuntry=new String[data.size()];
                    for(int index=0;index<data.size();index++){
                              HashMap<String, String> map=data.get(index);
                          arrConuntry[index]=map.get(OP_NAME);
                     }  


                     // pass arrConuntry array to ArrayAdapter<String> constroctor :
                    adaptercountry = new ArrayAdapter<String>(getActivity(),
                                        android.R.layout.simple_spinner_dropdown_item,
                                                                              arrConuntry);
                    spcountry.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View w) {
                              new AlertDialog.Builder(getActivity())
                              .setTitle("Select")
                              .setAdapter(adaptercountry, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    spcountry.setText(adaptercountry.getItem(which).toString());

                                     try {
                                        cname=country_list.getJSONObject(which).getString("operator_id");
                                         Log.d("Response: ", "> " + cname);

                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                  dialog.dismiss();
                                }
                              }).create().show();
                            }
                    });

                }

Upvotes: 1

Related Questions