【问题标题】:ArrayAdapter/ListView is not workingArrayAdapter/ListView 不工作
【发布时间】:2011-03-16 19:55:44
【问题描述】:

我是使用 android 编程的新人,在执行我的第一个应用程序时,我的列表出现了问题。 代码如下:

Cursor c = db.rawQuery("SELECT nombre FROM contactos", null);

        ArrayList<String> listaArray = new ArrayList<String>();
        ListView listadoContactos = (ListView)findViewById(R.id.listViewListaContactos);

        if (c.moveToFirst())
        {
            do {
                listaArray.add(c.getString(0));
            } while(c.moveToNext());
        }

        //Creamos un adaptador y lo asignamos al ListView.
        ArrayAdapter<String> adaptadorLista = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listaArray);

        listadoContactos.setAdapter(adaptadorLista);

当我看到结果时,我的列表只显示了我正在查询的数据库中的第一项。你能帮帮我吗?

感谢您的建议!乔治。

PS:“nombre”是第 0 列。这就是我写“getString(0)”的原因,因为我只想显示每行的 1 列。

【问题讨论】:

  • 看到非英文标识符对我来说总是很奇怪。

标签: android listview cursor android-arrayadapter


【解决方案1】:

尝试使用 SimpleCursorAdapter

// NOTE your query result should have id-field, named "_id"
    Cursor c = db.rawQuery("SELECT nombre, nombre_id as _id FROM contactos", null);

    SimpleCursorAdapter adaptorLista = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, new String[]{"nombre"}, new int[]{android.R.id.text1} );
            listadoContactos.setAdapter(adaptadorLista);

这里android.R.layout.simple_list_item_1是ListView中每一行的布局, new String[]{"nombre"} 光标中字段的名称,其值设置为 ListView 行中的 TextViews。最后一个参数new int[]{android.R.id.text1}中指定的TextView ids@

【讨论】:

  • 非常感谢。它对我有用。现在,我在显示列表视图时遇到了麻烦,它显示为一半。有什么建议吗?
  • 请显示屏幕布局以及“半切”是什么意思?
  • 对不起,我的英语不好,我的意思是“半切”:goo.gl/BYSGo再次感谢您。
  • 我需要用屏幕布局查看xml
  • 这里有 schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width= "fill_parent" android:layout_height="fill_parent" android:background="@drawable/wall">
【解决方案2】:

使用CursorAdapter 而不是 ArrayListAdapter。通过将光标复制到数组中只是为了将其提供给 ListView,您正在为自己做额外的工作。 Here is a tutorial on CursorAdapters

【讨论】:

    【解决方案3】:

    您可以使用 SimpleCursorAdapter 并直接将光标传递给它:

    Adapter adapter = new SimpleCursorAdapter(
        this,
        c,
        android.R.layout.simple_list_item_1,
        new String[] { "nombre" },
        new int[] { android.R.id.text1 },
        0);
    listadoContactos.setAdapter(adapter);
    

    然后您就不必逐步完成并自己构建列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多