使用Volley解析JSON并在自动完成文本框中展示数据求助
解决自动完成文本框无法加载JSON数据的问题
嘿,我看了你的代码,发现核心问题出在数据类型不匹配上,这才导致自动完成文本框没法正常显示内容。让我一步步给你梳理解决办法:
问题根源分析
你定义的responseList是List<String>类型,但代码里却往里面添加了ListCustomer对象——而ArrayAdapter<String>只能处理字符串元素,自然没法正确解析和显示内容。
快速修正步骤
- 直接提取字符串存入List:不需要创建
ListCustomer对象,直接把JSON里的c_name字符串添加到responseList即可,因为自动完成框只需要显示文本。 - 使用正确的上下文:创建
ArrayAdapter时,尽量用当前Activity的上下文(比如YourActivity.this)替代getApplicationContext(),避免布局显示异常。 - 增强错误处理:原代码中
volleyError.getMessage()可能返回null,需要添加空判断避免Toast显示异常。
修正后的完整代码
public void ListCustomernames(){ StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_listpopupwindow, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONArray array = new JSONArray(response); List<String> responseList = new ArrayList<String>(); for(int i=0;i< array.length();i++){ JSONObject jsonObject = array.getJSONObject(i); // 直接提取c_name字符串存入List String customerName = jsonObject.getString("c_name"); responseList.add(customerName); } // 使用Activity上下文创建适配器 ArrayAdapter<String> adapter = new ArrayAdapter<String>(YourActivity.this, android.R.layout.simple_dropdown_item_1line, responseList); mVoiceInputTv.setAdapter(adapter); mVoiceInputTv.setThreshold(1); // 输入1个字符就触发自动补全 } catch (JSONException e) { e.printStackTrace(); Toast.makeText(YourActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { // 处理错误时避免空指针 String errorMsg = volleyError.getMessage() != null ? volleyError.getMessage() : "请求失败,请检查网络"; Toast.makeText(YourActivity.this, errorMsg, Toast.LENGTH_SHORT).show(); } }); RequestQueue requestQueue= Volley.newRequestQueue(this); requestQueue.add(stringRequest); }
进阶优化(如果需要保留ListCustomer类)
如果后续需要用到自定义对象的其他属性,可以自定义ArrayAdapter来适配ListCustomer:
// 自定义适配器类 public class CustomerAdapter extends ArrayAdapter<ListCustomer> { public CustomerAdapter(Context context, List<ListCustomer> customers) { super(context, android.R.layout.simple_dropdown_item_1line, customers); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView textView = view.findViewById(android.R.id.text1); // 显示ListCustomer中的名称字段 textView.setText(getItem(position).getName()); return view; } } // 在请求回调中使用自定义适配器 List<ListCustomer> customerList = new ArrayList<>(); for(int i=0;i< array.length();i++){ JSONObject jsonObject = array.getJSONObject(i); ListCustomer customer = new ListCustomer(jsonObject.getString("c_name")); customerList.add(customer); } CustomerAdapter adapter = new CustomerAdapter(YourActivity.this, customerList); mVoiceInputTv.setAdapter(adapter);
内容的提问来源于stack exchange,提问作者yaseer shaikh
相关产品推荐
相关产品推荐

