FileNotFoundException:内容提供者不支持任何文件

时间:2017-09-22 14:24:43

标签: java android xml

每当我尝试使用相机意图拍摄照片时,我都会出错。

这是错误

FileNotFoundException: No files supported by provider at content://com.example.fahad.inventory/my_images/dcim/Inventory/JPEG20170922_170324_1975076666.jpg

 at com.example.fahad.inventory.AddProductActivity.getBitmap(AddProductActivity.java:270) 09-22 17:03:30.117 12950-12950/? W/System.err:     at com.example.fahad.inventory.AddProductActivity.onActivityResult(AddProductActivity.java:197)

这是我的代码

public class AddProductActivity extends AppCompatActivity {

private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_SELECT_IMAGE = 2;

private static final String IMAGE_PATH = "imagePath";
private static final String IMAGE_URI = "imageUri";
private static final String BITMAP = "bitmap";

private static final String CAMERA_DIR = "/dcim/";

private String imagePath = "";
private String imageUri = "";

private ImageView imageView;
private Bitmap bitmap;

private Uri mUri;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_product);

    Button addProduct = (Button) findViewById(R.id.id_btn_add_product);
    Button addImage = (Button) findViewById(R.id.id_btn_add_image);
    Button addGalleryImage = (Button) findViewById(R.id.id_btn_add_gallery_image);

    imageView = (ImageView) findViewById(R.id.id_image_view);

    if (savedInstanceState != null) {
        imagePath = savedInstanceState.getString(IMAGE_PATH);
        imageUri = savedInstanceState.getString(IMAGE_URI);
        bitmap = (Bitmap) savedInstanceState.get(BITMAP);
        imageView.setImageBitmap(bitmap);
    }

    addProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            insert();
        }
    });

    addImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                File f = createImageFile();

                mUri = FileProvider.getUriForFile(
                        AddProductActivity.this, ProductContract.CONTENT_AUTHORITY, f);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);

                // Solution taken from http://stackoverflow.com/a/18332000/3346625
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }

                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    addGalleryImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            } else {
                intent = new Intent(Intent.ACTION_GET_CONTENT);
            }
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "Select image"), REQUEST_SELECT_IMAGE);
        }
    });

}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG" + timeStamp + "_";
    File albumF = getAlbumDir();
    File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
    return imageF;
}

private File getAlbumDir() {
    File storageDir = null;

    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

        storageDir = new File(Environment.getExternalStorageDirectory()
                + CAMERA_DIR
                + getString(R.string.app_name));

        if (storageDir != null) {
            if (!storageDir.mkdirs()) {
                if (!storageDir.exists()) {
                    return null;
                }
            }
        }
    } else {
        Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
    }

    return storageDir;
}

public void insert() {
    EditText editProductName = (EditText) findViewById(R.id.id_edit_product_name);
    EditText editProductPrice = (EditText) findViewById(R.id.id_edit_product_price);
    EditText editProductQuantity = (EditText) findViewById(R.id.id_edit_product_quantity);


    String name = editProductName.getText().toString();
    String quantity = editProductQuantity.getText().toString();
    String price = editProductPrice.getText().toString();

    ContentValues values = new ContentValues();

    values.put(ProductContract.ProductColumns.PRODUCT_NAME, name);
    values.put(ProductContract.ProductColumns.PRODUCT_QUANTITY, quantity);
    values.put(ProductContract.ProductColumns.PRODUCT_PRICE, price);
    values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_PATH, imagePath);
    values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_URI, imagePath);

    Uri uri = getContentResolver().insert(ProductContract.ProductColumns.CONTENT_URI, values);
    if (uri != null) {
        finish();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        imageUri = mUri.getPath();
        bitmap = getBitmap(mUri);
        imageView.setImageBitmap(bitmap);

    } else if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
        if (data != null) {
            Uri uri = data.getData();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                final int flags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
                ContentResolver contentResolver = getContentResolver();
                contentResolver.takePersistableUriPermission(uri, flags);
            }
            imageView.setImageBitmap(getBitmapFromUri(uri));
            imageUri = uri.toString();
            imagePath = uri.toString();
        }
    }

}

public Bitmap getBitmapFromUri(Uri uri) {

    if (uri == null || uri.toString().isEmpty())
        return null;

    // Get the dimensions of the View
    int targetW = imageView.getWidth();
    int targetH = imageView.getHeight();

    InputStream input = null;
    try {
        input = this.getContentResolver().openInputStream(uri);

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, bmOptions);
        input.close();

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        input = this.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
        input.close();
        return bitmap;

    } catch (FileNotFoundException fne) {
        fne.printStackTrace();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            input.close();
        } catch (IOException ioe) {

        }
    }
}

private Bitmap getBitmap(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {
        parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString(IMAGE_PATH, imagePath);
    outState.putString(IMAGE_URI, imageUri);
    outState.putParcelable(BITMAP, bitmap);
}

contentAuthority是我的包名。

com.example.fahad.inventory

这是我的路径:

<?xml version="1.0" encoding="utf-8"?>
 <paths>
<external-path name="my_images" />
 </paths>

这是我在清单中的提供者:

<provider
        android:name=".data.ProductProvider"
        android:authorities="com.example.fahad.inventory"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths" />
    </provider>

我看过一些这样的帖子,我不明白。或者它对我的问题没有帮助。

日志中的错误指向:

getContentResolver().openFileDescriptor(uri, "r");

此外,onActivityResult从相机返回的数据始终为空。

我认为问题是我必须在我的自定义OpenFile中实施contentProvider方法,但问题是我不知道该方法中要写什么。

getUriForFile返回错误uri

请帮助我,我已经在这个问题上待了两个星期了,似乎我不会去任何地方。 我是contentProvider的新手。

先谢谢你,快乐的编码!

0 个答案:

没有答案