我正在开发我的应用程序的一部分,它允许用户使用 Intent 选择器从相机或图库中选择图像。
它在我的 2.2.1 android 手机上运行良好,但是当我在 4.2.2 AVD 上编译它时,当我使用相机时它返回一个空指针错误,
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);
}
}
这是我得到的错误:
05-05 05:03:31.730: E/AndroidRuntime(820): Caused by: java.lang.NullPointerException
它说问题出在这一行:
InputStream stream = getContentResolver().openInputStream(data.getData());
我究竟做错了什么?
更新:
现在它正在工作,这是解决方案:
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);
}
}
谢谢你的帮助!