Skip to content Skip to sidebar Skip to footer

Illegalstateexception: Could Not Execute Method For Android:onclick When Trying To Migrate To Another Page?

I've been working on an app (which i took over from another student's final year project on my lecturer's recommendation) due to university internship requirements and am having is

Solution 1:

I suspect the problem is related with the clash of android:onClick="loginButtonClick" in main menu xml and login xml.

You should not depend on android:onClick attribute for handling View click. It is because when using android:onClick you can't be sure that your method handling the onClick will work. There is no exact mechanism to ensure your code is connected to the View. Another problem is, android:onClickwon't work for Fragment. So, I consider using android:onClick as bad practice.

To solve the problem, use setOnClickListener on your View. Coupled with findViewById, your code will more robust because you will always see an error if you are giving an incorrect id for findViewById. To make your code more robust and avoid clashing the id, you need to use a decscriptive name id for the view. Use naming convention like this:

layout name + _ + What the view for + _ + type of view

For example, for your login xml you can use something like this:

....

<Button
    android:id="@+id/login_cloudpark_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:background="#0026FF"
    android:text="Login to CloudPark"
    android:textColor="#FFFF"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.687" />

<android.support.constraint.Guideline
    android:id="@+id/login_begin_gdl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_begin="20dp" />

...

then use it with findViewById:

publicclassLoginActivityextendsAppCompatActivity {

  ...

  private Button mBtnLogin;

  @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ...

    mBtnLogin = findViewById(R.id.login_cloudpark_btn);
  }
}

after that, add clickListener to mBtnLogin:

mbtnLogin.setOnClickListener(newView.OnClickListener() {
      @OverridepublicvoidonClick(View v) {
         // place your clicking handle code here.
      }
    });

By doing the above, you will separate the View in xml and your logic cleanly.

Post a Comment for "Illegalstateexception: Could Not Execute Method For Android:onclick When Trying To Migrate To Another Page?"