我用下面的代碼從 Gallery中獲取圖片。給出一個空指針異常並且系統崩潰。我在設備上測試了代碼,只要我在gallery中選擇一個圖像時,系統就崩潰了。哪些地方出錯了呢?
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);
我運行過這段代碼,是好用的。