You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将两个JSON数组分别设置到两个Spinner中?

Solution to Populate Two Spinners from API JSON Response

Let’s walk through completing your code to parse the API response and populate your two Spinners correctly. Here’s a step-by-step implementation tailored to your use case:

Step 1: Complete the AsyncHttpClient Request & JSON Parsing

First, finish your getdata() method with proper response handling and parsing logic:

private void getdata() {
    if (isNetworkAvailable()) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(800000);
        
        // Replace with your actual API endpoint URL
        String apiUrl = "your_api_endpoint_url";
        
        client.get(apiUrl, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    // Convert raw response to a readable string
                    String responseString = new String(responseBody);
                    
                    // Parse the JSON array (your response is wrapped in an array)
                    JSONArray responseArray = new JSONArray(responseString);
                    // Extract the first (and only) object from the array
                    JSONObject responseObj = responseArray.getJSONObject(0);
                    
                    // Validate the API status
                    if (responseObj.getString("status").equals("success")) {
                        // Pull out the two data arrays from the response
                        JSONArray data1 = responseObj.getJSONArray("Data1");
                        JSONArray data2 = responseObj.getJSONArray("Data2");
                        
                        // Convert JSON arrays to ArrayLists for Spinner adapters
                        ArrayList<String> spinner1Items = convertJSONArrayToArrayList(data1);
                        ArrayList<String> spinner2Items = convertJSONArrayToArrayList(data2);
                        
                        // Populate each Spinner
                        setupSpinner(spinner1Items, yourFirstSpinner); // Replace with your first Spinner instance
                        setupSpinner(spinner2Items, yourSecondSpinner); // Replace with your second Spinner instance
                    } else {
                        Toast.makeText(getApplicationContext(), "API request failed", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Failed to parse response", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                error.printStackTrace();
                Toast.makeText(getApplicationContext(), "Network request failed", Toast.LENGTH_SHORT).show();
            }
        });
    } else {
        Toast.makeText(getApplicationContext(), "No network connection", Toast.LENGTH_SHORT).show();
    }
}

Step 2: Helper Method to Convert JSONArray to ArrayList

This reusable method converts the JSON arrays into a format that works with Spinner adapters:

private ArrayList<String> convertJSONArrayToArrayList(JSONArray jsonArray) throws JSONException {
    ArrayList<String> itemList = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        itemList.add(jsonArray.getString(i));
    }
    return itemList;
}

Step 3: Helper Method to Setup Spinner Adapter

This method takes your item list and Spinner instance to apply the adapter:

private void setupSpinner(ArrayList<String> items, Spinner spinner) {
    // Create a default ArrayAdapter for the Spinner
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_spinner_item, items);
    // Set the layout for the dropdown menu
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Attach the adapter to the Spinner
    spinner.setAdapter(adapter);
}

Important Reminders:

  • Replace your_api_endpoint_url with your actual API address.
  • Replace yourFirstSpinner and yourSecondSpinner with the Spinner objects you’ve initialized via findViewById in your activity/fragment.
  • The code includes error handling for network issues, JSON parsing errors, and API status checks to keep your app stable.

内容的提问来源于stack exchange,提问作者Sonal Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:14:25