下面列出了怎么用android.support.v4.widget.CursorAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
private void deleteAll(){
ListView notesList = (ListView) findViewById(R.id.notes_list);
CursorAdapter ca = (CursorAdapter) notesList.getAdapter();
Cursor c = ca.getCursor();
c.moveToPosition(-1);
while (c.moveToNext()){
if (c.getInt(c.getColumnIndexOrThrow(DbContract.NoteEntry.COLUMN_TYPE)) == DbContract.NoteEntry.TYPE_AUDIO) {
String filePath = getFilesDir().getPath()+"/audio_notes" + c.getString(c.getColumnIndexOrThrow(DbContract.NoteEntry.COLUMN_CONTENT));
new File(filePath).delete();
} else if (c.getInt(c.getColumnIndexOrThrow(DbContract.NoteEntry.COLUMN_TYPE)) == DbContract.NoteEntry.TYPE_SKETCH) {
String content = c.getString(c.getColumnIndexOrThrow(DbContract.NoteEntry.COLUMN_CONTENT));
new File(getFilesDir().getPath()+"/sketches"+content).delete();
new File(getFilesDir().getPath()+"/sketches"+content.substring(0, content.length()-3) + "jpg").delete();
}
DbAccess.deleteNote(getBaseContext(), c.getInt(c.getColumnIndexOrThrow(DbContract.NoteEntry.COLUMN_ID)));
}
updateList();
}
/**
* Init ListView with commands.
*
* @param pi
*/
private void initListView(RaspberryDeviceBean pi) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
fullCommandCursor = deviceDb.getFullCommandCursor();
return null;
}
@Override
protected void onPostExecute(Void r) {
CommandAdapter commandsAdapter = new CommandAdapter(CustomCommandActivity.this, fullCommandCursor, CursorAdapter.FLAG_AUTO_REQUERY);
commandListView.setAdapter(commandsAdapter);
commandListView.setOnItemClickListener(CustomCommandActivity.this);
// commandListView.setOnItemLongClickListener(CustomCommandActivity.this);
registerForContextMenu(commandListView);
}
}.execute();
}
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_LIBRARY_UPDATE.equals(intent.getAction())) {
Log.d(LOG_TAG, "library update broadcast received");
// TODO
} else if (ACTION_BADGE_EARNED.equals(intent.getAction()) && dataService != null) {
Badge badge = (Badge) intent.getSerializableExtra(EXTRA_BADGE);
dataService.getAPIAdapter().toastBadge(badge);
} else if (Constants.ACTION_OFFLINE_VIDEO_SET_CHANGED.equals(intent.getAction())) {
((CursorAdapter) gridView.getAdapter()).changeCursor(getCursor());
setCancelButtonEnabled(areDownloadsEnqueued());
setupListNavigation();
} else if (ACTION_DOWNLOAD_PROGRESS_UPDATE.equals(intent.getAction())) {
@SuppressWarnings("unchecked")
Map<String, Integer> status = (Map<String, Integer>) intent.getSerializableExtra(EXTRA_STATUS);
Adapter adapter = (Adapter) gridView.getAdapter();
adapter.setCurrentDownloadStatus(status);
adapter.updateBars();
} else if (ACTION_TOAST.equals(intent.getAction())) {
Toast.makeText(ManageDownloadsActivity.this, intent.getStringExtra(EXTRA_MESSAGE), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_logcat);
LogLine.isScrubberEnabled = PreferenceHelper.isScrubberEnabled(this);
handleShortcuts(getIntent().getStringExtra("shortcut_action"));
mHandler = new Handler(Looper.getMainLooper());
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogHelper.stopRecordingLog(LogcatActivity.this);
}
});
binding.list.setLayoutManager(new LinearLayoutManager(this));
binding.list.setItemAnimator(null);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar_actionbar));
setTitle(R.string.logcat);
mCollapsedMode = !PreferenceHelper.getExpandedByDefaultPreference(this);
log.d("initial collapsed mode is %s", mCollapsedMode);
mSearchSuggestionsAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_dropdown,
null,
new String[]{"suggestion"},
new int[]{android.R.id.text1},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setUpAdapter();
updateBackgroundColor();
runUpdatesIfNecessaryAndShowWelcomeMessage();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_logcat);
LogLine.isScrubberEnabled = PreferenceHelper.isScrubberEnabled(this);
handleShortcuts(getIntent().getStringExtra("shortcut_action"));
mHandler = new Handler(Looper.getMainLooper());
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogHelper.stopRecordingLog(LogcatActivity.this);
}
});
binding.list.setLayoutManager(new LinearLayoutManager(this));
binding.list.setItemAnimator(null);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar_actionbar));
setTitle(R.string.logcat);
mCollapsedMode = !PreferenceHelper.getExpandedByDefaultPreference(this);
log.d("initial collapsed mode is %s", mCollapsedMode);
mSearchSuggestionsAdapter = new SimpleCursorAdapter(this,
R.layout.list_item_dropdown,
null,
new String[]{"suggestion"},
new int[]{android.R.id.text1},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setUpAdapter();
updateBackgroundColor();
runUpdatesIfNecessaryAndShowWelcomeMessage();
}
public CalendarCursorAdapter(Context context) {
super(context,
R.layout.list_item_calendar,
null,
new String[]{CalendarContract.Calendars.CALENDAR_DISPLAY_NAME},
new int[]{R.id.text_view_title},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
/**
* Setting up the views here.
*/
public void setUpViews() {
final CursorAdapter suggestionAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
new String[]{SearchManager.SUGGEST_COLUMN_TEXT_1},
new int[]{android.R.id.text1},
0);
final List<String> suggestions = new ArrayList<>();
spinnerHelpArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, helptopicItems); //selected item will look like a spinner set from XML
spinnerHelpArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerHelpTopic.setAdapter(spinnerHelpArrayAdapter);
spinnerSLAAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,slaItems); //selected item will look like a spinner set from XML
spinnerSLAAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSLA.setAdapter(spinnerSLAAdapter);
spinnerPriArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, priorityItems); //selected item will look like a spinner set from XML
spinnerPriArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPriority.setAdapter(spinnerPriArrayAdapter);
editTextLastName.setFilters(new InputFilter[]{filter});
editTextFirstName.setFilters(new InputFilter[]{filter});
subEdittext.setFilters(new InputFilter[]{filter});
}
private void requestPermissions(final Activity thisActivity, View videosFragmentView) {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
MainActivity.permissionsSnackbar = Snackbar.make(videosFragmentView, "Storage access permission is required to scan and play media files on this device.", Snackbar.LENGTH_INDEFINITE)
.setAction("OK", new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MainActivity.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
MainActivity.permissionsSnackbar.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MainActivity.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Video.VideoColumns.DISPLAY_NAME, MediaStore.Video.VideoColumns.DATA, MediaStore.Video.VideoColumns._ID};
Cursor c = getActivity().getContentResolver().query(uri, projection, null, null, null);
mAdapter = new VideosAdapter(getActivity(), c, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
}
@Override
public void prepareSearchSuggestions(List<DrawerItemCategory> navigation) {
final String[] from = new String[]{"categories"};
final int[] to = new int[]{android.R.id.text1};
searchSuggestionsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
if (navigation != null && !navigation.isEmpty()) {
for (int i = 0; i < navigation.size(); i++) {
if (!searchSuggestionsList.contains(navigation.get(i).getName())) {
searchSuggestionsList.add(navigation.get(i).getName());
}
if (navigation.get(i).hasChildren()) {
for (int j = 0; j < navigation.get(i).getChildren().size(); j++) {
if (!searchSuggestionsList.contains(navigation.get(i).getChildren().get(j).getName())) {
searchSuggestionsList.add(navigation.get(i).getChildren().get(j).getName());
}
}
}
}
searchSuggestionsAdapter.notifyDataSetChanged();
} else {
Timber.e("Search suggestions loading failed.");
searchSuggestionsAdapter = null;
}
}
private void deleteSelectedItems(){
ListView notesList = (ListView) findViewById(R.id.notes_list);
CursorAdapter adapter = (CursorAdapter) notesList.getAdapter();
SparseBooleanArray checkedItemPositions = notesList.getCheckedItemPositions();
for (int i=0; i < checkedItemPositions.size(); i++) {
if(checkedItemPositions.valueAt(i)) {
DbAccess.trashNote(getBaseContext(), (int) (long) adapter.getItemId(checkedItemPositions.keyAt(i)));
}
}
}
private void updateList() {
ListView notesList = (ListView) findViewById(R.id.notes_list);
CursorAdapter adapter = (CursorAdapter) notesList.getAdapter();
String selection = DbContract.NoteEntry.COLUMN_TRASH + " = ?";
String[] selectionArgs = { "1" };
adapter.changeCursor(DbAccess.getCursorAllNotes(getBaseContext(), selection, selectionArgs));
}
private void deleteItem(int position) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean delNotes = sp.getBoolean(SettingsActivity.PREF_DEL_NOTES, false);
CursorAdapter adapter = (CursorAdapter) list.getAdapter();
if (delNotes) {
DbAccess.trashNotesByCategoryId(getBaseContext(), (int) (long) adapter.getItemId(position));
}
DbAccess.deleteCategory(getBaseContext(), (int) (long) adapter.getItemId(position));
updateList();
}
private void deleteSelectedItems(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean delNotes = sp.getBoolean(SettingsActivity.PREF_DEL_NOTES, false);
CursorAdapter adapter = (CursorAdapter) list.getAdapter();
SparseBooleanArray checkedItemPositions = list.getCheckedItemPositions();
for (int i=0; i < checkedItemPositions.size(); i++) {
if(checkedItemPositions.valueAt(i)) {
if (delNotes) {
DbAccess.trashNotesByCategoryId(getBaseContext(), (int) (long) adapter.getItemId(checkedItemPositions.keyAt(i)));
}
DbAccess.deleteCategory(getBaseContext(), (int) (long) adapter.getItemId(checkedItemPositions.keyAt(i)));
}
}
}
@Override
public CursorAdapter onCreateAdapter(final View view, final Bundle savedInstanceState) {
final Collection<Binding> bindings = FragmentUtils.getBindings(this.getClass());
final SupportItemAdapter adapter = new SupportItemAdapter(getActivity(), bindings);
adapter.setViewBinder(FragmentUtils.createViewBinder(this.getClass()));
return adapter;
}
@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 SupportCursorAdapter adapter = new SupportCursorAdapter(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 boolean onSuggestionClick(int position) {
CursorAdapter selectedView = searchView.getSuggestionsAdapter();
Cursor cursor = (Cursor) selectedView.getItem(position);
int index = cursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_1);
searchView.setQuery(cursor.getString(index), true);
return true;
}
/**
* @param context the Context
* @param c full device cursor
* @param alwaysWithUserHost true, if [email protected] should always be displayed (not only in dropdown view)
*/
public DeviceSpinnerAdapter(Context context, Cursor c, boolean alwaysWithUserHost) {
super(context, alwaysWithUserHost ? R.layout.device_row_dropdown : R.layout.device_row,
c, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void resetListContents(String topicId) {
Log.d(LOG_TAG, "resetListContents");
if (topicId != null) {
// Set this.topicCursor to a cursor over the videos we need.
User user = dataService.getAPIAdapter().getCurrentUser();
String userId = user == null ? "" : user.getNickname();
String sql = "select video._id, video.youtube_id, video.readable_id, video.title " +
", uservideo.seconds_watched, uservideo.completed " +
"from topicvideo, video " +
"left outer join uservideo on uservideo.video_id = video.readable_id and uservideo.user_id=? " +
"where topicvideo.topic_id=? and topicvideo.video_id=video.readable_id ";
String[] selectionArgs;
if (isShowingDownloadedVideosOnly()) {
sql += " and video.download_status=? ";
selectionArgs = new String[] {userId, topicId, String.valueOf(Video.DL_STATUS_COMPLETE)};
} else {
selectionArgs = new String[] {userId, topicId};
}
sql += "order by video.seq";
if (topicCursor != null) {
topicCursor.close();
}
topicCursor = this.dataService.getHelper().getReadableDatabase()
.rawQuery(sql, selectionArgs);
CursorAdapter adapter = getUnwrappedAdapter();
if (adapter != null) {
adapter.changeCursor(topicCursor);
}
}
}
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 onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
((CursorAdapter) this.getListAdapter()).swapCursor(cursor);
setListShown(true);
}
public void onLoaderReset(Loader<Cursor> loader) {
((CursorAdapter) this.getListAdapter()).swapCursor(null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
((CursorAdapter) this.getListAdapter()).swapCursor(cursor);
setListShown(true);
}
public void onLoaderReset(Loader<Cursor> loader) {
((CursorAdapter) this.getListAdapter()).swapCursor(null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
((CursorAdapter) this.getListAdapter()).swapCursor(cursor);
setListShown(true);
}
public void onLoaderReset(Loader<Cursor> loader) {
((CursorAdapter) this.getListAdapter()).swapCursor(null);
}
private void updateList(){
CursorAdapter adapter = (CursorAdapter) list.getAdapter();
adapter.changeCursor(DbAccess.getCategoriesWithoutDefault(getBaseContext()));
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
((CursorAdapter)getListAdapter()).changeCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
((CursorAdapter)getListAdapter()).changeCursor(null);
}