数组适配器仅显示数组的最后一个元素.如何获取所有值

Ara*_*vin 2 android

我有以下代码用于显示我的应用程序中的联系人.我有问题显示联系人.我的数组(from)只从数据库中获取一个值,但在数据库中有很多值.如何从数据库中获取所有值.

mydatabasecode:

public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}
Run Code Online (Sandbox Code Playgroud)

GetvalueFromDb代码:

 List<Contact> contacts = db.getAllContacts();
    for (Contact cn : contacts) {
        from = new String[] { cn.getName()};
        Toast.makeText(getApplicationContext(), ""+Arrays.toString(from), Toast.LENGTH_LONG).show();

    }
note = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_edit,from);
        lv.setAdapter(note);
Run Code Online (Sandbox Code Playgroud)

Tro*_*omB 5

from只创建一个字符串,而不是要应用于数组适配器的字符串数组.请尝试以下方法:

List<Contact> contacts = db.getAllContacts();
ArrayList<String> from = new ArrayList<String>;
for (Contact cn : contacts) {
    from.add(cn.getName());
    Toast.makeText(getApplicationContext(), ""+Arrays.toString(from), Toast.LENGTH_LONG).show();

}
note = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_edit, from);
    lv.setAdapter(note);
Run Code Online (Sandbox Code Playgroud)