Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Dialog NoSuchMethodException error when using XML onClick

I'm new to Java and Android, and I'm working on my first test app.

I've progressed with it, but I'm blocked with a Dialog.

I show the dialog from the Activity like this:

//BuyActivity.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shop);

    initialize_PR();
    display_PR();
    BuyDialog=new Dialog(this);
    BuyDialog.setContentView(R.layout.dialog_buy);

}
public void Action_ShowDialog_Buy(View view) {
    BuyDialog.show() ;
}

And the dialog is correctly shown when the button of the Activity that triggers Action_ShowDialog_Buy is clicked. But after that, the Dialog itself has a button:

<!-- dialog_buy.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<!-- Other stuff -->

<Button
    android:id="@+id/Button_Buy"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/Some_Other_Stuff"
    android:layout_centerHorizontal="true"
    android:text="@string/button_buy"
    android:onClick="Action_ShowDialog_Buy" />

</RelativeLayout>

The button method Action_ShowDialog_Buy is implemented on the Activity:

public void Action_ShowDialog_Buy(View view) {
    BuyDialog.dismiss() ;
}

but when I click on the Button in the Dialog I receive the error:

java.lang.IllegalStateException: Could not find a method BuyActivity.Action_ShowDialog_Buy(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'Button_Buy'

and below:

Caused by: java.lang.NoSuchMethodException:BuyActivity.Action_ShowDialog_Buy

but as you can see above, the method exists on the Activity.

I think I understand this is some kind of scope issue, but I do not manage to understand it. Please note that I have readed Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs but I need to understand, not just to copy code.

Many thanks

like image 841
Envite Avatar asked Jul 11 '26 18:07

Envite


1 Answers

You are trying to call the method "Action_ShowDialog_Buy", but this method doesn't exist in the Dialog object! This method should not be in the Activity, if you specify it in the xml. If you want to handle the click in the Activity, you should set the onClickListener programatically:

Button b=(Button)BuyDialog.findViewById(R.id.Button_Buy);
b.setOnClickListener(new OnClickListener(){
    @Override
    onClick(View v){
      BuyDialog.dismiss();
    }

});
like image 89
Sebastian Breit Avatar answered Jul 13 '26 08:07

Sebastian Breit