2

我有以下代码用于在我的应用程序中显示联系人。我在显示联系人时遇到问题。我的数组(来自)仅从数据库中获取一个值,但在数据库中存在许多值。如何从数据库中获取所有值。

我的数据库代码:

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;
}

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);
4

2 回答 2

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);
于 2013-07-30T17:45:29.783 回答
1

因为你在循环中初始化from array和最后一次循环运行时你得到了最后一个值

你可以试试

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

    }
于 2013-07-30T17:46:27.290 回答