从SQLite填充CheckList

时间:2012-05-03 07:58:37

标签: android sqlite

我想从我的数据库中填充一个列表。

我有以下代码:

setContentView(R.layout.pro);
    addProFromDB();

}

我应该如何填充多个 xCodexInlinexPlacexHolderx

private void addProFromDB() {
    // TODO Auto-generated method stub

    ArrayList<String> results = new ArrayList<String>();
    SQLiteDatabase sampleDB = null;

    try {
        list = (ListView)findViewById(android.R.id.list);
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
        sampleDB.execSQL("create table tbl_product("
                + "pro_id integer PRIMARY KEY autoincrement,"
                + "pro_name text," + "pro_price integer);");

        sampleDB.execSQL("insert into tbl_product(pro_name, pro_price) values ('oil', '200' );");

        Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
                null);
        char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
        int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");

    } finally {
        if (sampleDB != null)
        sampleDB.close();
    }
    setListAdapter(new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_checked, new ArrayList()));

它没有给出任何错误,但也没有显示插入的项目。

2 个答案:

答案 0 :(得分:1)

您的代码段中存在多少问题。

  1. 每次运行app时,您都在创建表tbl_product
  2. 您每次都在新创建的表格中插入新元素。
  3. 最后您将空数组传递给ArrayAdapter new ArrayList()
  4. 我建议你仔细阅读任何教程,然后逐步解决问题。

    我建议您关注this tutorial,并在使用sqlite时使用CursorAdapter

答案 1 :(得分:0)

我要修改你的代码,现在你可以检查并使用这段代码,这对你有用..

private void addProFromDB() {
// TODO Auto-generated method stub

ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;

try {
    list = (ListView)findViewById(android.R.id.list);
    sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
    sampleDB.execSQL("create table if not exists tbl_product("
            + "pro_id integer PRIMARY KEY autoincrement,"
            + "pro_name text," + "pro_price integer);");

    sampleDB.execSQL("insert into tbl_product(pro_name, pro_price) values ('oil', '200' );");

    Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
            null);
    char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
    int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");

ArrayList list = new ArrayList()
list.add(pro_nameColumnIndex);
list.add(pro_priceColumnIndex);
setListAdapter(new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_checked, list));

} finally {
    if (sampleDB != null)
    sampleDB.close();
}