Android: 从数据库填充一个 ListView

Android: Populate a a ListView from a Database

我有一个 SQLite 数据库,我想用它来填充 ListView,但我一辈子都不知道该怎么做。基于各种互联网资源(其他 questions/tutorials/etc),我已经能够获得此代码,但它显然无法正常工作,因为我现在甚至无法在模拟器中打开该应用程序:

populateListView 方法

public void populateListView() {
    Cursor cursor = db.getAllContacts();
    String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_LOCATION, DBAdapter.KEY_TIME};
    int[] toViewIds = new int[] {R.id.textView3, R.id.textView2, R.id.textView4};
    SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
            R.layout.list_view_layout, cursor, fromFieldNames, toViewIds, 0);

    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(myCursorAdapter);
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical"
    android:id="@+id/TableLayout">


<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Set New Alarm"
    android:id="@+id/setAlarmButton"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="onClickSetAlarm" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView" />

</RelativeLayout>

list_view_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView2" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView3" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView4"
    android:layout_gravity="center_horizontal" />
</LinearLayout>

我相当确定问题不在于 DBAdapter 的代码,因为在我添加这段代码之前它工作正常(我让它显示了带有数据的 Toast)。

谢谢!

这个问题我昨天刚回答。创建 CursorLoader 的最简单方法,当 activity 创建并易于设置适配器时,它只会在后台从数据库加载数据一次:只需形成列 "from" (DB.COLUMN_NAME)和 "to" (R.id.textviewToDisplay)。 请检查这个答案。 retriveing data from exisint sqlite database

使用 SimpleCursorAdapter

Cursor cursor = obj.fetchAllNames();
        registerForContextMenu(lv);

        String[] columns = new String[] {
                obj.KEY_MAIL,
                obj.KEY_NAME

              };


          // the XML defined views which the data will be bound to
          int[] to = new int[] {
            R.id.tvname,
            R.id.tvemail

          };

          // create the adapter using the cursor pointing to the desired data
          //as well as the layout information
          try{
          dataAdapter = new SimpleCursorAdapter(
            this, R.layout.viewusertext,cursor,columns,
            to,
            0);
          }catch(Exception e)
          {e.printStackTrace();}

          lv.setAdapter(dataAdapter);

其中 lv 是列表视图,dataAdapter 是 private SimpleCursorAdapter dataAdapter;

检索要在列表中显示的所需元素的查询:

public Cursor fetchAllNames() {

          Cursor mCursor = app.myDbHelper.MyDB().query("reg", new String[] {"email as _id","fname"},
            null, null, null, null, null);
          try{

          if (mCursor != null) {
           mCursor.moveToFirst();
          }
          return mCursor;
          }catch(Exception e)
          {
              return mCursor;
          }
         }

"reg" 是 table 名称。

注意:在使用 simplecursoradapter 时,您应该将主键用作 _id。在我的例子中,电子邮件是主键,我将其定义为 public static final String KEY_MAIL="_id";