无法使用setImageUri在listView上显示图像

时间:2018-06-01 09:59:09

标签: android imageview recycler-adapter android-room

我将用户的图像uri保存为RoomDatabase中的字符串。 这就是我所知道的我不知道如何克服这个错误并显示将图像显示到RecyclerView中,我已经阅读了一些关于位图和etcetra的内容但是无法理解或使用它们进行编码。

RecyclerAdapter.java

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

Student current = students.get(position);
holder.nameItemView.setText(current.getName());
holder.numberItemView.setText(current.getNumber());

 ///here!
Uri uri = Uri.parse(current.getImagePath());
    holder.studImage.setImageURI(uri);

}
listView上的

它不显示图像。 我检查了调试器并看到了这个错误:

ava.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{5ca0d63 20181:com.example.android.studmanagedbtrain/u0a92} (pid=20181, uid=10092) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
             at android.os.Parcel.readException(Parcel.java:2004)
W/ImageView: Unable to open content: content:/com.android.providers.media.documents/document/image%3A42
             java.io.FileNotFoundException: No content provider: content:/com.android.providers.media.documents/document/image%3A42
                 at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1396)
                 at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1247)
                 at android.content.ContentResolver.openInputStream(ContentResolver.java:967)
                 at android.widget.ImageView.getDrawableFromUri(ImageView.java:951)
                 at android.widget.ImageView.resolveUri(ImageView.java:922)
                 at android.widget.ImageView.setImageURI(ImageView.java:531)
                 at .
                   etc.
                   etc.
                 .
                 at android.os.Handler.handleCallback(Handler.java:790)
                 at android.os.Handler.dispatchMessage(Handler.java:99)
                 at android.os.Looper.loop(Looper.java:164)
                 at android.app.ActivityThread.main(ActivityThread.java:6494)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
             resolveUri failed on bad bitmap uri: content:/com.android.providers.media.documents/document/image%3A42

5 个答案:

答案 0 :(得分:1)

使用Picasso库加载图片,如下所示:

 Picasso.with(mContext).load(imageUrl).into(promotionImageView)

答案 1 :(得分:1)

  

您从文件中获取Uri的方式可能存在问题

 Uri Uri = getUriFromFilePath(MainActivity.this, PhotoFilePath);

 public Uri getUriFromFilePath(Context ctx, File filePath) {
        Uri requirdUri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            requirdUri = FileProvider.getUriForFile(ctx,
                    ctx.getApplicationContext().getPackageName() + PROVIDER_FILE_EXTENSION,
                    filePath);
        } else {
            requirdUri = Uri.fromFile(filePath);
        }

        return requirdUri;
    }
  

在资源中创建路径文件 - > XML       RES / XML / paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
    <root-path
        name="external_files"
        path="/storage/"/>
</paths>
  

在应用程序标记

中的manifest.xml文件中添加提供程序
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.demo.example.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/paths"/>
</provider>

答案 2 :(得分:0)

使用Picasso库从网址高效加载图片。

答案 3 :(得分:0)

请试试这个,

Uri uri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
imgView.setImageURI(null); 
imgView.setImageURI(uri);

希望它会有所帮助。

答案 4 :(得分:0)

尝试使用以下方法

public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
            String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }