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

Android中如何通过JSON文件为Searchable Spinner加载客户列表

Populating Searchable Spinner from JSON File

Since you already have the Searchable Spinner dependency set up (compile 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1') and confirmed basic functionality works, let’s walk through updating your code to load customer data from a JSON file.

Step 1: Prepare Your Customer JSON File

First, create a customers.json file (place it in the src/main/assets folder—create the assets folder if it doesn’t exist) with your customer data. Example structure:

[
  {"id": 1, "name": "John Doe"},
  {"id": 2, "name": "Jane Smith"},
  {"id": 3, "name": "Bob Johnson"}
]

Step 2: Create a Customer Model Class

Make a simple data class to map the JSON objects to usable Java objects:

public class Customer {
    private int id;
    private String name;

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    // Override toString to display the customer name in the spinner
    @Override
    public String toString() {
        return name;
    }
}

Note: Overriding toString() is critical—this is what the Searchable Spinner uses to display each item.

Step 3: Update Your Activity/Fragment to Load JSON via AsyncTask

Modify your existing code to read, parse the JSON, and populate the spinner:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class YourCustomerActivity extends AppCompatActivity {
    private SearchableSpinner searchableSpinner;
    private List<Customer> customerList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_fragment_layout);

        searchableSpinner = findViewById(R.id.searchable_spinner);
        // Execute AsyncTask to load JSON data
        new LoadCustomersTask().execute();
    }

    private class LoadCustomersTask extends AsyncTask<Void, Void, List<Customer>> {

        @Override
        protected List<Customer> doInBackground(Void... voids) {
            customerList = new ArrayList<>();
            try {
                // Read JSON file from assets folder
                InputStream inputStream = getAssets().open("customers.json");
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder jsonStringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonStringBuilder.append(line);
                }
                inputStream.close();
                reader.close();

                // Parse JSON array into Customer objects
                JSONArray jsonArray = new JSONArray(jsonStringBuilder.toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject customerJson = jsonArray.getJSONObject(i);
                    Customer customer = new Customer();
                    customer.setId(customerJson.getInt("id"));
                    customer.setName(customerJson.getString("name"));
                    customerList.add(customer);
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return customerList;
        }

        @Override
        protected void onPostExecute(List<Customer> customers) {
            if (customers != null && !customers.isEmpty()) {
                // Set up adapter for the Searchable Spinner
                ArrayAdapter<Customer> adapter = new ArrayAdapter<>(YourCustomerActivity.this,
                        android.R.layout.simple_spinner_item, customers);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                searchableSpinner.setAdapter(adapter);

                // Optional: Add selection listener to handle user choices
                searchableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Customer selectedCustomer = (Customer) parent.getSelectedItem();
                        Toast.makeText(YourCustomerActivity.this, 
                                      "Selected: " + selectedCustomer.getName(), 
                                      Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // Handle case where no item is selected
                    }
                });
            } else {
                Toast.makeText(YourCustomerActivity.this, 
                              "Failed to load customer data", 
                              Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Step 4: Confirm Layout Setup

Ensure your layout XML includes the Searchable Spinner correctly:

<com.toptoche.searchablespinnerlibrary.SearchableSpinner
    android:id="@+id/searchable_spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Select a customer"/>

Key Tips

  • Error Handling: The AsyncTask includes basic exception handling, but you can expand it to show user-friendly error messages for production.
  • JSON Source: If your JSON comes from a remote API instead of a local file, replace the asset reading code with an HTTP request (using libraries like OkHttp or Retrofit for cleaner code).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:55:42