Не удалось получить путь от URI в Android - PullRequest
0 голосов
/ 29 мая 2019

Я пытаюсь загрузить изображение с камеры. Я использую провайдер файлов для этого, но дело в том, что когда я пытаюсь создать PATH из URI изображения, это не работает. Я попробовал почти все, но это не работает. Я не могу получить путь из URI.

Manifest.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>

file_paths.xml:

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

Код загрузки изображения:

   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();
  }
  }
  }

Путь из URI:

     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;
    }
    }

Код загрузки:

        private void execMultipartPost() throws Exception {

    String path = getRealPathFromURI(DemoCam.this,photoUri);

    RequestBody requestBody;

    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;


        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", filename + ".jpg", fileBody)
                .addFormDataPart("name", "eere")
                .addFormDataPart("user_id", "346")
                .addFormDataPart("email", "a@gmail.com")
                .addFormDataPart("postal_code", "121001")
                .addFormDataPart("phone", "7503366400")
                .addFormDataPart("type", "S")
                .addFormDataPart("address", "fefrfrf")
                .addFormDataPart("gender", "M")
                .addFormDataPart("skype_id", "hde.jfjf")
                .build();
   }




    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(Constants.EDIT_PROFILE_DATA)
            .post(requestBody)
            .addHeader("Authorization", "Bearer " + api_token)
            .build();


    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(150, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();


    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();
                    Log.e("TAG", "run:error " + e.toString());
                    e.printStackTrace();
                }
            });
        }


        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {

                        ResponseBody responseBody = response.body();
                        String content = responseBody.string();

                        Log.e("TAG", "advisor profile content: " + content);


                    } catch (Exception e) {

                        Toast.makeText(DemoCam.this, e.toString(), Toast.LENGTH_SHORT).show();

                        //pBar.setVisibility(View.GONE);

                        e.printStackTrace();

                    }

                }
            });
        }

    });
}

stacktrace

1 Ответ

0 голосов
/ 30 мая 2019

Я столкнулся с аналогичной проблемой в своем приложении и использовал приведенный ниже код для получения пути от 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. его работа для меня

...