Search code examples
javaandroidandroid-custom-viewinflate-exception

How to solve InflateException at custom view


My question is about Android/Java.

My main.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <org.javaforum.input
        android:layout_width="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        oninvalid="this.setCustomValidity('SO - Please enter a correct E-Mail!!!')"
        android:hint="Enter your E-Mail"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>

</LinearLayout>

My input.java:

public class input extends TextView{
    public input(Context context, AttributeSet attr) {
        super(context, attr, getIdentifier(context,attr));
        if(existsoninvalid(attr)){
            //Code
        }
    }
    
    public static boolean existsoninvalid(AttributeSet attr){
        for(int f=1; f<=attr.getAttributeCount(); f++){
            if(attr.getAttributeName(f)=="oninvalid"){//Here must be the error
                //Code
            }
        }
        return false;
    }

    @Override
    public void onFinishInflate() {
        
    }
}

The app crashes with the Exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{org.javaforum/org.javaforum.MainActivity}: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class org.javaforum.input

But when I remove this:

if(attr.getAttributeName(f)=="oninvalid"){//Here must be the error
        //Code
}

The app doesn't crash and I don't get any Exceptions. I don't know why. Where is the problem? And how can I solve it?


Solution

  • The exception has a nested "caused by" exception with more details.

    Indexing is zero based. Your for loop starts at 1 and goes off by one in the other end.

    In addition, in Java use equals() and not == for string comparison. (This does not cause a crash but does not work the way you intend either.)