我想用SimpleCursorAdapter显示列表视图中从数据库查询的项目。 例如,数据库中可能有20,000个项目。我想只加载100项(_id:1-100)查询而不是加载所有项目,当在listview的末尾滚动时,加载另外100项(_id:101-200)查询,如何实现它?欢迎任何建议,谢谢。
相关代码如下:
protected void onCreate(Bundle savedInstanceState) {
mCursor = managedQuery(CONTENT_URI, PROJECTION, null, null, "_id DESC");
mAdapter = new SimpleCursorAdapter(this,R.layout.list_content, mCursor, keys, values);
setListAdapter(mAdapter);
}
在我定义的列表视图中,我想通过查询数据库加载更多项目。
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
int lastItem = firstVisibleItem + visibleItemCount - 1;
if (mListAdapter != null) {
if ((lastItem == mListAdapter.getCount()-1) && (mRefreshState != REFRESHING)) {
mFooterView.setVisibility(View.VISIBLE);
mRefreshState = REFRESHING;
new Handler().postDelayed(new Runnable() {
public void run() {
//execute the task , i want to load more items by query database
RefreshListView(LOADING_STORED_INFO);
}
}, DEFAULT_DELAY_TIMER);
}
}
}
在AsyncTask加载数据中,我执行查询操作。
protected Integer doInBackground(Integer... params)
{
Uri uri = ContentUris.withAppendedId(CONTENT_URI, mCursor.getInt(0)-1);
cursor = managedQuery(uri, PROJECTION, null, null, "_id DESC");
return (0 == params[0]) ? 1 : 0;
}
@Override
protected void onPostExecute(Integer result)
{
mAdapter.changeCursor(cursor);//is this OK?
mAdapter.notifyDataSetChanged();
/*
if (1 == result)
{
mListView.setSelection(1);
}
else
{
mListView.setSelection(mCount-1);
}*/
// Call onRefreshComplete when the list has been refreshed.
mListView.onRefreshComplete(result);
super.onPostExecute(result);
}
答案 0 :(得分:2)
以这种方式在SQL查询中使用LIMIT
语句:
SELECT your_column FROM your_table ORDER BY your_order LIMIT limit_skip, limit_count
然后,您可以使用OnScrollListener
检索第一个可见单元格的索引和可见单元格的数量,以便您可以连贯地增加limit_skip
和limit_count
。
而不是通用AsyncTask
使用CursorLoader
并实施LoaderManager.LoaderCallbacks<Cursor>
,如下所示:
public Loader<Cursor> onCreateLoader(int id, Bundle args){
String orderBy = "_id DESC"
if(args != null){
orderBy += " LIMIT " + args.getInt("LIMIT_SKIP") + "," + args.getInt("LIMIT_COUNT");
}
return new CursorLoader(this /*context*/, CONTENT_URI, PROJECTION, null, null, orderBy);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data){
listAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader){
listAdapter.swapCursor(null);
}
然后,在onCreate()
中,将null
作为cursor
传递给new SimpleCursorAdapter()
并以这种方式创建CursorLoader
:
getLoaderManager().initLoader(0, null, this /*LoaderCallbacks<Cursor>*/);
然后,在onScroll()
中,每次以这种方式重置加载器:
Bundle args = new Bundle();
args.putInt("LIMIT_SKIP", limit_skip_value);
args.putInt("LIMIT_COUNT", limit_count_value);
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);