【发布时间】:2016-08-23 07:26:41
【问题描述】:
我正在构建一个非常简单的应用程序,其中包含一个 SQLiteDatabase,我想使用自定义 SimpleCursorAdapter 将其显示在 ListFragment 中。
我的代码运行良好,但我不确定我是否以正确的方式做事。我已经搜索了很多(权威)示例,但只找到了使用ArrayAdapter 的过于简化的示例,或者使用ContentProvider 的过于复杂的示例。
列表片段
public class CallListFragment extends ListFragment{
private CallListDbHelper dbHelper;
private SQLiteDatabase db;
private Cursor cursor;
private CallListAdapter adapter;
@Override
public void onResume() {
super.onResume();
// Create a database helper
dbHelper = new CallListDbHelper(getActivity());
// Get the database
db = dbHelper.getReadableDatabase();
// Get a cursor to the entire call list from the database
cursor = db.query( // SELECT
CallEntry.TABLE_NAME, // FROM ...
new String[] { // <columns>
CallEntry._ID,
CallEntry.COLUMN_NUMBER,
CallEntry.COLUMN_TIME },
null, // WHERE ... (x = ?, y = ?)
null, // <columnX, columnY>
null, // GROUP BY ...
null, // HAVING ...
CallEntry.COLUMN_TIME + " DESC" // ORDER BY ...
);
adapter = new CallListAdapter(getActivity(), cursor);
setListAdapter(adapter);
}
@Override
public void onPause() {
super.onPause();
// Close cursor, database and helper
if( null !=cursor ) cursor.close();
if( null != db ) db.close();
if( null != dbHelper ) dbHelper.close();
}
}
适配器
public class CallListAdapter extends SimpleCursorAdapter {
private static final String[] FROM = {
CallListContract.CallEntry.COLUMN_NUMBER,
CallListContract.CallEntry.COLUMN_TIME
};
private static final int[] TO = {
R.id.phoneNumber,
R.id.time
};
public CallListAdapter(Context context, Cursor cursor){
this(context, R.layout.listitem_call, cursor, FROM, TO);
}
private CallListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout, cursor, from, to, 0);
}
}
【问题讨论】:
-
嗯,片段看起来不错。 CallListAdapter 可能也很有趣。
-
已添加适配器代码。
标签: android android-listfragment android-cursoradapter android-cursor android-database