无法从Android中的URI获取路径

时间:2019-05-29 13:07:23

标签: android android-layout uri filenotfoundexception

我正在尝试从相机上传图像。我正在为此使用文件提供程序,但问题是,当我尝试从图像URI创建PATH时,它不起作用。我几乎尝试了所有操作,但是没有用。我无法从URI获取路径。

Manifest.xml:

var measid = dataContext.MeasResults.Select(a=>a.MeasId).DefaultIfEmpty().Max(p => p ?? 0) + 1;

file_paths.xml:

      <provider
        android:authorities="${applicationId}.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
           </provider>

图片上传代码:

    <?xml version="1.0" encoding="utf-8"?>
       <paths>
          <files-path name="image_picked" path="picked/" />
          <external-path name="*" path="."/>
       </paths>

URI的路径:

   private void openCameraIntent() {

    if (MarshMallowPermissionUtils.checkPermissionForCamera(this)) {
        Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {

            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
            pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(pictureIntent, REQUEST_IMAGE);
        }
    }
    else {
        MarshMallowPermissionUtils.requestPermissionForCamera(this);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQUEST_PERMISSION && grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Thanks for granting Permission", Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            imageView.setImageURI(Uri.parse(imageFilePath));
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "You cancelled the operation", Toast.LENGTH_SHORT).show();
        }
    }
}

private File createImageFile() throws IOException {

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "deep_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    imageFilePath = image.getAbsolutePath();

    return image;
}

  public String getRealPathFromURI(Context context, Uri contentUri) 
 {
Cursor cursor = null;
try { 
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
 } finally {
   if (cursor != null) {
  cursor.close();
  }
  }
  }

上传代码:

     private void getPathFromUri(){

    String path = getRealPathFromURI(DemoCam.this,photoUri);
    if (path != null) {
        File file = new File(path);

        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        String filename = "file_" + System.currentTimeMillis() / 1000L;
    }
    }

stacktrace

1 个答案:

答案 0 :(得分:0)

我在我的应用中遇到了类似的问题,并且我使用下面的代码来获取uri的路径

请按照以下步骤操作:

呼叫摄像头意图:

请在摄像机意图中添加此行

Uri mPhotoUri = getContentResolver()。insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                         新的ContentValues());

intent.putExtra(MediaStore.EXTRA_OUTPUT,mPhotoUri);

 /*for getting image using camera*/
    private void cameraIntent() {
      Uri  mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new ContentValues());
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
        startActivityForResult(intent, GlobalString.REQUEST_CAMERA);
    }

OnActivityResult

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("data===", "" + data);
        // creating method gallery camera and file
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GlobalString.SELECT_GALLERY) {
                onSelectFromGalleryResult(data);
            }
            else if (requestCode == GlobalString.REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }
        }
    }

/* this method use camera*/
    private void onCaptureImageResult(Intent data) {

        String path = null;
        Log.i(TAG, "check capture image uri---" + mPhotoUri);
        try {
            Log.i(TAG,"check image path:--"+getRealPathFromURI(mPhotoUri));
      path =getRealPathFromURI(mPhotoUri);
    }Catch(Exception e)
       {
        Log.e(TAG,"Exception--"+e);
        }
       }

getRealPathFromURI()

private String getRealPathFromURI(Uri contentURI) {
        String filePath;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            filePath = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            filePath = cursor.getString(idx);
            cursor.close();
        }
        return filePath;
    }

尝试使用此代码从URI获取图像路径。它对我有用