【问题标题】:ListView with Custom Cursor Adapter is Empty/Blank具有自定义光标适配器的 ListView 为空/空白
【发布时间】:2012-07-15 10:40:21
【问题描述】:

所以几天来我一直在尝试让 ListView 显示 SQLite 数据库中的数据,但我仍然找不到解决方案。

ListView XML 看起来像:

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


<Button 
    android:id="@+id/gotoEntry"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="New Entry" />

<ListView 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list" >
</ListView>

</LinearLayout>

行项目如下所示:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:textSize="15dp"
android:padding="15dp"
android:id="@+id/thetext"
>
</TextView>

我的光标适配器看起来像:

public class ItemAdapter extends CursorAdapter{
private Cursor iCursor;
private Context iContext;
private final LayoutInflater iInflater;


public ItemAdapter(Context context, Cursor c) {
    super(context, c);
    iInflater=LayoutInflater.from(context);
    iContext=context;
}


@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView itemName = (TextView) view.findViewById(R.id.thetext);

    itemName.setText(cursor.getString(cursor.getColumnIndex(db_Setup.KEY_NAME)));
    }
}


@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) throws InflateException {
    final View view = iInflater.inflate(R.layout.single_item, parent, false);
    return view;
}
}

光标是用这个方法制作的:

public static Cursor getName() {
    Cursor q = myDatabase.query(DATABASE_TABLE, new
        String[] {db_Setup.KEY_NAME}, null, null, null, null, null);
q.moveToFirst();

return q;
}

并像这样在 listactivity 中实例化:

Cursor cursor = db_Setup.getName();

我试图在我的 ListActivity 中执行此操作以将列表视图绑定到光标:

ItemAdapter ia = new ItemAdapter(getBaseContext(), cursor);
ia.bindView(findViewById(R.id.thetext), getApplicationContext(), cursor);

当我运行应用程序时没有错误...在这篇文章的顶部有一个来自 XML 的按钮,并且空白(没有 listView)... 我已经在 SQLite 数据库中输入了一些值,大约有 14 个值。为什么什么都没有显示?

【问题讨论】:

    标签: android sqlite listview android-cursoradapter


    【解决方案1】:

    最后一行不正确。创建 ItemAdapter 后,只需调用 ListActivity.setListAdapter(ia)。详情请见Displaying query results

    【讨论】:

    • 非常感谢!没想到差错这么小!那么 bindView 方法有什么用呢?
    • ListView内部调用该方法绑定一条记录。你不直接调用它。您实际上可以优化您的方法。 ListView 回收记录视图。如果 view 参数不为 null,则可以重复使用,否则膨胀一个新视图。这将使滚动更流畅。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2012-09-20
    相关资源
    最近更新 更多