Method imageView.getDrawable() launches Nullpointerexception

Asked

Viewed 213 times

1

I wanted to take Imageview’s drawable and convert it to a bitmap. The conversion method I already have and is working well however, when I request the execution, it presents the following error:

Error Presented:

inserir a descrição da imagem aqui

When I get the image straight from the project’s Drawable folder it works, the error only occurs when I try to get the image from Imageview.

Activity_main:

inserir a descrição da imagem aqui

Mainactivity:

public class MainActivity extends AppCompatActivity {
    private Bitmap bitmap; //vai guardar a imagem da ImageView
    private ImageView image; //Possui a Imagem que quero converter

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.img);
    }

    public void converte(View v){
        bitmap = drawableToBitmap(image.getDrawable());
    }

    public static Bitmap drawableToBitmap (Drawable drawable) {
        Bitmap bitmap = null;

        if (drawable instanceof BitmapDrawable) {
           BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable.getBitmap();
            }
        }
        if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {//O ERRO OCORRE AQUI. . .
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
  • What is Mainactivity line 83?

  • It is the second if of the drawableToBitmap (Drawable drawable) method. It is commented there.

  • 1

    Sorry, I hadn’t seen it. At what moment you call the convert method(View v), what you are passing in this parameter?

  • I call when I click on the button shown in the layout

  • 1

    How you are assigning the image to Imageview?

  • I do this by the same layout, click on the image / background and select the desired image.

Show 1 more comment

1 answer

4


The method image.getDrawable() is returning null, hence the NullPointerException

You have to assign the image to Imageview through the attribute android:src and not the attribute android:background.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.