下面列出了怎么用android.widget.CursorAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 关注1
* 模糊查询数据 & 显示到ListView列表上
*/
private void queryData(String tempName) {
// 1. 模糊搜索
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
// 2. 创建adapter适配器对象 & 装入模糊搜索的结果
adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 3. 设置适配器
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println(cursor.getCount());
// 当输入框为空 & 数据库中有搜索记录时,显示 "删除搜索记录"按钮
if (tempName.equals("") && cursor.getCount() != 0){
tv_clear.setVisibility(VISIBLE);
}
else {
tv_clear.setVisibility(INVISIBLE);
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listDrinks = getListView();
try {
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
db = starbuzzDatabaseHelper.getReadableDatabase();
cursor = db.query("DRINK",
new String[]{"_id", "NAME"},
null, null, null, null, null);
CursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listDrinks.setAdapter(listAdapter);
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
}
@Override
public void onRestart() {
super.onRestart();
try {
StarbuzzDatabaseHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor newCursor = db.query("DRINK",
new String[] { "_id", "NAME"},
"FAVORITE = 1",
null, null, null, null);
ListView listFavorites = (ListView)findViewById(R.id.list_favorites);
CursorAdapter adapter = (CursorAdapter) listFavorites.getAdapter();
adapter.changeCursor(newCursor);
favoritesCursor = newCursor;
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
}
void init(final Cursor c, int flags) {
if ((flags & CursorAdapter.FLAG_AUTO_REQUERY) == CursorAdapter.FLAG_AUTO_REQUERY) {
flags |= CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER;
mAutoRequery = true;
} else {
mAutoRequery = false;
}
boolean cursorPresent = c != null;
mCursor = c;
mDataValid = cursorPresent;
mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1;
if ((flags & CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER) == CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER) {
mChangeObserver = new ChangeObserver();
mDataSetObserver = new MyDataSetObserver();
} else {
mChangeObserver = null;
mDataSetObserver = null;
}
if (cursorPresent) {
if (mChangeObserver != null) c.registerContentObserver(mChangeObserver);
if (mDataSetObserver != null) c.registerDataSetObserver(mDataSetObserver);
}
}
@Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
//Context context = holder.itemView.getContext();
//GlideApp.with(context).clear(holder.ivIcon);
CursorAdapter adapter = (CursorAdapter) holder.lvAccess.getAdapter();
if (adapter != null) {
Log.i(TAG, "Closing access cursor");
adapter.changeCursor(null);
holder.lvAccess.setAdapter(null);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new LyricCursorAdapter(getActivity(), R.layout.explorer_item,
null, FROM, TO, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mAdapter.setViewBinder(VIEW_BINDER);
setListAdapter(mAdapter);
// Done on a separate thread
getLoaderManager().initLoader(LOADER_ID, null, this);
registerForContextMenu(getListView());
getListView().setTextFilterEnabled(true);
}
@Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
//Context context = holder.itemView.getContext();
//GlideApp.with(context).clear(holder.ivIcon);
CursorAdapter adapter = (CursorAdapter) holder.lvAccess.getAdapter();
if (adapter != null) {
Log.i(TAG, "Closing access cursor");
adapter.changeCursor(null);
holder.lvAccess.setAdapter(null);
}
}
@SuppressWarnings("unchecked")
private void setupAdapterView(final View view, final Bundle savedInstanceState) {
mAdapterView = (AdapterView<CursorAdapter>) view.findViewById(getAdapterViewId());
mAdapter = onCreateAdapter(mAdapterView, savedInstanceState);
mAdapterView.setAdapter(mAdapter);
}
public CursorAdapter onCreateAdapter(final AdapterView<CursorAdapter> adapterView, final Bundle savedInstanceState) {
final int layout = FragmentUtils.getAdapterItemLayout(this.getClass());
final Collection<Binding> bindings = FragmentUtils.getBindings(this.getClass());
final ModernCursorAdapter adapter = new ModernCursorAdapter(getActivity(), layout, bindings);
adapter.setViewBinder(FragmentUtils.createViewBinder(this.getClass()));
return adapter;
}
public void bindViewAtPosition(final int position) {
final CursorAdapter adapter = getCursorAdapter();
final Cursor cursor = adapter.getCursor();
if (cursor != null && cursor.moveToPosition(position)) {
adapter.bindView(getView(), getActivity(), cursor);
}
}
@Override
public CursorAdapter onCreateAdapter(final View view, final Bundle savedInstanceState) {
final Collection<Binding> bindings = FragmentUtils.getBindings(this.getClass());
final ModernItemAdapter adapter = new ModernItemAdapter(getActivity(), bindings);
adapter.setViewBinder(FragmentUtils.createViewBinder(this.getClass()));
return adapter;
}
private void setUpPoemList() {
shareListener = new OnShareClickListener();
deleteListener = new OnDeleteClickListener();
final ListView poemsList = (ListView) findViewById(R.id.poem_history_list);
adapter = new PoemCursorAdapter(
getApplicationContext(),
null,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// MoPub integration
final ViewBinder mopubViewBinder = new ViewBinder.Builder(R.layout.native_ad_layout)
.mainImageId(R.id.native_ad_main_image)
.iconImageId(R.id.native_ad_icon_image)
.titleId(R.id.native_ad_title)
.textId(R.id.native_ad_text)
.build();
MoPubNativeAdPositioning.MoPubServerPositioning adPositioning =
MoPubNativeAdPositioning.serverPositioning();
final MoPubNativeAdRenderer adRenderer = new MoPubNativeAdRenderer(mopubViewBinder);
moPubAdAdapter = new MoPubAdAdapter(this, adapter, adPositioning);
moPubAdAdapter.registerAdRenderer(adRenderer);
poemsList.setAdapter(moPubAdAdapter);
}
private void setLoader() {
CursorAdapter listAdapter = new MostUtilizedListAdapter(getActivity(), null, ACTIVE_LOADER);
if (dashboardType == DashboardType.PHYSICAL) {
cursorAdapterLoader = new CursorAdapterLoader(listAdapter) {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
return DashboardHelper.querySelection(provider, Host.class, activeSelection)
.orderByDescending(CPU_USAGE)
.limit(page * ITEMS_PER_PAGE)
.asLoader();
}
};
} else {
cursorAdapterLoader = new CursorAdapterLoader(listAdapter) {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
return DashboardHelper.querySelection(provider, Vm.class, activeSelection)
.orderByDescending(CPU_USAGE)
.limit(page * ITEMS_PER_PAGE)
.asLoader();
}
};
}
listView.setAdapter(listAdapter);
}
protected void initAdapters() {
final CursorAdapter cursorAdapter = createCursorAdapter();
listView.setAdapter(cursorAdapter);
listView.setEmptyView(getActivity().findViewById(android.R.id.empty));
listView.setTextFilterEnabled(true);
cursorAdapterLoader = new CursorAdapterLoader(cursorAdapter) {
@Override
public synchronized Loader<Cursor> onCreateLoader(int id, Bundle args) {
ProviderFacade.QueryBuilder<E> query = provider.query(entityClass);
appendQuery(query);
final CustomSort customSort = getCustomSort();
if (customSort == null) {
final SortEntry orderBy = (SortEntry) orderBySpinner.getSelectedItem();
final SortOrder order = SortOrderType.getSortOrder((String) orderSpinner.getSelectedItem());
query.orderBy(orderBy.orderBySql(), order);
} else {
for (CustomSort.CustomSortEntry entry : customSort.getSortEntries()) {
query.orderBy(entry.getColumnName(), entry.getSortOrder());
}
}
return query.limit(page * ITEMS_PER_PAGE).asLoader();
}
};
getLoaderManager().initLoader(BASE_LOADER, null, cursorAdapterLoader);
}
@Override
protected CursorAdapter createCursorAdapter() {
SimpleCursorAdapter snapshotListAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.snapshot_list_item,
null,
new String[]{NAME, SNAPSHOT_STATUS, DATE, PERSIST_MEMORYSTATE},
new int[]{R.id.snapshot_description, R.id.snapshot_status, R.id.snapshot_date, R.id.snapshot_persist_memorystate}, 0);
snapshotListAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
TextView textView = (TextView) view;
if (columnIndex == cursor.getColumnIndex(NAME)) {
String name = cursor.getString(columnIndex);
textView.setText(name);
} else if (columnIndex == cursor.getColumnIndex(DATE)) {
String date = DateUtils.convertDateToString(getActivity(), cursor.getLong(columnIndex));
textView.setText(date);
} else if (columnIndex == cursor.getColumnIndex(SNAPSHOT_STATUS)) {
String status = cursor.getString(columnIndex);
textView.setText(status == null ? getString(R.string.NA) : status.replace("_", " ").toUpperCase());
} else if (columnIndex == cursor.getColumnIndex(PERSIST_MEMORYSTATE)) {
textView.setText(getString(R.string.snapshot_memory));
textView.setVisibility((new CursorHelper(cursor)).getBoolean(columnIndex) ? View.VISIBLE : View.GONE);
}
return true;
}
});
return snapshotListAdapter;
}
@Override
protected CursorAdapter createCursorAdapter() {
SimpleCursorAdapter diskListAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.disk_list_item,
null,
new String[]{NAME, SIZE, STATUS},
new int[]{R.id.disk_name, R.id.disk_size, R.id.disk_status}, 0);
diskListAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
TextView textView = (TextView) view;
if (columnIndex == cursor.getColumnIndex(NAME)) {
String name = cursor.getString(columnIndex);
textView.setText(name);
} else if (columnIndex == cursor.getColumnIndex(SIZE)) {
long size = cursor.getLong(columnIndex);
String sizeText = (size == -1) ? getString(R.string.disk_unknown_size) : new MemorySize(size).toString();
textView.setText(sizeText);
} else if (columnIndex == cursor.getColumnIndex(STATUS)) {
String status = cursor.getString(columnIndex);
textView.setText(status == null ? getString(R.string.NA) : status.toUpperCase());
}
return true;
}
});
return diskListAdapter;
}
@Override
protected CursorAdapter createCursorAdapter() {
SimpleCursorAdapter storageDomainListAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.storage_domain_list_item,
null,
new String[]{NAME, STATUS},
new int[]{R.id.storage_domain_name, R.id.storage_domain_status}, 0);
storageDomainListAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == cursor.getColumnIndex(NAME)) {
TextView textView = (TextView) view;
String name = cursor.getString(cursor.getColumnIndex(NAME));
textView.setText(name);
} else if (columnIndex == cursor.getColumnIndex(STATUS)) {
ImageView imageView = (ImageView) view;
String statusString = cursor.getString(cursor.getColumnIndex(STATUS));
imageView.setImageResource(StorageDomainStatus.fromString(statusString).getResource());
}
return true;
}
});
return storageDomainListAdapter;
}
@Override
protected CursorAdapter createCursorAdapter() {
SimpleCursorAdapter diskListAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.disk_list_item,
null,
new String[]{NAME, SIZE, STATUS},
new int[]{R.id.disk_name, R.id.disk_size, R.id.disk_status}, 0);
diskListAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
TextView textView = (TextView) view;
if (columnIndex == cursor.getColumnIndex(NAME)) {
String name = cursor.getString(columnIndex);
textView.setText(name);
} else if (columnIndex == cursor.getColumnIndex(SIZE)) {
long size = cursor.getLong(columnIndex);
String sizeText = (size == -1) ? getString(R.string.disk_unknown_size) : new MemorySize(size).toString();
textView.setText(sizeText);
} else if (columnIndex == cursor.getColumnIndex(STATUS)) {
String status = cursor.getString(columnIndex);
textView.setText(status == null ? getString(R.string.NA) : status.toUpperCase());
}
return true;
}
});
return diskListAdapter;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.session_manager_activity);
mListViewSessions = (ListView) findViewById(R.id.listViewSessions);
getLoaderManager().initLoader(0, null,
new SessionLoaderCallbacks());
mAdapter = new SimpleCursorAdapter(this, R.layout.session_list_row,
null, FROM, TO, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mAdapter.setViewBinder(new SessionViewBinder());
mListViewSessions.setAdapter(mAdapter);
mListViewSessions
.setOnItemClickListener(new SessionOnItemClickListener());
registerForContextMenu(mListViewSessions);
}
public SearchViewAssert hasSuggestionsAdapter(CursorAdapter adapter) {
isNotNull();
CursorAdapter actualAdapter = actual.getSuggestionsAdapter();
assertThat(actualAdapter) //
.overridingErrorMessage("Expected suggestions adapter <%s> but was <%s>.", adapter,
actualAdapter) //
.isSameAs(adapter);
return this;
}
public void setAdapter(CursorAdapter adapter) {
mListPopupWindow.setAdapter(adapter);
mAdapter = adapter;
}
public void setAdapter(CursorAdapter adapter) {
mListPopupWindow.setAdapter(adapter);
mAdapter = adapter;
}
public void setAdapter(CursorAdapter adapter) {
mListPopupWindow.setAdapter(adapter);
mAdapter = adapter;
}
public void setAdapter(CursorAdapter adapter) {
mListPopupWindow.setAdapter(adapter);
mAdapter = adapter;
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(cursor);
mGridView.setVisibility(View.VISIBLE);
mGridView.smoothScrollToPosition(0);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(cursor);
mGridView.setVisibility(View.VISIBLE);
mGridView.smoothScrollToPosition(0);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(cursor);
mGridView.setVisibility(View.VISIBLE);
mGridView.smoothScrollToPosition(0);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
((CursorAdapter) mGridView.getAdapter()).swapCursor(null);
}