我通过启动多个加载器从游标将数据加载到listview中。我希望我的listview显示来自所有游标的数据,但listview中的数据会立即以2秒的间隔更改并显示最后一个游标的数据。请帮我。我哪里出错了?我必须合并游标吗?
我的片段的onCreateView()内部:
for (int i = 0; i < idsArray.length; i++) {
Bundle b = new Bundle();
b.putInt("id", idsArray[i]);
getLoaderManager().initLoader(idsArray[i], b, this); //initiating multiple loaders
}
adapter = new CustomAdapter(getActivity(), R.layout.list_row, null, column_names_array, ui_ids_array, 0);
listView.setAdapter(adapter);
加载器回调方法:
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle b) {
Builder uriBuilder = MY_PROVIDER_URI.buildUpon();
uriBuilder.appendPath("categories");
uriBuilder.appendPath(String.valueOf(b.getInt("id")));
uriBuilder.appendPath("data");
return new CursorLoader(getActivity(), uriBuilder.build(), null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(adapter != null && data != null){
adapter.swapCursor(data);
adapter.notifyDataSetChanged();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
这是我的适配器类:
public class CustomAdapter extends SimpleCursorAdapter {
Cursor cursor;
Context context;
Activity activity;
int layout;
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags ) {
super(context, layout, c, from, to, flags);
this.cursor = c;
this.context = context;
this.activity = (Activity) context;
this.layout = layout;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(this.layout, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
//finding UI elements in list row here
view.setTag(holder);
}
//binding data to views of viewholder here
}
static class ViewHolder {
//variables of all my UI elements
}
}
答案 0 :(得分:2)
你的循环:
for (int i = 0; i < idsArray.length; i++) {
Bundle b = new Bundle();
b.putInt("id", idsArray[i]);
getLoaderManager().initLoader(idsArray[i], b, this); //initiating multiple loaders
}
将导致创建多个Loader,一旦Loader完成加载其数据,方法
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(adapter != null && data != null){
// This line result in replacing the last Cursor by the new one
adapter.swapCursor(data);
adapter.notifyDataSetChanged();
}
}
被调用。当最后一个Loader完成加载Cursor时,由于 swapCursor ,其数据将替换最后一个Cursor。
如果查看CursorAdapter文档,您会注意到此CursorAdapter一次只能管理一个Cursor。
要解决您的问题,您应该尝试将所有想要的数据查询到单个查询中,从而产生一个Cursor。