android 无法将项强制转换为com,example,sharingapp,联系人

ckocjqey  于 2023-03-16  发布在  Android
关注(0)|答案(2)|浏览(129)

我正在处理Android应用程序代码,并且扩展了ArrayAdapter类,但收到此错误消息
Item cannot be cast to com.example.sharingapp.Contact
下面是我的代码:

package com.example.sharingapp;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import java.util.ArrayList;

    public class ContactAdapter extends ArrayAdapter<Contact> {

    private LayoutInflater inflater;
    private Context context;

    public ContactAdapter(Context context, ArrayList<Contact> contacts) {
        super(context, 0, contacts);
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // getItem(position) gets the "contact" at "position" in the "contacts" ArrayList
        // (where "contacts" is a parameter in the ContactAdapter creator as seen above ^^)
        Contact contact =  getItem(position);

        String username = "Username: " + contact.getUsername();
        String email = "Email: " + contact.getEmail();

        // Check if an existing view is being reused, otherwise inflate the view.
        if (convertView == null) {
            convertView = inflater.from(context).inflate(R.layout.contactlist_contact, parent, false);
        }

        TextView username_tv = (TextView) convertView.findViewById(R.id.username_tv);
        TextView email_tv = (TextView) convertView.findViewById(R.id.email_tv);
        ImageView photo = (ImageView) convertView.findViewById(R.id.contacts_image_view);

        photo.setImageResource(android.R.drawable.ic_menu_gallery);

        username_tv.setText(username);
        email_tv.setText(email);

        return convertView;
    }
}

错误涉及以下行:
Contact contact = getItem(position);

x7rlezfr

x7rlezfr1#

您需要在适配器中保留一个“联系人”列表。
你需要这样的东西:

private LayoutInflater inflater;
private Context context;
private ArrayList<Contact> contactList = new ArrayList<>();

然后,在构造函数上:

public ContactAdapter(Context context, ArrayList<Contact> contacts) {
       super(context, 0, contacts);
       this.context = context;
       this.inflater = LayoutInflater.from(context);
       this.contactsList = contacts;
    }

然后重写“getItem”以从您的“contactList”返回具有给定位置的联系人:

@Override
    public Contact getItem(int position) {
        // TODO Auto-generated method stub
        return contacts.get(position);
    }
dced5bon

dced5bon2#

这是Coursera课程面向对象设计的代码库。
我遇到了类似的问题,我通过修复ContactListloadContacts方法中的代码解决了这个问题,从ItemList类复制此方法后,需要设置正确的ArrayList类型。

相关问题