将数据从JSON ArrayList加载到微调器中

时间:2016-01-05 13:05:14

标签: java android json arraylist android-spinner

我似乎无法弄清楚这一点,因为我只是这个Android内容的初学者。

我的应用程序通过JSON从我的WebAPI获取客户名称。

现在我正在尝试将其加载到微调器中,但是如何在那里加载我的JSON arraylist?

我尝试在其中加载custTable,但它现在在微调器中显示“com.jetron.jetronbuitendienst.CustomerDetailsTable .....”。

我的代码:

  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);
        }

    }
}

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

3 个答案:

答案 0 :(得分:1)

这对我有用

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();
                            }
                    });

                }

答案 1 :(得分:1)

检查API参考here

ArrayAdapter使用Object.toString()来填充视图。

在代码中,对象CustomerDetailsTable不会覆盖toString()函数,所以它只打印类的名称。

答案 2 :(得分:1)

好吧,因为你得到了这个:

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

这意味着你有一个名为Value的数组。所以你能做的就是:

声明公共变量:

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

然后将代码修改为:

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());

    }

希望它有所帮助!!!