使用CursorLoader与LoaderManager从Android应用程序中检索图像

3

目前我正在使用getContentResolver().query()/managedQuery()来获取指向从相册应用程序检索图像的光标。由于我使用的API部分已过时,所以我想使用带有LoaderManager的CursorLoader。

/**
 * Creates a cursor to access the content defined by the image uri for API
 * version 11 and newer.
 * 
 * @return The created cursor.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private Cursor createCursorHoneycomb() {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);

    return cursor;
}

/**
 * Creates a cursor to access the content defined by the image uri from API
 * version 8 to 10.
 * 
 * @return The created cursor.
 */
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.FROYO)
private Cursor createCursorFroyo() {
    String[] projection = {
            MediaStore.Images.Media.DATA
    };
    Cursor cursor = managedQuery(imageUri, projection, null, null, null);

    return cursor;
}

由于我没有ListView,所以我不使用任何适配器。我只为ImageView设置图像位图。

/**
 * Sets the image bitmap for the image view.
 */
private void setupImageView() {
    String imagePath = getImagePathFromUri(imageUri);
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    ImageView imageView = (ImageView) findViewById(R.id.image_view);

    imageView.setImageBitmap(bitmap);
}

/**
 * Returns an image path created from the supplied image uri.
 * 
 * @param imageUri The supplied image uri.
 * @return Returns the created image path.
 */
@SuppressWarnings("deprecation")
private String getImagePathFromUri(Uri imageUri) {
    Cursor cursor = null;
    String imagePath = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        cursor = createCursorHoneycomb();
    } else {
        cursor = createCursorFroyo();
    }

    // if image is loaded from gallery
    if (cursor != null) {
        startManagingCursor(cursor);

        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();
        imagePath = cursor.getString(columnIndex);
    }
    // if image is loaded from file manager
    else {
        imagePath = imageUri.getPath();
    }

    return imagePath;
}

可以使用CursorLoader和LoaderManager从相册应用或文件管理器中加载图像吗?我找不到任何解决方案。

3个回答

9

需要时调用getSupportLoaderManager启动加载器管理器。

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

然后创建一个游标加载器,用于检索图像路径。
@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;
}

光标加载器完成后,它将使用检索到的数据来更新用户界面。

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

这很容易做到。但是我必须理解如何使用onCreateLoader()和onLoadFinished()。


你能否在这里与我分享你的整个代码?我非常需要做同样的事情(但使用MediaStore音频),无论我做什么,OnLoadFinished都不会被调用。提前感谢你的慷慨。 - dariusiv
它一直提示我在 public Loader<Cursor> onCreateLoader(int id, Bundle args) 中将返回类型更改为 CursorLoader。请帮帮我。 - Rahul Upadhyay
@dariusiv:你必须通过 getLoaderManager().initLoader(<id>, <args>, <callback>) 来启动加载器,通常是 getLoaderManager().initLoader(0, null, this) - Marcus Husar

2

您可能希望将此替换为

Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);

使用这个方法

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

0
能否使用CursorLoader和LoaderManager从图库应用程序或文件管理器中加载图片?
只有在他们发布、文档化和支持ContentProvider的情况下才可以。

感谢您的回答,CommonsWare。目前我必须接受没有更好的解决方案这一事实。我会尝试寻找更好的解决方案。 - Marcus Husar
最终我找到了解决方案。请看下面的答案。 - Marcus Husar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接