简体   繁体   中英

Not able to upload image from camera and gallery in Android 8 & 9

I have a profile picture concept in my app. User has options to upload an image from camera or gallery in the app but the problem is the image is being uploaded to some devices not all. Mainly the problem occurs with Android version 8 & 9. I tried almost everything but failed to achieve. Please help.

Code:

   dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.dialog_image_upload);
            dialog.setCanceledOnTouchOutside(false);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

            TextView txtTakePhoto = (TextView) dialog.findViewById(R.id.txtTakePhoto);
            TextView txtPictureFromGallery = (TextView) dialog.findViewById(R.id.txtPictureFromGallery);
            ImageView imgClose = (ImageView) dialog.findViewById(R.id.imgClose);

            imgClose.setOnClickListener(this);
            txtTakePhoto.setOnClickListener(this);
            txtPictureFromGallery.setOnClickListener(this)

Code for take photo from camera:

        case R.id.txtTakePhoto:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    {
                        cameraIntent();
                    }

                } else {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                        Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
                    }
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PHONE_PERMISSION_CODE);
                }
            } else {
                cameraIntent();

            }
            break;

Code for take photo from gallery:

        case R.id.txtPictureFromGallery:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    {
                        imageBrowse();

                    }

                } else {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
                    }
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PHONE_PERMISSION_CODE);
                }
            } else {

                imageBrowse();

            }
            break;

Pending code for image uploading :

        private void cameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);

}


private void imageBrowse() {

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}


//handling the image chooser activity result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_IMAGE_REQUEST) {

            onSelectFromGalleryResult(data);

        } else if (requestCode == REQUEST_CAMERA) {

            onCaptureImageResult(data);
        }
    }
     //
        if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri DbsUri = data.getData();
        fileDbs = FilePath.getPath(getActivity(), DbsUri);
        File f1 = new File(fileDbs);
        edtCertificatesValue.setText(f1.getName());

        Log.e("tag", "filedbs" + fileDbs);

    } else if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri picUri = data.getData();
        filePath = FilePath.getPath(getActivity(), picUri);
        File f2 = new File(filePath);
        edtIdentityDocumentValue.setText(f2.getName());
        Log.e("tag", "filePath" + filePath + " " + f2.getName());


    } else if (requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri picUri = data.getData();
        fileAddress = FilePath.getPath(getActivity(), picUri);
        File f3 = new File(fileAddress);
        edtProofOfAddressValue.setText(f3.getName());
        Log.e("tag", "fileAddress" + fileAddress);

    } else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri CvUri = data.getData();
        fileCvPath = FilePath.getPath(getActivity(), CvUri);
        File f4 = new File(fileCvPath);
        edtCurriculumVitaeValue.setText(f4.getName());
        Log.e("tag", "fileCvPath" + fileCvPath);
//
    }
 //
 //        } else
  }

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    bm = null;


    File imageFile = getTempFile(getActivity());
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());

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


    boolean isCamera = (data == null ||
            data.getData() == null ||
            data.getData().toString().contains(imageFile.toString()));

    if (isCamera) { /* CAMERA */
        selectedImageUri = Uri.fromFile(imageFile);
    } else { /* ALBUM */
        selectedImageUri = data.getData();
    }

    bm = getImageResized(getActivity(), selectedImageUri);
    int rotation = getRotation(getActivity(), selectedImageUri, isCamera);
    bm = rotate(bm, rotation);

    ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);

    byte[] byteImage = bytes1.toByteArray();
    encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);


    imgProfile.setImageBitmap(bm);

    Uri picUri = data.getData();

    Log.e("TAG", "onSelectFromGalleryResult: " + bm);


    fileImagePath = getPath(picUri);

    if (fileImagePath != null) {

        try {

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

    } else {

        Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
    }

    dialog.dismiss();

}

private String getPath(Uri contentUri) {
    String[] proj = {MediaStore.Images.Media.DATA};
    CursorLoader loader = new CursorLoader(getActivity(), contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

// new code

private static File getTempFile(Context context) {
    File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
    imageFile.getParentFile().mkdirs();
    return imageFile;
}



 private void onCaptureImageResult(Intent data) {

    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
    byte[] byteImage = bytes1.toByteArray();
    encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);


    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    Log.d("TAG", "onActivityResult: " + Uri.fromFile(destination));
    try {
        rotateImageIfRequired(thumbnail, getActivity(), Uri.fromFile(destination));
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d("TAG", "thumbnail: " + thumbnail);

    imgProfile.setImageBitmap(thumbnail);

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes1.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    fileImagePath = destination.toString();

    if (fileImagePath != null) {

        try {
              // execMultipartPost();
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_LONG).show();
    }

    dialog.dismiss();
}



 //This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

API hit Code:

  private void execMultipartPost() throws Exception {

    RequestBody requestBody;

    pBar.setVisibility(View.VISIBLE);


    final HashMap<String, String> loggedDetail = sessionManager.getLoggedDetail();
    HashMap<String, String> params = new HashMap<String, String>();

    String api_token = loggedDetail.get("api_token");

    if (filePath != null) {
        File file = new File(filePath);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        filename = "file_" + System.currentTimeMillis() / 1000L;

        Log.e("TAG", "filename: " + filename);

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", filename + ".jpg", fileBody)
                .addFormDataPart("name", edtName.getText().toString())
                .addFormDataPart("user_id", loggedDetail.get("id"))
                .addFormDataPart("email", edtEmailValue.getText().toString())

                .addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
                .addFormDataPart("phone", edtPhoneNumber.getText().toString())
                .addFormDataPart("type", loggedDetail.get("type"))
                .addFormDataPart("address", edtAddressValue.getText().toString())
                .addFormDataPart("gender", edtGenderValue.getText().toString())
                .addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())


                .build();

    } else {

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", "")
                .addFormDataPart("name", edtName.getText().toString())
                .addFormDataPart("user_id", loggedDetail.get("id"))
                .addFormDataPart("email", edtEmailValue.getText().toString())

                .addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
                .addFormDataPart("phone", edtPhoneNumber.getText().toString())
                .addFormDataPart("type", loggedDetail.get("type"))
                .addFormDataPart("address", edtAddressValue.getText().toString())
                .addFormDataPart("gender", edtGenderValue.getText().toString())
                .addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())

                .build();
    }


    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(Constants.EDIT_PROFILE_DATA)
            .post(requestBody)
            .addHeader("Authorization", "Bearer " + loggedDetail.get("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) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            });
        }


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

Yes, you need to configure the FileProvider. In your app's manifest, add a provider to your application:

<application>
   ...
   <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
    ...
</application>

Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

Read the android documentation https://developer.android.com/training/camera/photobasics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM