0

我是 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 并且总是出现错误或空列表

4

1 回答 1

2

后:

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

只需使用此 Cursor 创建一个 CursorAdapter,如SimpleCursorAdapter,然后将 Adapter 传递给您的 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. 如果您想自定义信息的显示方式,请编写您自己的布局。

于 2013-03-24T16:10:10.037 回答