android-get nullpointerexception 尝试访问外部存储(sdcard)上的视频

Posted

技术标签:

【中文标题】android-get nullpointerexception 尝试访问外部存储(sdcard)上的视频【英文标题】:android-get nullpointerexception when try to access video on external storage(sdcard) 【发布时间】:2013-07-10 09:09:54 【问题描述】:

在我的应用中,我有一个视频上传选项,允许用户上传视频。一切正常,除非用户尝试从外部存储中选择视频。该应用程序将崩溃并提供NullPointerException。有人可以解释为什么吗?当用户从图库或手机存储中选择视频而不是外部存储时,该功能如何正常工作?这是我收到的错误消息

java.lang.RuntimeException: Failure delivering result ResultInfowho=null, request=2, result=-1, data=Intent  act=file:///mnt/sdcard/android/data/com.dropbox.android/files/scratch/VIDEO0010.mp4 dat=file:///mnt/sdcard/Android/data/com.dropbox.android/files/scratch/VIDEO0010.mp4  to activity com.myactivity.android/com.myactivity.android.Webviewer: java.lang.NullPointerException

下面是我的代码

private VideoFileInfo getVideoInfo(Uri uri) 


        String[] projection =  MediaStore.Images.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.TITLE ;
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        cursor.moveToFirst(); //this is where the app crashed

        String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
        String fileName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
        int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
        long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));

        System.out.println("path: " + filePath);
        System.out.println("name: " + fileName);
        System.out.println("size: " + fileSize);
        System.out.println("duration: " + duration);
        vfi.setPathNameSizeDuration(filePath, fileName, fileSize, duration);



    return vfi;

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent intent) 

    switch (requestCode) 

    case FILECHOOSER_REQUESTCODE_VIDEO:     
        if (resultCode == Activity.RESULT_OK) 
            System.out.println("SELECT_AUDIO");
            Uri selectedVideoUri = intent.getData();
            selectedPath = getVideoInfo(selectedVideoUri).getPath();
            System.out.println("SELECT_AUDIO Path : " + selectedPath);
            //bm = BitmapFactory.decodeFile(selectedPath);
            blVideoDail = true;
        
        break;
    

private void createVideoIntent()
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("video/*");

    Intent chooser = createVideoChooserIntent(createVideoFromCameraIntent());
    chooser.putExtra(Intent.EXTRA_INTENT, intent);
    startActivityForResult(chooser, FILECHOOSER_REQUESTCODE_VIDEO); 

private Intent createVideoChooserIntent(Intent... intents) 
    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
    chooser.putExtra(Intent.EXTRA_TITLE, "Please Choose Your Video");
    return chooser;

private Intent createVideoFromCameraIntent()   
    return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

有人可以帮忙吗?谢谢

点击cursor.moveToFirst(); 时应用程序崩溃。

FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfowho=null, request=2, result=-1, data=Intent  act=file:///mnt/sdcard/Android/data/com.dropbox.android/files/scratch/VIDEO0010.mp4 dat=file:///mnt/sdcard/Android/data/com.dropbox.android/files/scratch/VIDEO0010.mp4  to activity com. myactivity .android/com.myactivity.android.Webviewer: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3437)
at android.app.ActivityThread.access$1100(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1291)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.myactivity.android.Webviewer.getVideoInfo(Webviewer.java:455)
at com.myactivity.android.Webviewer.onActivityResult(Webviewer.java:500)
at android.app.Activity.dispatchActivityResult(Activity.java:4740)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3383)
... 11 more

【问题讨论】:

请张贴logcat。告诉我们发生空指针异常的行。更好的是,自己看看那条线 - 通常很容易弄清楚...... 你是在真机上测试这段代码吗? 我发现从外部存储中选择视频时,即使是 youtube 也无法正常工作。这是一个无法修复的已知问题吗? 如果是,请确保在运行此代码之前拔下设备。因为您的外部存储器将被挂载,因此您的代码/应用程序将无法找到该视频... 我只是尝试拔下设备并运行应用程序。仍然没有工作:( 【参考方案1】:

public void selectFile() Intent intent = new Intent(); intent.setType("video/*"); 意图.setAction(意图.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "选择一个视频 "), SELECT_VIDEO);

使用以下代码从手机/卡中选择视频

@覆盖 public void onActivityResult(int requestCode, int resultCode, Intent data)

    if (resultCode == RESULT_OK) 
        if (resultCode == Activity.RESULT_OK) 
            if (requestCode == SELECT_VIDEO)
                onSelectFromGalleryResult(data);
            /*
             * else if (requestCode == REQUEST_CAMERA)
             * onCaptureImageResult(data);
             */
    


@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) 
    Uri selectedImageUri = data.getData();
    String[] projection =  MediaColumns.DATA ;
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    File fileUpload = new File(selectedImagePath);
    // selected_image_file.add(fileUpload);
    // new UploadAdvertisement().execute();

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);
    ImageView image = new ImageView(getApplicationContext());
    // image.setId(adverticse_image_start_id);
    int width = (int) (getResources().getDimension(R.dimen.dim_100) / getResources()
            .getDisplayMetrics().density);
    int left_margin = (int) (getResources().getDimension(R.dimen.dim_15) / getResources()
            .getDisplayMetrics().density);
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(width,
            LayoutParams.MATCH_PARENT);
    param.setMargins(left_margin, 0, 0, 0);

    image.setLayoutParams(param);
    image.setImageBitmap(bm);
    System.out.println("selected video path >>>>" + selectedImagePath);
    if (selectedImagePath != null) 
        new UploadFileToserver().execute();
    

以上代码将为您提供所选项目的文件名

【讨论】:

私有静态最终 int SELECT_VIDEO = 3;将其用作全局变量

以上是关于android-get nullpointerexception 尝试访问外部存储(sdcard)上的视频的主要内容,如果未能解决你的问题,请参考以下文章

Failed to start bean ‘documentationPluginsBootstrapper‘; nested exception is java.lang.NullPointerEx

Failed to start bean ‘documentationPluginsBootstrapper‘; nested exception is java.lang.NullPointerEx

Maven + Spring + Hibernate:hibernate3-maven-plugin hbm2ddl 失败,原因是“Caused by: java.lang.NullPointerEx

Java中遍历Map的常用方法

Android - 在动态注册的广播接收器上出现“无法传递广播”错误

无法在 null 对象上调用方法 replace(),但存在字符串