【问题标题】:Show all database contents in a ListView在 ListView 中显示所有数据库内容
【发布时间】:2020-11-01 03:00:37
【问题描述】:

我想在 Android Studio 的列表视图中显示所有数据库内容,我希望看到 3 行,每行包含 "name, family and ID" ,但我看到了一个复杂的包名称和一些其他字符如下:

com.google.www.hmdbtest01.Person@529e71b4

com.google.www.hmdbtest01.Person@529e7238

com.google.www.hmdbtest01.Person@529e7298

如果我的数据库中有更多行,我会在输出中看到更多类似上面的行。

我的代码如下:

public class ListOfData extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_of_data);

    ListView  list = findViewById(R.id.list1);
    HmDbManager01 db= new HmDbManager01(this);
    ArrayList personList = db.getAll();
    ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
    android.R.layout.simple_list_item_1, personList);

    list.setAdapter(arrayList);
}
}

db.getAll()如下:

public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();

if(cursor.getCount() > 0){
    while (!cursor.isAfterLast()){
        Person p1 = new Person();
        p1.pID=cursor.getString(0);
        p1.pName=cursor.getString(1);
        p1.pFamily=cursor.getString(2);
        allData.add(p1);
        cursor.moveToNext();
    }
}
cursor.close();
sqLiteDatabase.close();
return allData;
}

而且,这是人:

package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}

让我知道你的 cmets 解决这个问题。

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    arrayListAdapter 会将您的 personList 转换为字符串列表

    改变喜欢它:

        ArrayList<String> persons = new ArrayList<String>();
        personList.forEach(personModel -> {
            persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
        });
        ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
                android.R.layout.simple_list_item_1, persons);
    

    【讨论】:

    • 感谢 mahdi,但您的解决方案会生成一个字符串,但我需要一个表格。
    • 所以你必须实现你的自定义数组适配器
    • 我使用 Simple_list_item_1 作为适配器。适合这张桌子吗?感谢您推荐适配器。
    • 简单的适配器不适合,因此我建议您从 [这里] (medium.com/mindorks/…) 阅读更多内容
    • 以上代码中的 personModel 是什么?我看到“personModel.name”以及其他变量的错误:personModel.lastName 和 personModel.id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多