Java – Android Dialog NoSuchMethodException error when using XML onClick

Android Dialog NoSuchMethodException error when using XML onClick… here is a solution to the problem.

Android Dialog NoSuchMethodException error when using XML onClick

I’m new to Java and Android, and I’m developing my first test app.

I’ve made progress, but I’m blocked by the dialog.

I display the dialog box in 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 when the button that triggers the Action_ShowDialog_Buy activity is clicked, the dialog box is displayed correctly. But after that, 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>

Button methods Action_ShowDialog_Buy implemented on Activity:

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

But when I hit the button in the dialog, I get 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 the following:

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

But as you can see above, the method exists on the activity.

I

think I understood that it was some kind of scope issue, but I failed to understand it. Notice that I read Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogsBut I need to understand, not just copy the code.

Thank you very much

Solution

You are trying to call the method “Action_ShowDialog_Buy”, but the method does not exist in the Dialog object! If you specify this method in XML, it should not be in an activity. If you want to handle clicks in an activity, you should programmatically set onClickListener:

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

});

Related Problems and Solutions