0
我嘗試從照片庫中選擇多個圖像並將其保存在我的sdCard上的自定義文件夾中。 我寫了一些代碼,但我有nullPintException 這是我的源使用Intents從Android上的照片庫中選擇多個圖像NullPointerException
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_FROM_GALLERY);
,這是OnActivityResultCode
if(data!=null)
{
ClipData clipData = data.getClipData();
for (int i = 0; i < clipData.getItemCount(); i++)
{
Uri selectedImage = clipData.getItemAt(i).getUri();
if (selectedImage != null) {
mCurrentPhotoPath = getRealPathFromURI(selectedImage);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
// bitmap=getResizedBitmap(bitmap,1280,720);
String partFilename = currentDateFormat();
if (bitmap != null) {
SaveImage(bitmap, partFilename);
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = CarRecieveActivity.this.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private void SaveImage(Bitmap finalBitmap,String fileName) {
File myDir = new File(rootDirectory + "/"+vinNumber.getText().toString());
myDir.mkdirs();
String fname = fileName+".jpg";
File file = new File (myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
這是我的源。我有兩個錯誤。 第一當我點擊只有一個圖像在我的畫廊clipData爲空;第二,當我從圖庫中選擇多張圖像,然後點擊確定按鈕,我有這個錯誤
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it
錯誤是在這個函數getRealPathFromURI() 我怎麼能解決這兩個問題嗎? 感謝
從設備
請參考此答案http://stackoverflow.com/a/27115327/7045114 –
如果您只選擇一個圖像,則data.getData()是uri。 – greenapps
不要使用像'getRealPathFromURI()'這樣的函數。你不需要一個真正的路徑。使用getContentResolver()。openInputStream(uri)打開輸入流並將該流用於BitmapFactory。 – greenapps