【问题标题】:How to add data with ContentResolver in custom folder?如何在自定义文件夹中使用 ContentResolver 添加数据?
【发布时间】:2021-10-02 22:39:44
【问题描述】:

我在 Pictures 文件夹中创建了 MyAppImages 文件夹。我想在这个文件夹中保存一张新图片。

当我通过ContentResolver插入MediaStore.Image.Media.EXTERNAL_CONTENT_URI时,我可以将图片直接保存到图片文件夹中。

当我使用 FileProvider 通过 uri 添加自己的文件夹时,我收到 java.lang.UnsupportedOperationException: No external inserts 错误。

当我用Uri.fromFile(myDirFile) 添加我自己的文件夹时,我得到了 java.lang.IllegalArgumentException: Unknown URL file:///storage/emulated/0/Android/data/com.my.app/files/Pictures/MyApp%20Image 错误。但是,当我调用myDirFile.exists() 时,它返回true。

我的代码:

private void saveByteToFile(byte[] byteArray, String contentType, long seconds){

 File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        
 //getOrCreate MyApp Images directory
 File myDirFile = new File(attachmentDir.getAbsolutePath(), "MyApp Images"); 

 //first error I mentioned
 //Uri myDirUri = FileProviderUtil.getUriFor(MyApplication.getContext(), myDirFile); 
 //second error I mentioned
 Uri myDirUri = Uri.fromFile(myDirFile);
        
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   if (!myDirFile.exists())
        Files.createDirectory(Paths.get(myDirFile.getAbsolutePath()));
 } else {
      myDirFile.mkdirs();
 }

 Logger.i(myDirFile.exists() + " myDirUri: " + myDirUri); //exists return true

 ContentValues contentValues = new ContentValues();
 contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
 contentValues.put(MediaStore.MediaColumns.MIME_TYPE, contentType);
 contentValues.put(MediaStore.MediaColumns.DATE_ADDED, seconds);
 contentValues.put(MediaStore.MediaColumns.DATE_MODIFIED, seconds);
 contentValues.put(MediaStore.Images.Media.DATA, myDirFile.getAbsolutePath());

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
 contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
 }

 ContentResolver resolver = getContext().getContentResolver();
 try {
    Uri outputUri = resolver.insert(myDirUri, contentValues); //->the errors I mentioned here are returning

    if (outputUri == null)
        throw new IOException("Failed to create new MediaStore record.");

        try (final OutputStream stream = resolver.openOutputStream(outputUri)) {
           if (stream == null)
               throw new IOException("Failed to open output stream.");

               stream.write(byteArray);

        } finally {
           if (Build.VERSION.SDK_INT > 28) {
               ContentValues updateValues = new ContentValues();
               updateValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
               resolver.update(outputUri, updateValues, null, null);
           }
        }

           return outputUri;
        } catch (IOException e) {
            Logger.exception(e);
            throw e;
        }
}

【问题讨论】:

    标签: android file fileoutputstream android-10.0 android-contentresolver


    【解决方案1】:

    看看这个可能对你有帮助..

    private fun saveImage(bmp: Bitmap) {
        var imageOutStream: OutputStream
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val values = ContentValues()
            //image name
            values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg");
            // image type
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            //storage path
            values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + "Camera");
    
            val uri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            imageOutStream = uri?.let { requireContext().getContentResolver().openOutputStream(it) }!!
        }
    
        else
        {
            //creating directory and saving
            val imagesDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
            val image = File(imagesDir, "image.jpg")
            imageOutStream =  FileOutputStream(image);
    
        }
        //compreesing the image
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
        Toast.makeText(requireContext(),"ImageSaved",Toast.LENGTH_LONG).show()
        imageOutStream.close();
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2019-06-17
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多