【问题标题】:Load converted List<String> into listview将转换后的 List<String> 加载到列表视图中
【发布时间】:2018-04-05 15:48:22
【问题描述】:

我的 Android 应用程序中有一个填充列表 (ServicesList) - 类型为 String、自定义类 (ServiceRecord.java)、自定义适配器 () 和自定义列表视图 (lvS)。

我已经能够通过以下代码将 List 变量转换为自定义列表:

    List<ServiceRecord> objectList = (List)servicesList;
    ServicesCustomAdapter adapter = new ServicesCustomAdapter(this, objectList);
    lvS.setAdapter(adapter);  

我想将转换后的列表设置到列表视图中,但我收到错误“java.lang.classexception: java.lang.String cannot be cast to app.services.net.ServiceRecord”。有人可以告诉我如何去做吗?

我的自定义类如下:

public class ServiceRecord {
    private String service;


    public String getService() {
        return service;
    }
    public void setService(String service) {
        this.service = service;
    }

}

还有我的自定义适配器:

public class ServicesCustomAdapter extends ArrayAdapter<ServiceRecord>{
    private List<ServiceRecord> items;

    public ServicesCustomAdapter(Context context, List<ServiceRecord> items) {
        super(context, R.layout.list_service, items);
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if(v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.list_service, null);            
        }

        ServiceRecord bbs = items.get(position);

        if(bbs != null) {
            //TextView un = (TextView)v.findViewById(R.id.list);
            TextView tvservice = (TextView)v.findViewById(R.id.tvservice);


            if(tvservice != null) tvservice.setText(bbs.getService());

        }

        return v;
    }

}

【问题讨论】:

  • 错误是不言自明的。向下转换期间对象类型不匹配。
  • 我该如何解决这个问题?请告诉我怎么做。

标签: android list listview


【解决方案1】:

您必须创建一个包含ServiceRecord 类对象的List。试试下面的代码。

 List<ServiceRecord> objectList = new ArrayList<>();
    for (String item: servicesList){
        ServiceRecord sr=new ServiceRecord();
        sr.setService(item);
        objectList.add(sr);
    }
    ServicesCustomAdapter adapter = new ServicesCustomAdapter(this, objectList);
    lvS.setAdapter(adapter);

PS:虽然你的ServiceRecord 类只有一个属性。那么为什么不直接使用List&lt;String&gt; 来完成列表适配器呢。

【讨论】:

  • 那么,objectList 的大小 = 0?
  • 仅供参考,我将在 ServiceRecord 类中添加更多属性。这就是为什么它需要这种方法。非常感谢我的朋友
  • 是的,我就是这样。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多