【问题标题】:Android ListView (not ListActivity) connecting to SQLite DB using CustomCursorAdapterAndroid ListView(不是 ListActivity)使用 CustomCursorAdapter 连接到 SQLite DB
【发布时间】:2011-02-19 22:08:56
【问题描述】:

我正在尝试创建自定义光标适配器并将其附加到我的列表视图。

虽然我还没有在我的适配器中创建文本框和设置值, 当我尝试调用 super(ctx, c);

时,我的代码当前会引发运行时异常

可能出了什么问题?网上搜遍了,没找到。提前致谢!

自定义光标适配器:

public class CustomCursorAdaptor extends CursorAdapter {

    private Context context;
    private int layout;

    public CustomCursorAdaptor (Context ctx, int layout, Cursor c, String[] from, int[] to) {
        super(ctx,  c);
        this.context = ctx;
        this.layout = layout;
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return(new View(context));
    }

    @Override
    public void bindView(View v, Context context, Cursor c) {

        }
}

和我的活动:

public class DynamicScrollView extends Activity {
     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context ctx=getBaseContext();
        RelativeLayout newLayout=new RelativeLayout(ctx);
        ListView lv=new ListView(ctx);

    SQLiteDatabase db;
        db = ctx.openOrCreateDatabase("TShow.db", SQLiteDatabase.OPEN_READONLY, null);
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);

        Cursor cur = db.query("control", new String[] {"id"}, "parent_id=2", null, null, null, null);

        CustomCursorAdaptor adapter = new CustomCursorAdaptor(ctx, lv.getId(), cur, new String[] {"id"}, new int[] {2});
        lv.setAdapter(adapter);

         newLayout.addView(lv);
         setContentView(newLayout);
         }
}

【问题讨论】:

    标签: android sqlite android-listview


    【解决方案1】:

    我真的不太了解你在这里传递给CursorAdaptor 的基本上下文,但我知道通常你应该使用Activity 作为上下文。 ActivityContext 的子类,以防你不知道。

    所以,而不是:

    new CustomCursorAdaptor(ctx, lv.getId(), cur, new String[] {"id"}, new int[] {2});
    

    ...你可以试试:

    new CustomCursorAdaptor(this, lv.getId(), cur, new String[] {"id"}, new int[] {2});
    

    【讨论】:

    • 我发现了问题所在。这不是上下文。游标适配器期望有一列 _id 用作索引。我在选择中添加了另一列作为_id,它起作用了!更新代码:codeCursor cur = db.query("control", new String[] {"id as _id", "id"}, "parent_id=2", null, null, null, null); code
    【解决方案2】:

    光标适配器期望有一个_id 列用作索引。我在选择中添加了另一列作为_id,它起作用了!更新代码:

    Cursor cur = db.query("control", new String[] {"id as _id", "id"}, "parent_id=2", null, null, null, null);
    

    我从异常描述中追溯到它说:列'_id'不存在

    【讨论】:

      【解决方案3】:

      感谢您提供有关 ListView 工作所需的 _id 列的黄金提示。

      @dmg:您不能使用(本机)SQL 'AS' 语句命名您的 _id 列。只需添加“_id”列而不更改它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-05
        • 2013-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多