【问题标题】:Android - Convert file path to uri (not working)Android - 将文件路径转换为uri(不起作用)
【发布时间】:2017-07-10 14:06:47
【问题描述】:

我想将文件路径转换为 ​​uri。但我收到错误说它无法解析 uri。图像来自从相机意图保存图像。图像保存到这个目录:getFilesDir();在应用程序中。

在我的光标适配器中:

String imgPath = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_IMG_PATH ));
        String productName = cursor.getString(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_NAME ));
        int productStock = cursor.getInt(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_STOCK ));
        Uri uri = ContentUris.withAppendedId(InventoryContract.InventoryEntry.CONTENT_URI,
                cursor.getLong(cursor.getColumnIndexOrThrow( InventoryContract.InventoryEntry.COLUMN_PRODUCT_ID )));
        File imgFile = new File(imgPath);
        Uri imgURI = Uri.fromFile(imgFile);

        if(imgFile.exists()) {
            Log.v("image file" , String.valueOf(imgFile));
            //Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            productImage.setImageURI(imgURI);
            Log.v("Image does exist", "file | " + String.valueOf(imgURI));
        }
        else {
            Log.v("bitmap --- ", "Could not find file | " + imgPath);
        }

错误行之一:

W/ImageView: resolveUri failed on bad bitmap uri: file:///data/user/0/com.example.android.inventoryapp/files/JPEG_20170710_094130_1552703275.jpg

【问题讨论】:

  • 不要使用setImageURI()。这将在主应用程序线程上加载图像,这将冻结您的 UI 一段时间。使用图像加载库(例如 Glide、Picasso),为库提供您的 File 对象。
  • 我找到了解决办法,谢谢!
  • 这是一个来自 Udacity.com 的项目,标准禁止外部库/框架。
  • 那么,我不能推荐 Udacity 课程。这是在面试、代码审查等中会困扰你的事情。
  • 我同意该标准存在缺点。他们说目的是熟悉原始 Java,但为什么要重新发明轮子。尽管我仍然认为整个课程都很好。它被称为:谷歌纳米学位的Android基础

标签: java android file


【解决方案1】:

尝试使用下面的代码

 Uri uri =   Uri.fromFile(new File(filepath));

【讨论】:

    【解决方案2】:

    感谢大家的帮助。我找到了解决方案。文件路径很好,但我认为它是一个空文件。我不得不这样写:

    private File createImageFile(Bitmap image) throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File directory = this.getFilesDir();
    
            // Save Bitmap
            this.photo = new File(directory, imageFileName + ".jpg");
            this.photo.createNewFile();
            // Write to/Compress the Bitmap from the camera intent to the file
            FileOutputStream fos = new FileOutputStream(this.photo);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
    
            // path to file
            this.imgPath = this.photo.getAbsolutePath();
            return this.photo;
        }
    

    【讨论】:

      猜你喜欢
      • 2015-02-20
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多