Java 当我从mobile OnePlus 3 Android oreo的下载文件夹中选择file/Image/.doc时,Android应用程序崩溃

Java 当我从mobile OnePlus 3 Android oreo的下载文件夹中选择file/Image/.doc时,Android应用程序崩溃,java,android,Java,Android,我正在使用Intent为文件选择器活动编写一些代码。代码在除onepluse 3之外的所有设备中都能正常工作。我检查异常我得到了NumberFormatException异常。我试图解决这个问题,但没有得到一个适当的解决办法。请给出解决这个问题的方法 private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory

我正在使用Intent为文件选择器活动编写一些代码。代码在除onepluse 3之外的所有设备中都能正常工作。我检查异常我得到了NumberFormatException异常。我试图解决这个问题,但没有得到一个适当的解决办法。请给出解决这个问题的方法

    private void showFileChooser() {
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
       intent.addCategory(Intent.CATEGORY_OPENABLE);
       intent.setType("*/*");
       startActivityForResult(intent, PICK_FILE_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == PICK_FILE_REQUEST && resultCode == RESULT_OK) {
            if (resultCode != RESULT_CANCELED) {
                if (data == null) {
                    //no data present
                    return;
                }


                Uri selectedFileUri = data.getData();

                Log.i("suraj", " FuelExpensesActivity Selected Uri Path:" + selectedFileUri);
              String  selectedFilePath = FilePath.getPath(this, selectedFileUri);
                Log.i("suraj", "FuelExpensesActivity Selected File Path:" + selectedFilePath);

                if (selectedFilePath != null && !selectedFilePath.equals("")) {

                    TextView tvFileName = new TextView(this);
                    tvFileName.setLayoutParams(new android.view.ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                    tvFileName.setPadding(5, 5, 5, 5);
                    tvFileName.setTextColor(Color.parseColor("#FFFFFF"));
                    tvFileName.setText(getFileName(selectedFileUri));
                    parent_layout_doc.addView(tvFileName);
                    parent_layout_doc.setPadding(5, 5, 5, 5);
                    imgUrl.add(selectedFilePath);

                } else {
                    Toast.makeText(this, "file not found.....", Toast.LENGTH_SHORT).show();
                }
            }
} }

面向异常

 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=11, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg flg=0x1 }} to activity {com.riya.product.intranet/com.riya.product.allwance_criteria.FoodActivity}: java.lang.NumberFormatException: For input string: "raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg"
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4517)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4560)
    at android.app.ActivityThread.-wrap19(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6798)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.NumberFormatException: For input string: "raw:/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg"
    at java.lang.Long.parseLong(Long.java:590)
    at java.lang.Long.valueOf(Long.java:804)
    at methodclass.FilePath.getPath(FilePath.java:46)
    at com.riya.product.allwance_criteria.FoodActivity.onActivityResult(FoodActivity.java:1415)
    at android.app.Activity.dispatchActivityResult(Activity.java:7272)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4513)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4560) 
    at android.app.ActivityThread.-wrap19(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6798) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
FilePath.java

public class FilePath {

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

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

    // DocumentProvider
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        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);
            }
        }
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        // MediaStore (and general)

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

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

我也尝试下面的解决方案,但没有解决我的问题

                else if (isDownloadsDocument(uri)) {


                final String id = DocumentsContract.getDocumentId(uri);
                if (!TextUtils.isEmpty(id)) {
                    if (id.startsWith("raw:")) {
                        return id.replaceFirst("raw:", "");
                    }
                    try {
                        final Uri contentUri = ContentUris.withAppendedId(
                                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                        return getDataColumn(context, contentUri, null, null);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        Log.e("suraj", "Exception in FilePath "+ e.getMessage());
                        return null;
                    }
                }
            }

}

raw:/storage/simulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg不是一个数字。偶数/storage/emulated/0/Download/harley-davidson-vrod-tecnobike-img01~2.jpg不是一个数字,所以这是您的问题。看起来图像名没有完全取下,就像在harley-davidson-vrod-tecnobike-img01~2.jpg中一样,一些数字被转义并添加了特殊字符,请使用文件路径签入真实设备,然后进行比较,可用路径和检索路径是否相同..Markus Kauppinen我必须在哪里更改代码以及我必须在那里替换哪些代码?Pravin。。。当选择路径上方的文件时,选择FilePath=FilePath.getPaththis,选择FileUri;此行返回文件/图像的正确路径。在其他设备中,我得到了返回值,但在OnePlus 3中,它在selectedFilePath=FilePath.getPaththis,selectedFileUri中给了我异常;这一行看起来好像我们不能假设DocumentsContract.getDocumentId包含一个数字id。它返回一个字符串。它也可以是DonaldDucksCar313或任何有效字符串。所以,不要试图把它分解成一个长的。我不知道你的代码应该做什么,但是看起来你需要重新思考你的策略,以完成你想要完成的事情。