无法从URI

时间:2018-01-20 01:38:22

标签: android file imageview uri

我正在尝试加载存储在应用程序文件文件夹中的图像 当我打开活动时,我从logcat获取此错误:

  

1-20 01:30:40.125 14331-14331 / mx.eusaga.af W / ImageView:无法打开   内容:   内容://mx.eusaga.af.fileprovider/imagenes/1-db384fa8-f28b-4595-abbf-d45d38fd4036.jpg                                                            java.io.FileNotFoundException:没有这样的文件或目录                                                                在android.os.Parcel.openFileDescriptor(本机方法)                                                                在android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)                                                                在android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)                                                                在android.support.v4.content.FileProvider.openFile(FileProvider.java:545)                                                                在android.content.ContentProvider.openAssetFile(ContentProvider.java:1322)                                                                在android.content.ContentProvider.openTypedAssetFile(ContentProvider.java:1502)                                                                在android.content.ContentProvider.openTypedAssetFile(ContentProvider.java:1568)                                                                在android.content.ContentProvider $ Transport.openTypedAssetFile(ContentProvider.java:391)                                                                在android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1080)                                                                在android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:921)                                                                在android.content.ContentResolver.openInputStream(ContentResolver.java:646)                                                                在android.widget.ImageView.resolveUri(ImageView.java:768)                                                                在android.widget.ImageView.setImageURI(ImageView.java:429)                                                                在android.support.v7.widget.AppCompatImageView.setImageURI(AppCompatImageView.java:124)                                                                在mx.eusaga.af.Adapter.ImagenAdapter.onBindViewHolder(ImagenAdapter.java:51)                                                                在mx.eusaga.af.Adapter.ImagenAdapter.onBindViewHolder(ImagenAdapter.java:30)                                                                在android.support.v7.widget.RecyclerView $ Adapter.onBindViewHolder(RecyclerView.java:6482)                                                                在android.support.v7.widget.RecyclerView $ Adapter.bindViewHolder(RecyclerView.java:6515)                                                                在android.support.v7.widget.RecyclerView $ Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)                                                                在android.support.v7.widget.RecyclerView $ Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)                                                                在android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5563)                                                                在android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5559)                                                                在android.support.v7.widget.LinearLayoutManager $ LayoutState.next(LinearLayoutManager.java:2229)                                                                在android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:556)                                                                在android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)                                                                在android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)                                                                在android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)                                                                在android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)                                                                在android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3109)                                                                在android.view.View.measure(View.java:17547)                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)                                                                在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)                                                                在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)                                                                在android.widget.LinearLayout.onMeasure(LinearLayout.java:613)                                                                在android.view.View.measure(View.java:17547)                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)                                                                在android.widget.FrameLayout.onMeasure(FrameLayout.java:436)                                                                在android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)                                                                在android.view.View.measure(View.java:17547)                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)                                                                在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)                                                                在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)                                                                在android.widget.LinearLayout.onMeasure(LinearLayout.java:613)                                                                在android.view.View.measure(View.java:17547)                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)                                                                在android.widget.FrameLayout.onMeasure(FrameLayout.java:436)                                                                在android.view.View.measure(View.java:17547)                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)                                                                在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)                                                                在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)                                                             在android.widget.LinearLayout.onMeasure(L

用于获取图像的代码如下:

private Uri obtenerImagen(String archivo) {
    File Directorio = new File(context.getFilesDir() + "/imagenes/");
    Directorio.mkdirs();
    File imagen = new File(Directorio,archivo + ".jpg");
    Uri uri = FileProvider.getUriForFile(context,"mx.eusaga.af.fileprovider",imagen);
    return uri;
}

这是我的文件提供者:

<!-- FileProvider -->
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="mx.eusaga.af.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true" >
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

这些是我的文件路径:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="imagenes" path="imagenes/"/>
</paths>

文件夹 imagenes ,文件 1-db384fa8-f28b-4595-abbf-d45d38fd4036.jpg 存在于正确的文件夹中。

感谢您的帮助!!

4 个答案:

答案 0 :(得分:0)

你有没有试过毕加索:http://square.github.io/picasso/? 您可以使用更少的代码从文件加载图像。

答案 1 :(得分:0)

Ur错误说

FileNotFoundException

表示您提供的路径无效。 Plz检查您的目录和文件路径

答案 2 :(得分:0)

  

您尚未在清单

中添加READ_EXTERNAL_STORAGE预设
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  

在运行时使用以下代码进行权限授予。

    public final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    public static final int NO_RESULT = -5;
    public static final String ALERT_TITLE = "Demo";
  

onCreate()

中的call方法
    askMarshmallowPermissions();




>   private void askMarshmallowPermissions() {
>             List<String> permissionsNeeded = new ArrayList<String>();
>     
>             final List<String> permissionsList = new ArrayList<String>();
>     
>             if (!addPermission(permissionsList, android.Manifest.permission.WRITE_EXTERNAL_STORAGE))
>                 permissionsNeeded.add("Write to storage");
>     
>             if (permissionsList.size() > 0) {
>                 if (permissionsNeeded.size() > 0) {
>                     // Need Rationale
>                     String message = "You need to grant access to " + permissionsNeeded.get(0);
>                     for (int i = 1; i < permissionsNeeded.size(); i++)
>                         message = message + ", " + permissionsNeeded.get(i);
>                     showMessageOKCancel(message,
>                             new DialogInterface.OnClickListener() {
>                                 @Override
>                                 public void onClick(DialogInterface dialog, int which) {
>                                     ActivityCompat.requestPermissions(MainActivity.this,
>                                             permissionsList.toArray(new String[permissionsList.size()]),
>                                             REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
>                                 }
>                             });
>                     return;
>                 }
>                 ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
>                         REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
>                 return;
>             }
>             callAfterPermission();
>         }
>     
>       
>       private void callAfterPermission() {
>           // your code after premission granted.
>       }



    private boolean addPermission(List<String> permissionsList, String permission) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission))
                    return false;
            }
        }
        return true;
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showAlertDialogWithFinishActivity(MainActivity.this,
                                "01 - Please grant all required permissions to " +
                                        "continue running the app. Please Restart the App and allow Permissions.",
                                ALERT_TITLE, true, NO_RESULT, null);
                    }
                })
                .create()
                .show();
    }

  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);

                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for ACCESS_FINE_LOCATION
                if (perms.get(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

                    callAfterPermission();
                } else {

                    showAlertDialogWithFinishActivity(MainActivity.this,
                            "02 - Please grant all required permissions to " +
                                    "continue running the app. Please restart the app and allow permissions.",
                            ALERT_TITLE, true, NO_RESULT, null);
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

答案 3 :(得分:0)

 String folderpath = "/data/data/" + getPackageName() + "/files";
 String imagefolderpath = "/data/data/" + getPackageName() + "/files" +  "/images";

 File fileFolder = new File(folderpath);
        // check if file Folder exists, if not create one and its subfolders
        if (!fileFolder.exists()) {
            fileFolder.mkdir();
        }

File imageFolder = new File(imagefolderpath);
        // check if image Folder exists, if not create one and its subfolders
        if (!imageFolder.exists()) {
            imageFolder.mkdir();
        }

String imageFilePath = imageFolder + "/test.jpg";

File imagePath = new File(imageFilePath);
if (!imageFolder.exists()) {
    Log.d("Log","Image not exists");
}