Using CursorLoader with LoaderManager to retrieve images from android apps

谁说我不能喝 提交于 2019-11-28 14:08:52

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();
}

It’s quite easy to do. But I had to understand how to use onCreateLoader() and onLoadFinished().

You may want to replace this

Cursor cursor = managedQuery(imageUri, projection, null, null, null);

with this

CursorLoader cursorLoader = new CursorLoader(this, imageUri,
projection, null, null, null);
Cursor cursor = CursorLoader.loadInBackground();

Is it possible to use CursorLoader with LoaderManager to load images from the gallery app or a file manager?

Only if they publish, document, and support a ContentProvider.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!