当我从光标得到一个位置时,我得到一个空指针异常

时间:2014-04-08 05:15:59

标签: android sqlite cursor

首先,我使用的是managedquery。它运行正常,但应用程序在nexus和moto-G.中崩溃了。为什么,我重新使用了getcontent resolver而不是托管查询。现在,我得到了一个空指针exception.Please帮我解决这个问题

     public String getRealPathFromURI(Uri contentUri) {
                String videoPath=null;
                String[] proj = { MediaStore.Video.Media.DATA };

                Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
                Log.i("cursor","upload-->" +cursor);
                Log.i("contentUri","upload-->"  +contentUri);
                Log.i("proj","upload-->"  +proj);

                 if(cursor.moveToFirst()){

            //I got a null pointer exception here
                   int column_index = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                    Log.i("column_index","Upload-->" +column_index);
                    videoPath = cursor.getString(column_index);
                    Log.i("videoPath","Upload-->" +videoPath );

                }
                 cursor.close();
                return videoPath;


        }

1 个答案:

答案 0 :(得分:0)

试试这段代码它为我工作

onCreate()中的

添加以下内容

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = (YourActivity) 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 = getAbsoluteImagePath(selectedImage);
           Log.d("TAG","Image path = "+path);

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

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