I am working on a part of my application that allows the user to select an image either from the camera or from the gallery using the choice of intent.
It works fine on my 2.2.1 android phone, but when I compile it on 4.2.2 AVD, it returns a null pointer error when I use the camera,
public void onClick(View View) { Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null); galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); galleryIntent.addCategory(Intent.CATEGORY_OPENABLE); Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Intent chooser = new Intent(Intent.ACTION_CHOOSER); chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent); chooser.putExtra(Intent.EXTRA_TITLE, "Chooser"); Intent[] intentArray = {cameraIntent}; chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooser,REQUEST_CODE); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { try { if (bitmap != null) { bitmap.recycle(); } InputStream stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); stream.close(); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.onActivityResult(requestCode, resultCode, data); } }
this is the error i get:
05-05 05: 03: 31.730: E / AndroidRuntime (820): caused by: java.lang.NullPointerException
And he said that the problem is in this line:
InputStream stream = getContentResolver().openInputStream(data.getData());
What am I doing wrong?
Updated:
Now it works and here is the solution:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { if(data.getData()!=null) { try { if (bitmap != null) { bitmap.recycle(); } InputStream stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); stream.close(); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { bitmap=(Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(bitmap); } super.onActivityResult(requestCode, resultCode, data); } }
Thank you for your help!
source share