I'm working on a part of my application that allows a user to select an image either from camera or from gallery, using an Intent chooser.
It's working fine on my 2.2.1 android phone, but when i compile it on a 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 it said that the problem is in this line :
InputStream stream = getContentResolver().openInputStream(data.getData());
What am i doing wrong?
Updated:
Now it's working 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 you help!