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

标签 android

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

我的数据库代码:

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

最佳答案

您正在使 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);

关于android - 数组适配器仅显示数组的最后一个元素。如何获取所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17953780/

相关文章:

android - 在 Here Map Android SDK 中重新路由

Android:如何使用 "uses-library"?

java - HTTPClient错误异常: 400 Bad Request using Spring REST template

android - 锁定 Android 键盘仅显示数字

android - iPhone 有 9-patch 加载器吗?

android - 没有使用 gradle 插件 2.2.0 生成 "unaligned"apk,破坏了 Spoon runner

android - 我如何解析器numberformatexception错误

Android - 如何获取 Spinner 中的所有项目?

android - Caffe:检查失败:网络应该只有一个输出

android - 有安卓的照片处理库吗?