Search code examples
androidcompound-drawables

Attempt to invoke virtual method 'android.graphics.Rect android.graphics.drawable.Drawable.getBounds()' on a null object reference


I have the following code:

etEmail.setOnTouchListener((view, motionEvent) -> {
    final int DRAWABLE_RIGHT = 2;
    if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
        if(motionEvent.getRawX() >= (etEmail.getRight() - etEmail.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
            Utils.getInstance().showPopup("...",MainActivity.this,null);
            return true;
        }
    }
    return false;
});

While generally it seems to work, I suddenly got a crashlytics report saying:

Attempt to invoke virtual method 'android.graphics.Rect android.graphics.drawable.Drawable.getBounds()' on a null object reference

for Brand: Xiaomi, Model: Redmi Note 6 Pro, Android: 9.

Has anyone here have an idea what can cause the drawable to "disappear" or be considered as null?

XML layout:

    <EditText
        android:id="@+id/etEmail"
        tools:ignore="Autofill"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableEnd="@drawable/ic_info"
        android:paddingEnd="12dp"
        android:paddingStart="10dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

Solution

  • In your xml it says drawableEnd while in your code your'e assuming it's the drawable on the right. I have a feeling the crash happened on a device with a RTL language (meaning, the drawable will be on the left).