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



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

After:

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

简单地创建一个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。如果您想自定义信息的显示方式,请编写自己的布局。

相关内容

最新更新