下面列出了怎么用android.content.Loader的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String s = mNegative ? "<" : ">";
SQLiteLoader retVal = new SQLiteLoader(
getActivity(),
mHelper,
"log",
new String[] { "description", "cents", "time", "_id" },
"envelope = ? AND cents "+s+" 0",
new String[] {Integer.toString(mId)},
null,
null,
"time * -1"
);
retVal.setNotificationUri(EnvelopesOpenHelper.URI);
return retVal;
}
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
if (data != null && data.moveToNext()) {
/*
* Here we have to check the column indexes by name as we have requested for all. The order may be different.
*/
final String fileName = data.getString(data.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)/* 0 DISPLAY_NAME */);
final int fileSize = data.getInt(data.getColumnIndex(MediaStore.MediaColumns.SIZE) /* 1 SIZE */);
String filePath = null;
final int dataIndex = data.getColumnIndex(MediaStore.MediaColumns.DATA);
if (dataIndex != -1)
filePath = data.getString(dataIndex /* 2 DATA */);
if (!TextUtils.isEmpty(filePath))
this.filePath = filePath;
updateFileInfo(fileName, fileSize, fileType);
} else {
fileNameView.setText(null);
fileTypeView.setText(null);
fileSizeView.setText(null);
filePath = null;
fileStreamUri = null;
fileStatusView.setText(R.string.dfu_file_status_error);
statusOk = false;
}
}
public Loader<Cursor> onCreateLoader(final int id, Bundle bundle) {
CursorLoader cursorLoader = null;
switch (id) {
case LOADER_USER_PHOTOS_EXTERNAL:
String selection = null;
String[] selectionArgs = null;
if (null != bundle
&& bundle.containsKey(LOADER_PHOTOS_BUCKETS_PARAM)) {
selection = Images.Media.BUCKET_ID + " = ?";
selectionArgs = new String[] { bundle
.getString(LOADER_PHOTOS_BUCKETS_PARAM) };
}
cursorLoader = new PhotupCursorLoader(getActivity(),
MediaStoreCursorHelper.MEDIA_STORE_CONTENT_URI,
MediaStoreCursorHelper.PHOTOS_PROJECTION, selection,
selectionArgs, MediaStoreCursorHelper.PHOTOS_ORDER_BY,
false);
break;
}
return cursorLoader;
}
/**
* create new cursor with specific projection
*
* @param id
* @param args
* @return
*/
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projectALL = new String[]{"*"};
String selection = null;
if (args != null) {
String searchRecord = args.getString("SEARCH_KEY");
if (searchRecord != null && searchRecord.length() > 0) {
selection = RecordDbContract.RecordItem.COLUMN_NUMBER + " LIKE '%" + searchRecord + "%'";
}
}
String sort = mPreferenceHelper.getSortSelection()
+ mPreferenceHelper.getSortArrange();
return new CursorLoader(getActivity(), RecordDbContract.CONTENT_URL, projectALL, selection, null, sort);
}
@Override
public Loader onCreateLoader(int picker_type, Bundle bundle) {
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
Uri queryUri = MediaStore.Files.getContentUri("external");
CursorLoader cursorLoader = new CursorLoader(
mContext,
queryUri,
MEDIA_PROJECTION,
selection,
null, // Selection args (none).
MediaStore.Files.FileColumns.DATE_ADDED + " DESC" // Sort order.
);
return cursorLoader;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
@Override
public Loader<Cursor> getCursorLoader() {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), LoginPresenterImpl.ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
mAdapter.swapCursor(data);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
int limit = args.getInt(TAG, getFetchSize());
return CatnutUtils.getCursorLoader(
getActivity(),
CatnutProvider.parse(Comment.MULTIPLE),
PROJECTION,
null,
null,
Comment.TABLE + " as c",
"inner join " + User.TABLE + " as u on c.uid=u._id",
"c." + BaseColumns._ID + " desc",
String.valueOf(limit)
);
}
@Override
public void onLoadFinished(Loader<String> loader, String data) {
pbProgressBar.setVisibility(View.GONE);
try {
JSONObject baseJsonResponse = new JSONObject(data);
JSONArray res = baseJsonResponse.getJSONArray("result");
for (int i = 0; i < res.length(); i++) {
JSONObject currentContest = res.getJSONObject(i);
int change = currentContest.getInt("newRating") - currentContest.getInt("oldRating");
Contest contest =
new Contest(
currentContest.getInt("contestId"),
currentContest.getString("contestName"),
currentContest.getInt("rank"),
currentContest.getInt("oldRating"),
change,
currentContest.getInt("newRating"));
contestList.add(contest);
}
} catch (JSONException e) {
e.printStackTrace();
}
contestList = reverse(contestList);
if (contestList.size() == 0) {
tvEmptyList.setVisibility(View.VISIBLE);
filterMenuItem.setVisible(false);
} else {
recyclerView.setVisibility(View.VISIBLE);
filterMenuItem.setVisible(true);
adapter.notifyDataSetChanged();
}
positiveNegativeChangeList(contestList);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onChange(boolean selfChange) {
if (!isAdded()) {
return;
}
//Reload data
LoaderManager lm = getLoaderManager();
Loader<Cursor> loader = lm.getLoader(0);
if (loader != null) {
loader.forceLoad();
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Hide the progress bar when the loading is finished.
ProgressBar progressBar = findViewById(R.id.progressBar_album);
progressBar.setVisibility(View.GONE);
// Set the text of the empty view
mEmptyTV.setText(R.string.no_audio_files);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
// Set album cover
String coverPath = cursor.getString(cursor.getColumnIndex(AnchorContract.AlbumEntry.TABLE_NAME + AnchorContract.AlbumEntry.COLUMN_COVER_PATH));
coverPath = mDirectory + File.separator + coverPath;
int reqSize = getResources().getDimensionPixelSize(R.dimen.album_info_height);
BitmapUtils.setImage(mAlbumInfoCoverIV, coverPath, reqSize);
// Set the album info time
int[] times = DBAccessUtils.getAlbumTimes(this, mAlbumId);
Log.e("AlbumActivity", "Update AlbumLastCompletedTime");
if (mPlayer != null) {
mCurrAudioLastCompletedTime = mPlayer.getCurrentAudioFile().getCompletedTime();
mCurrUpdatedAudioId = mPlayer.getCurrentAudioFile().getId();
}
mAlbumLastCompletedTime = times[0];
mAlbumDuration = times[1];
String timeStr = Utils.getTimeString(this, times[0], times[1]);
mAlbumInfoTimeTV.setText(timeStr);
}
}
mAlbumInfoTitleTV.setText(mAlbumName);
// Swap the new cursor in. The framework will take care of closing the old cursor
mCursorAdapter.swapCursor(cursor);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Get the details fragment
DetailsFragment fragment = (DetailsFragment) getFragmentManager()
.findFragmentById(R.id.fragment_details);
// Is details fragment visible?
if (fragment != null && fragment.isVisible() && cursor.getCount() == 0) {
fragment.updateView(-1);
Toast.makeText(getActivity(), "No data", Toast.LENGTH_LONG).show();
}
Log.d(TAG, "onLoadFinished with cursor: " + cursor.getCount());
mAdapter.swapCursor(cursor);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
Bundle extras = cursor.getExtras();
int totalSize = extras.getInt(ContentResolver.EXTRA_TOTAL_SIZE);
mAdapter.setTotalSize(totalSize);
int beforeCount = mAdapter.getFetchedItemCount();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor.getColumnIndex(
ImageContract.Columns.DISPLAY_NAME));
String absolutePath = cursor.getString(cursor.getColumnIndex(
ImageContract.Columns.ABSOLUTE_PATH));
ImageAdapter.ImageDocument imageDocument = new ImageAdapter.ImageDocument();
imageDocument.mAbsolutePath = absolutePath;
imageDocument.mDisplayName = displayName;
mAdapter.add(imageDocument);
}
int cursorCount = cursor.getCount();
if (cursorCount == 0) {
return;
}
Activity activity = ImageClientFragment.this.getActivity();
mAdapter.notifyItemRangeChanged(beforeCount, cursorCount);
int offsetSnapShot = mOffset.get();
String message = activity.getResources()
.getString(R.string.fetched_images_out_of, offsetSnapShot + 1,
offsetSnapShot + cursorCount, totalSize);
mOffset.addAndGet(cursorCount);
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
}
/**
* Data loader event
*
* @param loader
*/
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// data is not available anymore, delete reference
// setAdapter();
adapter = null;
expandableListView.setAdapter(adapter);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
mAdapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
mAdapter.swapCursor(data);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selection = mSelection;
boolean search = args.getBoolean(SEARCH_TWEET);
if (search) {
if (!TextUtils.isEmpty(mCurFilter)) {
selection = new StringBuilder(mSelection)
.append(" and ").append(Status.columnText)
.append(" like ").append(CatnutUtils.like(mCurFilter))
.toString();
} else {
search = false;
}
}
int limit = args.getInt(TAG, getFetchSize());
return CatnutUtils.getCursorLoader(
getActivity(),
CatnutProvider.parse(Status.MULTIPLE),
PROJECTION,
selection,
null,
Status.TABLE,
null,
BaseColumns._ID + " desc",
search ? null : String.valueOf(limit)
);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
//addEmailsToAutoComplete(emails);
}
@Override
public void onLoadFinished(Loader<List<Earthquake>> loader, List<Earthquake> earthquakes) {
Log.i(LOG_TAG, "onLoadFinished()");
findViewById(R.id.progress).setVisibility(View.GONE);
((TextView) findViewById(R.id.empty_state)).setText(R.string.no_earthquakes_found);
// Clear the adapter of previous earthquake data
mAdapter.clear();
/// If there is a valid list of {@link Earthquake}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (earthquakes != null && !earthquakes.isEmpty()) {
mAdapter.addAll(earthquakes);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == 0) {
return new CursorLoader(this, Calls.CONTENT_URI, LogEntryAdapter.PROJECTION, null, null, Calls.DEFAULT_SORT_ORDER);
} else {
return new CursorLoader(this, Phone.CONTENT_URI, ContactsEntryAdapter.PROJECTION, Phone.HAS_PHONE_NUMBER+"=1", null, Phone.DISPLAY_NAME);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this,
deviceUri,
new String[] {DevicesContract.Device.MODEL,
DevicesContract.Device.NICKNAME,
DevicesContract.Device.DISPLAY_SIZE_INCHES,
DevicesContract.Device.MEMORY_MB,
DevicesContract.Device._ID},
null,
null,
null);
}
@Override
public Loader<Cursor> onCreateLoader(int loaderIndex, Bundle args) {
// Where the Contactables table excels is matching text queries,
// not just data dumps from Contacts db. One search term is used to query
// display name, email address and phone number. In this case, the query was extracted
// from an incoming intent in the handleIntent() method, via the
// intent.getStringExtra() method.
// BEGIN_INCLUDE(uri_with_query)
String query = args.getString(QUERY_KEY);
Uri uri = Uri.withAppendedPath(
CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);
// END_INCLUDE(uri_with_query)
// BEGIN_INCLUDE(cursor_loader)
// Easy way to limit the query to contacts with phone numbers.
String selection =
CommonDataKinds.Contactables.HAS_PHONE_NUMBER + " = " + 1;
// Sort results such that rows for the same contact stay together.
String sortBy = CommonDataKinds.Contactables.LOOKUP_KEY;
return new CursorLoader(
mContext, // Context
uri, // URI representing the table/resource to be queried
null, // projection - the list of columns to return. Null means "all"
selection, // selection - Which rows to return (condition rows must match)
null, // selection args - can be provided separately and subbed into selection.
sortBy); // string specifying sort order
// END_INCLUDE(cursor_loader)
}
@Override
public Loader<List<Contact>> onCreateLoader(int id, Bundle args) {
return new AsyncTaskLoaderExample<List<Contact>>(getActivity()) {
@Override
public List<Contact> loadInBackground() {
return new Select().from(Contact.class).queryList();
}
};
}
@Override
public Loader<List<DetailEntry>> onCreateLoader(int id, Bundle args) {
StorageService storageService = new LocalStorageService(getActivity());
DetailService detailService = new FlatFileDetailService(storageService);
MasterDetailLoader loader = new MasterDetailLoader(getActivity(), detailService);
callbacks.onLoaderCreated(loader);
return loader;
}