什么是在android中将数据从sqlite填充到listview的最佳方法

时间:2013-03-24 16:05:34

标签: android android-listview simplecursoradapter

我是android编程新手,希望你能帮助我 我一开始有些问题, 我想从Sqlite数据库填充数据,但我不知道最好的方法是什么。我的数据库有时候有很多数据,我想要一个优化方式从中获取数据。我搜索了很多并找到了SimpleCursorAdapter对我的目的有好处,但我找不到任何方法让它工作..这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_book);
    ListView Peot_list = (ListView) findViewById(R.id.list_poet_name);
    String SDcardPath = Environment.getExternalStorageDirectory().getPath();
    String DbPath = SDcardPath + "/Tosca/" + "persian_poem.db";




    try {
        db = SQLiteDatabase.openDatabase(DbPath,null,SQLiteDatabase.CREATE_IF_NECESSARY);

        // here you do something with your database ...
        getData();

    db.close();

    }
    catch (SQLiteException e) {

    }

}



private void getData() {
    TextView txtMsg;

    txtMsg=(TextView) findViewById(R.id.txtmsg);
        try {

        // obtain a list  from DB
            String TABLE_NAME = "classicpoems__poet_contents";
            String COLUMN_ID = "poet_id";
            String COLUMN_NAME = "poet_name";
            String COLUMN_CENTURY = "century_start";
            String [] columns ={COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};

        Cursor c = db.query(TABLE_NAME, columns,null, null, null, null, COLUMN_ID);
        int theTotal = c.getCount();
        Toast.makeText(this, "Total: " + theTotal, 1).show();

        int idCol = c.getColumnIndex(COLUMN_ID);
        int nameCol = c.getColumnIndex(COLUMN_NAME);
        int centuryCol = c.getColumnIndex(COLUMN_CENTURY);


        while (c.moveToNext()) {
        columns[0] = Integer.toString((c.getInt(idCol)));
        columns[1] = c.getString(nameCol);
        columns[2] = c.getString(centuryCol);


        txtMsg.append( columns[0] + " " + columns[1] + " "
        + columns[2] + "\n" );
        }
        } catch (Exception e) {
        Toast.makeText(this, e.getMessage(), 1).show();
        }




}

现在我可以从数据库中读取我想要的内容并将它们显示在txtMsg中但是我想将它们显示到列表视图中...我根本无法定义SimpleCursorAdapter并且总是得到错误或空列表

1 个答案:

答案 0 :(得分:2)

后:

Cursor c = db.query(TABLE_NAME, columns,null, null, null, null, COLUMN_ID);

使用此Cursor创建一个CursorAdapter,如SimpleCursorAdapter,然后将适配器传递给ListView。类似的东西:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, 
            new String[] {COLUMN_NAME,COLUMN_CENTURY}, new int[] {android.R.id.text1, android.R.id.text2}, 0);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);

(您实际上不需要Cursor c = db.query(...);下面的任何其他代码。)


每行的外观取决于您在适配器中使用的布局,在本例中为android.R.layout.simple_list_item_2。如果要自定义信息的显示方式,请编写自己的布局。

相关问题