2014-07-17 48 views
1

我需要從圖庫中獲取圖像並將其轉換爲位圖。當我從圖庫中選擇圖像時,意圖數據在onActivityResult中爲null

這是發送意圖代碼:

Intent i = new Intent(
       Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       startActivityForResult(i, RESULT_LOAD_IMAGE); 

onActivityResult:

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == mResultLoadImage && resultCode == RESULT_OK && data != null) { 
      Uri pickedImage = data.getData(); 
      String[] filePath = { MediaStore.Images.Media.DATA }; 
      Cursor cursor = getContentResolver().query(pickedImage, filePath, 
        null, null, null); 
      cursor.moveToFirst(); 
      String imagePath = cursor.getString(cursor 
        .getColumnIndex(filePath[0])); 
      bitmap = BitmapFactory.decodeFile(imagePath); 
      someFunction(bitmap); 
      cursor.close(); 
     } 
} 

我總是得到一個NullPointerException,並與debuger,我發現數據意圖爲空。 任何解決方案?

+0

是否圖像選擇器意圖變得開放? – niculare

+0

是的,意圖選擇器打開,但是當我選擇圖像時,它給我帶來了錯誤。 – mvd3

回答

0

試試這個,它應該工作:

Intent intent = new Intent(Intent.ACTION_PICK); 
startActivityForResult(intent, RESULT_LOAD_IMAGE); 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == RESULT_LOAD_IMAGE) { 
     Uri imageUri = data.getData(); 
     Bitmap imgBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, null); 
     // then do whatever you want with the bitmap 
    } 

} 
+0

同樣的錯誤。 – mvd3

相關問題