填充Android ListView的错误结果

时间:2016-12-09 19:20:49

标签: android listview android-contacts

我试图从手机通讯录中填充ListView,但结果是错误的。

我创建了一个联系人列表:

List<Contact> contacts = getContactNames();

我的适配器是:

ArrayAdapter<Contact> adapter = new ArrayAdapter<>(this, R.layout.contacts_list, R.id.contactName, contacts);
listView.setAdapter(adapter);

但是当我运行我的应用程序时,我在textView contactName中的包名称和textView contactNumber中的描述

我有三个文件,AcitivityMain.class,contacts_list.xml和Contact.class:

ActivityMain

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;

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

        // Find the list view
        this.listView = (ListView) findViewById(R.id.listView);

        // Read and show the contacts
        showContacts();
    }

    /**
     * Show the contacts in the ListView.
     */
    private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
            //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
        } else {
            // Android version is lesser than 6.0 or the permission is already granted.
            List<Contact> contacts = getContactNames();
            ArrayAdapter<Contact> adapter = new ArrayAdapter<>(this, R.layout.contacts_list, R.id.contactName, contacts);
            listView.setAdapter(adapter);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
                showContacts();
            } else {
                Toast.makeText(this, "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Read the name of all the contacts.
     *
     * @return a list of names.
     */
    private List<Contact> getContactNames() {
        List<Contact> contacts = new ArrayList<>();
        Contact contact = new Contact();
        // Get the ContentResolver
        ContentResolver cr = getContentResolver();
        // Get the Cursor of all the contacts
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contact.setContactName(name);
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        contact.setContactNumber(number);
                        contacts.add(contact);
                    }
                    pCur.close();
                }
            }
        }
        return contacts;
    }
}

联系班级

public class Contact {
    private String contactName;
    private String contactNumber;

    public Contact() {}

    public Contact(String name, String number) {
        this.contactName = name;
        this.contactNumber = number;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Contact)) return false;

        Contact contact = (Contact) o;

        if (getContactName() != null ? !getContactName().equals(contact.getContactName()) : contact.getContactName() != null)
            return false;
        return getContactNumber() != null ? getContactNumber().equals(contact.getContactNumber()) : contact.getContactNumber() == null;

    }

    @Override
    public int hashCode() {
        int result = getContactName() != null ? getContactName().hashCode() : 0;
        result = 31 * result + (getContactNumber() != null ? getContactNumber().hashCode() : 0);
        return result;
    }
}

contacts_list

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >

<ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="6dip"
    android:contentDescription="TODO"
    android:src="@mipmap/ic_launcher" />

<TextView
    android:id="@+id/contactNumber"
    android:layout_width="fill_parent"
    android:layout_height="26dip"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@id/icon"
    android:ellipsize="marquee"
    android:singleLine="true"
    android:text="Description"
    android:textSize="12sp" />

<TextView
    android:id="@+id/contactName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@id/contactNumber"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_alignWithParentIfMissing="true"
    android:layout_toRightOf="@id/icon"
    android:gravity="center_vertical"
    android:text="Example application"
    android:textSize="16sp" />

</RelativeLayout>

结果是: enter image description here

2 个答案:

答案 0 :(得分:1)

首先要做的事情。数组适配器仅适用于每个布局一个TextView。它不能使联系人姓名和电话号码都膨胀。这意味着电话号码textView将保留在xml布局中,在本例中为“Decription”。

关于包名称问题

ArrayAdapter documentation

  

然而,TextView被引用,它将被填充   数组中每个对象的toString()。您可以添加列表或数组   自定义对象。 覆盖对象的toString()方法   确定将为列表中的项目显示哪些文本

因此,您需要覆盖联系人中的toString方法并返回联系人姓名。

虽然这样可行,但我建议使用另一种适配器,因为理想情况下,toString方法应该代表对象及其所有字段

答案 1 :(得分:0)

此方法中您不会再次初始化您的联系人变量

请添加此行

Contact contact = new Contact();
像你这样在你的while循环中

private List<Contact> getContactNames() {
    List<Contact> contacts = new ArrayList<>();
    // Get the ContentResolver
    ContentResolver cr = getContentResolver();
    // Get the Cursor of all the contacts
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            Contact contact = new Contact();
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contact.setContactName(name);
            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contact.setContactNumber(number);
                    contacts.add(contact);
                }
                pCur.close();
            }
        }
    }
    return contacts;
}

并在您的Contact类中定义toString()函数

@Override
public void toString(){
   return name + "  " + number;
}

我希望它能解决你的问题