java.lang.Boolean不能强制转换为ba.store.models.Merchants

时间:2016-09-29 08:56:00

标签: java android android-studio android-fragments

我有listview adapter在片段中扩展BaseAdapter。在那个listview上,我实施了scrollview侦听器,可以检测用户何时到达listview的末尾。在这种情况下,将加载更多数据。此外,我在该片段上有一个按钮,单击该按钮将重置所有过滤器并使用起始项重新加载列表。问题是当用户在同一时间向下滚动时(在加载新元素之前)按下按钮应用程序将崩溃并出现以下错误:

java.lang.Boolean cannot be cast to ba.store.models.Merchants

这是它分崩离析的代码:

 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    Integer identity;
    ViewHolder viewHolder = null;
    notifyDataSetChanged();
    if (convertView == null) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sales_place_item, parent, false);
        viewHolder = new ViewHolder(view);
        view.setTag(viewHolder);

    } else {
        view = convertView;
        viewHolder = (ViewHolder) view.getTag();

    }
    Merchants merchants = (Merchants) getItem(position);
    if (merchants != null) {
        identity = merchants.getMerchantId();
        viewHolder.merchant_name.setText(merchants.getMerchantName());
        viewHolder.merchant_category.setText(merchants.getCategoryName().toUpperCase());
        viewHolder.border_limit.setText(merchants.getBorderLimitAmount().toString() + " KM");
        viewHolder.end_loyalty.setText(merchants.getEndLoyaltyPoints().toString());
        viewHolder.begin_loyalty.setText(merchants.getStartLoyaltyPoints().toString());

        if (merchants.getImagePath().equals(""))
            Picasso.with(view.getContext()).load(R.drawable.placeholder_sales).fit().into(viewHolder.merchant_image);
        else
            Picasso.with(view.getContext()).load(merchants.getImagePath()).fit().into(viewHolder.merchant_image);

    }


    return view;

}

getItem方法:

@Override
public Object getItem(int position) {
    if (merchants.size() > 0) {
        return merchants.get(position);
    } else
        return false;
}

2 个答案:

答案 0 :(得分:1)

问题在于您的getItem()方法。

如果没有要显示的数据,该方法将返回false,即布尔值。这打破了getview()中的演员表。

getItem()方法更改为:

@Override
public Object getItem(int position) {
    if (merchants.size() > 0)
        return merchants.get(position);
    else
        return null;
}

getView()中,替换:

 Merchants merchants = (Merchants) getItem(position);
    if (merchants != null) {
        identity = merchants.getMerchantId();
        ...

使用:

if (getItem(position) != null) {
    Merchants merchants = (Merchants) getItem(position);
    identity = merchants.getMerchantId();
    ...

这将解决崩溃,但您还必须检查merchants.getSize()为0的原因。

答案 1 :(得分:1)

尝试按以下方式替换getItem()

@Override
public Object getItem(int position) {
    if (merchants.size() > 0) {
        return merchants.get(position);
    } else
        return null;
}

当你的方法大小为零时,你正在返回false,它正在创建投射错误,说false无法转换为Merchants