选择文件来自文件管理器时,传递结果ResultInfo失败

时间:2017-03-05 17:40:50

标签: java android android-intent android-cursor mediastore

有意图音频文件选择器它工作正常和正确,但当我从文件管理器应用程序崩溃选择MP3文件并给我下面的日志:

E/AndroidRuntime: FATAL EXCEPTION: main
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=file:///mnt/sdcard/Download/g.p.mp3 }} to activity {com.example.er.part2/com.example.er.part2.Main2Activity}: java.lang.NullPointerException
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
                      at android.app.ActivityThread.access$1100(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at com.example.er.part2.Main2Activity.getRealPathFromURI(Main2Activity.java:128)
                      at com.example.er.part2.Main2Activity.onActivityResult(Main2Activity.java:98)
                      at android.app.Activity.dispatchActivityResult(Activity.java:5192)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184) 
                      at android.app.ActivityThread.access$1100(ActivityThread.java:130) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243) 
                      at android.os.Handler.dispatchMessage(Handler.java:99) 
                      at android.os.Looper.loop(Looper.java:137) 
                      at android.app.ActivityThread.main(ActivityThread.java:4745) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:511) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
                      at dalvik.system.NativeStart.main(Native Method)  

这是我的代码:

 Button button=(Button)findViewById(R.id.select);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent_upload = new Intent();
            intent_upload.setType("audio/*");
            intent_upload.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent_upload,1);

        }
    });
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 1 && resultCode == Activity.RESULT_OK){
            if ((data != null) && (data.getData() != null)){
                audioFileUri = data.getData();
                // Now you can use that Uri to get the file path, or upload it, ...
               filePath = getRealPathFromURI(getApplicationContext(),audioFileUri);
    }
}
  public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Audio.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

因为我告诉它在从媒体播放器中选择时工作正常但是当从文件管理器中选择时它发生了!以及日志下面的部分

Caused by: java.lang.NullPointerException at com.example.er.part2.Main2Activity.getRealPathFromURI(Main2Activity.java:128)

指向这一行:

int column_index = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);

2 个答案:

答案 0 :(得分:0)

  

从媒体播放器中选择时它可以正常工作

它只适用于某些设备和某些情况。

摆脱getRealPathFromURI()。使用ContentResolveropenInputStream()来访问Uri标识的内容。

答案 1 :(得分:0)

经过一些研究,我发现这种方法和问题解决了

@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
           if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{
                    split[1]
            };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = {
                MediaStore.Audio.Media.DATA
        };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    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());
}