Android-无法从内部存储中选择文件

时间:2016-07-26 05:21:38

标签: android android-sdcard android-internal-storage

我必须从移动设备的内部存储中获取图像并上传到服务器。如果我从SD卡选择图像它工作正常,而如果我从内部存储选择图像它显示错误,我无法得到此错误。 这是logcat输出 -

  

07-26 10:32:24.868:W / System.err(24051):java.io.FileNotFoundException:/document/primary:Pictures/Screenshots/Screenshot_20160712-172722.png:open failed:ENOENT(没有这样的文件或目录)

我正在使用此代码获取图片

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                1);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

OnActivityResult代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    // 1
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            try {
                // SDK < API11
                if (Build.VERSION.SDK_INT < 11)
                    realPath_1 = RealPathUtil
                            .getRealPathFromURI_BelowAPI11(getActivity(),
                                    data.getData());

                // SDK >= 11 && SDK < 19
                else if (Build.VERSION.SDK_INT < 19)
                    realPath_1 = RealPathUtil.getRealPathFromURI_API11to18(
                            getActivity(), data.getData());

                // SDK > 19 (Android 4.4)
                else
                    realPath_1 = RealPathUtil.getRealPathFromURI_API19(
                            getActivity(), data.getData());

                Log.e("", "Build Version     : " + Build.VERSION.SDK_INT);
                Log.e("", "Get Data Get Path : " + data.getData().getPath());
                if (realPath_1.equalsIgnoreCase("")) {
                    realPath_1 = data.getData().getPath().toString();
                }
                Log.e("", "Real Path 1       : " + realPath_1);

                file_1 = realPath_1.substring(
                        realPath_1.lastIndexOf('/') + 1,
                        realPath_1.length());
                Log.i("File Name 1 ", file_1);
                txt_file_name_1.setText(file_1);

            } catch (Exception e) {
                Uri selected = data.getData();
                realPath_1 = selected.getPath();
                file_1 = realPath_1.substring(
                        realPath_1.lastIndexOf('/') + 1,
                        realPath_1.length());
                Log.i("File Name 1 ", file_1);
                txt_file_name_1.setText(file_1);
            }
        }
    }}

这里有一个名为RealPathUtil的类来获取图像的路径。 我的

  

机器人:的minSdkVersion = “14”           机器人:targetSdkVersion = “23”

并从类RealPathUtil

中调用此方法
public static String getRealPathFromURI_API19(Context context, Uri uri) {
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
            new String[] { id }, null);

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }

    cursor.close();

    return filePath;
}

请提前帮助和感谢。

4 个答案:

答案 0 :(得分:1)

  • 使用以下代码获取文件URL。

     public static String getPath(final Context context, final Uri uri) {
    
    // check here to KITKAT or new version
    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];
            }
        }
        // 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;
    }
    public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri
            .getAuthority());
    }
    public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri
            .getAuthority());
    }
    public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri
            .getAuthority());
    
    public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri
            .getAuthority());
    }
    

答案 1 :(得分:1)

试试这个:

boolean isKitKat = false;
button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showFileChooser();
        }
    });

节目文件选择器功能代码

private void showFileChooser() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        isKitKat = true;
        startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
    } else {
        isKitKat = false;
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
    }
}

OnActivity结果代码:

@TargetApi(19)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {

        if (data != null && data.getData() != null && resultCode == getActivity().RESULT_OK) {

            boolean isImageFromGoogleDrive = false;

            Uri uri = data.getData();

            if (isKitKat && DocumentsContract.isDocumentUri(getActivity(), uri)) {
                if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        realPath_1 = Environment.getExternalStorageDirectory() + "/" + split[1];
                    } else {
                        Pattern DIR_SEPORATOR = Pattern.compile("/");
                        Set<String> rv = new HashSet<>();
                        String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
                        String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
                        String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
                        if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
                            if (TextUtils.isEmpty(rawExternalStorage)) {
                                rv.add("/storage/sdcard0");
                            } else {
                                rv.add(rawExternalStorage);
                            }
                        } else {
                            String rawUserId;
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                rawUserId = "";
                            } else {
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                                String[] folders = DIR_SEPORATOR.split(path);
                                String lastFolder = folders[folders.length - 1];
                                boolean isDigit = false;
                                try {
                                    Integer.valueOf(lastFolder);
                                    isDigit = true;
                                } catch (NumberFormatException ignored) {
                                }
                                rawUserId = isDigit ? lastFolder : "";
                            }
                            if (TextUtils.isEmpty(rawUserId)) {
                                rv.add(rawEmulatedStorageTarget);
                            } else {
                                rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
                            }
                        }
                        if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                            String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                            Collections.addAll(rv, rawSecondaryStorages);
                        }
                        String[] temp = rv.toArray(new String[rv.size()]);
                        for (int i = 0; i < temp.length; i++) {
                            File tempf = new File(temp[i] + "/" + split[1]);
                            if (tempf.exists()) {
                                realPath_1 = temp[i] + "/" + split[1];
                            }
                        }
                    }
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    String id = DocumentsContract.getDocumentId(uri);
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    Cursor cursor = null;
                    String column = "_data";
                    String[] projection = {column};
                    try {
                        cursor = getActivity().getContentResolver().query(contentUri, projection, null, null,
                                null);
                        if (cursor != null && cursor.moveToFirst()) {
                            int column_index = cursor.getColumnIndexOrThrow(column);
                            realPath_1 = cursor.getString(column_index);
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();
                    }
                } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    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;
                    }

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

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

                    try {
                        cursor = getActivity().getContentResolver().query(contentUri, projection, selection, selectionArgs, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            int column_index = cursor.getColumnIndexOrThrow(column);
                            realPath_1 = cursor.getString(column_index);
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();
                    }
                } else if ("com.google.android.apps.docs.storage".equals(uri.getAuthority())) {
                    isImageFromGoogleDrive = true;
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                Cursor cursor = null;
                String column = "_data";
                String[] projection = {column};

                try {
                    cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        int column_index = cursor.getColumnIndexOrThrow(column);
                        realPath_1 = cursor.getString(column_index);
                    }
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                realPath_1 = uri.getPath();
            }

            try {
                Log.d(TAG, "Real Path 1 : " + realPath_1);
                file_1 = realPath_1.substring(realPath_1.lastIndexOf('/') + 1, realPath_1.length());
                Log.i("File Name 1 ", file_1);
              } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }}

此处file_1 =获取图像名称,而realPath_1显示来自内部或外部存储的完整图像路径。

乐意提供帮助:)

答案 2 :(得分:0)

您的代码看起来很好,您只需要获得用户的运行时权限。在Andorid 6.0或更高版本中,在运行时需要用户的权限,仅声明清单是不够的。

请参阅我之前的帖子,了解如何获取runtime permissions

<强>更新

    private void showFileChooser() {
    try {
      // Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      // startActivityForResult(i, RESULT_LOAD_IMAGE);
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("file/*");
      startActivityForResult(intent, RESULT_LOAD_IMAGE);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            //Uri selectedImage = data.getData();
            txt_file_name_1.setText(data.getData().toString());
       }
  }

答案 3 :(得分:0)

我有一个类似的代码来打开文件管理器,我试图在其中打开文件管理器来保存文件,但我在任何地方都看不到内部存储,它只在下载文件夹中打开。