有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将数据从JSON ArrayList加载到spinner中

我似乎不明白这一点,因为我只是一个安卓的初学者

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

现在我正试图将其加载到一个微调器中,但如何在其中加载JSON arraylist呢

我尝试在其中加载custable,但它显示“com.jetron.jetronbuitendianst.CustomerDetailsTable…”现在在旋转器中

我的代码:

  package com.jetron.jetronbuitendienst;

import 安卓.annotation.TargetApi;
import 安卓.os.AsyncTask;
import 安卓.os.Build;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.widget.ArrayAdapter;
import 安卓.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 安卓.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(),   安卓.R.layout.simple_spinner_item, custTable);
            spinnerArrayAdapter.setDropDownViewResource(安卓.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) 个答案

  1. # 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();
                                }
                        });
    
                    }
    
  2. # 2 楼答案

    检查API引用here

    ArrayAdapter使用该对象。toString()以填充视图

    在代码中,使用对象CustomerDetailsTable不会重写toString()函数,因此它只打印类的名称

  3. # 3 楼答案

    既然你得到了这个:

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

    希望对你有帮助