Start the loader manager by invoking getSupportLoaderManager when it is needed.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
imageUri = data.getData();
getSupportLoaderManager().initLoader(0, null, this);
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Action canceled.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Action failed!", Toast.LENGTH_LONG).show();
}
}
}
Then create a cursor loader that is used to retrieve the image path.
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
MediaStore.Images.Media.DATA
};
CursorLoader cursorLoader = new CursorLoader(this, imageUri, projection, null, null, null);
return cursorLoader;
}
When the cursor loader is finished it uses the retrieved data to update the UI.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null) {
int columnIndex = data.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
data.moveToFirst();
imagePath = data.getString(columnIndex);
} else {
imagePath = imageUri.getPath();
}
setupImageView();
}