Android:通过意图调用图库并选择图像

时间:2011-08-09 09:55:38

标签: android android-sdcard android-gallery

使用整个网站提供的几个代码,我构建了一个小应用程序,可以调用Gallery意图,当选择图像时,路径会被撤消。

public class SDCardImagesActivity extends Activity {
    final int REQ_CODE_PICK_IMAGE= 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.header);
        Intent i = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, REQ_CODE_PICK_IMAGE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) { 
        case REQ_CODE_PICK_IMAGE:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

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

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();


                Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);

                Toast.makeText(SDCardImagesActivity.this, "selected", 2000).show();
            }
        }

    }
}

但是当我运行这个程序时,我得到了以下异常

08-09 15:12:53.191: ERROR/AndroidRuntime(26694): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

有人能帮助我吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的查询返回0行,这就是您收到错误的原因CursorIndexOutOfBoundsException =尝试访问0行的游标的第一行。

你确定他们在所述媒体(SD卡)上的照片吗?