这是我从画廊获取图像的代码。它给出空指针异常并崩溃。我正在测试设备本身的代码,一旦我在图库中选择了一张图片,它就会崩溃。我哪里出错了?
AlertDialog.Builder builder = new AlertDialog.Builder(CreatePod.this);
builder.setMessage("Select") .setCancelable(false).setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
startActivityForResult(gallIntent, 10);
}
})
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap b = (Bitmap) extras.get("data");
imgView.setImageBitmap(b);
String timestamp = Long.toString(System.currentTimeMillis());
MediaStore.Images.Media.insertImage(getContentResolver(), b, timestamp, timestamp);
HttpResponse httpResponse;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
int f = 0;
String ba1=Base64.encodeToString(ba, f);
最佳答案
而不是使用
Bitmap b = (Bitmap) extras.get("data");
imgView.setImageBitmap(b);
使用以下代码行:
Uri imageUri = data.getData();
Bitmap b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imgView.setImageBitmap(b);
我更改了您的代码并运行了,它对我有用!
关于android - 从图库加载图像时出现空指针异常。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9564644/