从库中加载图像时出现空指针异常。

时间:2012-03-05 09:55:58

标签: android

这是我从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);

2 个答案:

答案 0 :(得分:5)

而不是使用

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);

我改变了你的代码然后跑了,它对我有用!

答案 1 :(得分:0)

您的错误是照片不会以额外内容退回。它的Uri在getData()中。

请尝试使用此代码:

        switch (requestCode) {
        case 10:
            if (resultCode == Activity.RESULT_OK) {
                Uri bitmapUri = data.getData();

                try {

                    Bitmap b = Media.getBitmap(getContentResolver(), bitmapUri);
                    mImgView.setImageBitmap(b);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // ... etc ...
                break;
            }
    }

另外,我认为你在AlertDialogBu​​ilder周围做得太多了。我刚刚这样做了:

public void myClickHandler(View clickTarget) {
    Intent gallIntent = new Intent(Intent.ACTION_GET_CONTENT);
    gallIntent.setType("image/*");
    gallIntent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(gallIntent, 10);
}