0

Hello there,

  • I have a custom android app that allows uploading of files (pdf,excel,doc,images).
  • I'm able to upload such files from any path on the device until I was using Android 10. Now my device is upgraded to android 11, and I am facing uploading issue.
  • I am able to pick file attachments from Downloads folder but not able to pick any attachments from other folders and external folders on the Andorid 11 device. I am facing this issue in my physical device as well as on Android Emulator . It will be of great help if someone helps me out on this issue.

Here is the source code of my Application for reference

MainActivity.java

public void addFiles() {
    if (AppUtils.storageInitialCheck(getActivity())) {
        AppUtils.storagePermisson(getActivity());
    } else {
        picupFile(AppUtils.intentSelect.ADD_HOME_WORK_FILE_UPLOAD);
    }
}

public void picupFile(int fileUpload) {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"), fileUpload);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        AppLog.LOGE("Exception");
    }

}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    AppLog.LOGE("onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");

    if (requestCode == AppStrings.uploadPic.PROFILE_PIC_SELECTION_RESULT) {
        if (data != null) {
            String path = data.getExtras().getString(AppStrings.uploadPic.selected_image_path);

            SelectedPicModel model = new SelectedPicModel();
            model.setImage_id("0");
            model.setImage_path(path);
            selectedPicArrayList.add(model);
            AppLog.LOGE("selected_image_path--->" + path);
            AppLog.LOGE("onActivityResult:111--> " + AppUtils.getFilesize(path));

            adapter.notifyDataSetChanged();

            updateAddpicbutton();
        }
    }
    else if (resultCode == Activity.RESULT_OK && requestCode == AppUtils.intentSelect.ADD_HOME_WORK_FILE_UPLOAD) {
        String path = "";
        try {
            Uri uri = data.getData();

            if(uri==null)
            {
                Toast.makeText(getContext(),"URI is NULL",Toast.LENGTH_LONG).show();

            }
            else {
                AppLog.LOGE("URI-------------->"+uri);
            }

            path = AppUtils.getfilePath(getContext(), uri);
            AppLog.LOGE("FILE PATH ---->"+path);

            if (path != null) {

                SelectedPicModel model = new SelectedPicModel();
                model.setImage_id("0");
                model.setImage_path(path);
                selectedPicArrayList.add(model);
                AppLog.LOGE("selected_image_path--->" + path);
                AppLog.LOGE("onActivityResult:111--> " + AppUtils.getFilesize(path));

                adapter.notifyDataSetChanged();

                updateAddpicbutton();

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

    if (requestCode == Appintegers.NotbrdStudentsActivity) {
        sendstudeintIds = "";
        if (data != null) {
            student_array = (ArrayList<StudentsModel>) data.getSerializableExtra(AppStrings.intentData.student_array);
            getSelectedIds(student_array);
            if (getSelectedNames(student_array).equals("")){
                selected_student_tv.setText(getResources().getString(R.string.select_students));
            }else {
                selected_student_tv.setText(getSelectedNames(student_array));
            }
        }
    }
}

AppUtils.java

public static String getfilePath(final Context context, final Uri uri) {

    // DocumentProvider
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProviderString[] contentUriPrefixesToTry
        else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath1(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString()+"/Download/"+fileName;
            }

            final String id = DocumentsContract.getDocumentId(uri);

            String[] contentUriPrefixesToTry = new String[]{
                    "content://downloads/public_downloads",
                    "content://downloads/my_downloads",
                    "content://downloads/all_downloads"
            };
            for (String contentUriPrefix : contentUriPrefixesToTry) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                AppLog.LOGV("contentUri---->" + contentUri);
                try {
                    String path = getDataColumn(context, contentUri, null, null);
                    AppLog.LOGV("1.contentUri path---->" + path);
                    if (path != null) {
                        AppLog.LOGV("2.contentUri matched path---->" + path);
                        return path;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;

}
  • If i try to pick file from folders apart from DOWNLOADS or from external storage the file path i am getting null (Please refer MainActivity.java code & also mentioned filepath in the AppLog).

It will be great help if someone helps me out on this issue.

  • I already told you what you dit wrong and you know already that any file can be choosed and used using ACTION_GET_CONTENT. You do as if nothing was duscussed: https://stackoverflow.com/questions/68892607/not-able-to-upload-pick-images-and-file-attachments-within-my-android-app-from – blackapps Aug 28 '21 at 07:47
  • 1
    Use the uri. Dont try to convert to a path. Throw away that getfilePath code. – blackapps Aug 28 '21 at 07:51
  • sorry, i posted a new question again, as the earlier one was closed. Sorry to disturb you again, but I being new to android development was not sure about framing the question and putting it together. Your solution helped me resolve the issue. Thanks a ton again for all your help. Will make sure to communicate better and more clearly next time onward. – Ajay Ghatge Aug 28 '21 at 09:31

0 Answers0