imageView.getDrawable () method throws NullPointerException

1

I wanted to get the drawable from ImageView and convert it to a bitmap. The conversion method I already have and is working fine, but when I request execution, it has the following error:

Error Displayed:

WhenItakethedirectimagefromtheDrawablefolderoftheprojectitworks,theerroronlyoccurswhenItrytogettheImageViewimage.

Activity_main:

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;
    }
}
    
asked by anonymous 03.03.2016 / 18:54

1 answer

4

Method image.getDrawable() is returning null , hence NullPointerException

You have to assign the image to ImageView using the android:src attribute and not the android:background attribute.

    
03.03.2016 / 19:31