Nullpointerexcepiton在光标上从对话框片段的画廊选择照片

时间:2014-03-24 10:41:01

标签: android nullpointerexception cursor android-dialogfragment

我正试图通过DialogFragment从图库中选择照片。但我在初始化nullpointerexception时收到cursor。有什么想法可以解决这个错误吗?

以下是我的代码:

    if (resultCode == Activity.RESULT_OK) {
        Uri selectedImage = imageReturnedIntent.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        // Nullpointerexcepiton on this line
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

        cursor.close();

    }

这是我的logcat错误:

    03-24 12:34:37.645: E/AndroidRuntime(21479): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65538, result=-1, data=Intent { dat=content://media/external/images/media/3890 flg=0x1 }} to activity {com.example/com.example.MainActivity}: java.lang.NullPointerException

    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread.access$1100(ActivityThread.java:150)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.os.Handler.dispatchMessage(Handler.java:99)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.os.Looper.loop(Looper.java:213)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread.main(ActivityThread.java:5225)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at java.lang.reflect.Method.invoke(Method.java:525)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at dalvik.system.NativeStart.main(Native Method)

    03-24 12:34:37.645: E/AndroidRuntime(21479): Caused by: java.lang.NullPointerException
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at com.example.MainDialogFragment.onActivityResult(MainDialogFragment.java:226)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at com.example.MainActivity.onActivityResult(DelictActivity.java:85)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.Activity.dispatchActivityResult(Activity.java:5322)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
    03-24 12:34:37.645: E/AndroidRuntime(21479):    ... 11 more

5 个答案:

答案 0 :(得分:5)

你如何开始你的活动,从哪里开始? 如果您通过MainActivity传递结果,可以尝试在DialogFragment中创建一个新函数,如下所示:

public void onMyActivityResult(Context main, int resultCode... an so on){

     main.getContentResolver.......

}

编辑: 我这样做了:

获取onCreate中的活动:

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = (MainActivity) this.getActivity();
    }

然后:

     @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == REQUEST_GALLERY && resultCode == Activity.RESULT_OK) {
           ...

            Uri selectedImage = data.getData();
            String path = getRealPathFromURI(selectedImage);
           ...
            reloadImages();

        }
        super.onActivityResult(requestCode, resultCode, data);
        }

 private String getRealPathFromURI(Uri contentURI) {
    Cursor cursor = mActivity.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file
                  // path
        return contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        String path = cursor.getString(idx);
        cursor.close();
        return path;
    }
    }

答案 1 :(得分:2)

问题可能是因为getActivity()在此行中返回null

Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);

当您的片段未附加到活动时,会发生这种情况。我看到了两个可能的原因:

  • 您在片段生命周期中过早地调用getActivity()。在使用onAttach(Activity)
  • 之前,您需要等待getActivity()的调用
  • 您的片段已与活动分离,请检查Fragment.isAdded()的返回,以确保您的片段仍然已附加。

答案 2 :(得分:0)

从图库中选择图像 int PICK_IMAGE = 1;

public void getGalleryImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        activity.startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE);
        }

关于活动结果

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == PICK_IMAGE) {
                String selectedImagePath = getAbsolutePath(data.getData());
                Log.d("GetImage","Selected Image Path "+selectedImagePath )
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
}

//获取图片路径

public String getAbsoluteImagePath(Uri uri) {
        String[] projection = { MediaColumns.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

答案 3 :(得分:0)

我已经完成了这个......而且效果很好

 protected void onActivityResult(int requestCode, int resultCode, Intent 
 data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {

        Uri selectedImage = data.getData();
        URI = Uri.parse("file://" + selectedImage);
    }
}

答案 4 :(得分:0)

 private String getRealPathFromURI(Uri selectImagePath) {
    Cursor cursor = mActivity.getContentResolver().query(selectImagePath, null, null, null, null);
    if (cursor == null) { //this return actual path from storage
                
        return contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        String path = cursor.getString(idx);
        cursor.close();
        return path;
    }
    }