1

I am trying to open files by using Intent.ACTION_GET_CONTENT like in this post:

Android opening a file with ACTION_GET_CONTENT results into different Uri's

But here is just a solution how to get the filename with different SDKs/Folders and not for different devices. Also the Intent to get the Uri stays the same.

I want to open .png files.

Uri.getPath() for the both devices are (both .png files stored in the download folder):

   Samsung S3 Tablet (Android 8.0): /document/559

   Samsung Galaxy S7 (Android 8.0): /document/raw:/storage/0/emulated/Download/Karte1.png

Therefore the problem is, if i initialise an InputStream with

   getActivity().getContentResolver().openInputStream(uri)

its not working for the Tablet.

Here is the Intent code snippet:

    public void browseClick() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/png");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, 
            getString(R.string.choose_floorPlan)),REQUEST_CODE_OPEN_FILE);
        } catch (Exception ex) {
            System.out.println("browseClick :"+ex);
        }
    }

OnActivityResult:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_CODE_OPEN_FILE) {
            return;
        }
        if ((resultCode == RESULT_OK) && (data != null)) {

            try {
                selectedMap = data.getData();
                String filename = FileHelper.getUriName(selectedMap, 
                getActivity());              

                textMapDir.setText(getString(R.string.placeholder_
                folder_begin, filename));
                textMapDir.setText(selectedMap.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

In this method im using the uri and openInputStream(uri)

    private boolean createFiles(String pathProjectDir, Uri selectedMap) {
    if (!ExistsDir(pathProjectDir)) { //it should be possible to add more floors/buildings to an existing project
        if (getAndCreateDir(pathProjectDir).exists()) {
            InputStream excelFile;
            InputStream mapFile;
            try {
                excelFile = Objects.requireNonNull(getActivity()).getAssets().open(EXCEL_FILE_NAME);
                mapFile = getActivity().getContentResolver().openInputStream(selectedMap);

                if (FileHelper.getMimeType(selectedMap.getPath()).equals("application/pdf")) {

                    // some code

                } else if (FileHelper.getMimeType(selectedMap.getPath()).equals("image/png")) {
                    if ((copyFile(excelFile, getExcelPath(pathProjectDir)))
                            && (copyFile(mapFile, getMapPathPNG(pathProjectDir)))) {
                        return true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), getString(R.string.excel_file_unable_to_create), Toast.LENGTH_LONG).show();
                return false;
            }
        }
        Toast.makeText(getActivity(), getString(R.string.project_dir_was_not_created), Toast.LENGTH_LONG).show();
        return false;
    }
    Toast.makeText(getActivity(), getString(R.string.project_dir_exisitng), Toast.LENGTH_LONG).show();
    return false;
    }

Thats the getMimeType() method, where i check the MIME from the uri, that could be the problem:

    public static String getMimeType(String path) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(path);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

This is the copyFile() method where I copy the InputStream:

    public static Boolean copyFile(InputStream isFile, String pathOutput) {
    try {
        FileOutputStream fos = new FileOutputStream(new File(pathOutput));
        copyFileBuffer(isFile, fos);
        isFile.close();
        fos.flush();
        fos.close();
        return true;
    } catch (IOException io) {
        io.printStackTrace();
    }
    return false;
}

To complete the code here is the copyFileBuffer() method, but this should be fine:

    public static Boolean copyFile(InputStream isFile, String pathOutput) {
    try {
        FileOutputStream fos = new FileOutputStream(new File(pathOutput));
        copyFileBuffer(isFile, fos);
        isFile.close();
        fos.flush();
        fos.close();
        return true;
    } catch (IOException io) {
        io.printStackTrace();
    }
    return false;
}
Ema
  • 31
  • 3
  • You need to get real path from it – Piyush Aug 07 '19 at 13:24
  • @Piyush: There is no "real path" – CommonsWare Aug 07 '19 at 13:47
  • "if i initialise an InputStream... its not working for the Tablet" -- your `onActivityResult()` code does not show using `openInputStream()`. Please provide a [mcve]. This would include the code that is using `openInputStream()` and the specific details about "its not working". For example, if you are crashing, provide the full stack trace. Note that `getPath()` on its own only has value if the scheme of the `Uri` is `file`. – CommonsWare Aug 07 '19 at 13:49
  • thanks for the answer. I would provide the exact error from the tablet, but right know i dont have it, my company was asking for help. I was hoping its more simple or anybody faced the same problem and has a solution. But i will get the tablet soon and can debug the code. I will add more details than! – Ema Aug 07 '19 at 14:20
  • i added some code: Maybe `selectedMap.getPath()).equals("image/png")` in the createFiles() method is not working proper with the uri – Ema Aug 07 '19 at 14:44

1 Answers1

1

You have to get the real path from the uri . Below is the code for it . I had found it from an post on stack overflow but i don't have a link to it . So credit goes to whoever posted it. Pass the context and uri and get the real path

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getPathFromUri(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && 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
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // 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 the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        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 index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Aashit Shah
  • 578
  • 3
  • 9