0

I am working on an Alert Dialog in Android. The Alert Dialog shows up fine, but the Cancel-Button is not working properly: When the Cancel button is clicked, the OnClick-Method "Cancel Dialog" is not found, although it is in the Main Activity and I am passing the Dialog instances to the method. I cannot figure out, why; any help would be therefore very much appreciated.

The Logcat shows the following error:

11-01 21:10:30.111 11217-11217/de.die_web_agenten.www.batprice E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: de.die_web_agenten.www.batprice, PID: 11217
                                                                                 java.lang.IllegalStateException: Could not find method cancelDialog(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'dialog_cancel'
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                                                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                     at android.view.View.performClick(View.java:5198)
                                                                                     at android.view.View$PerformClick.run(View.java:21147)
                                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-01 21:10:34.599 11217-11217/de.die_web_agenten.www.batprice I/Process: Sending signal. PID: 11217 SIG: 9

This is the Main Activity:

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openDialog();

        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Contact us", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                Uri uri = Uri.parse("http://www.die-web-agenten.de/en/kontaktaufnahme/");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onBackPressed() {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_results) {
            // Handle the camera action
            Intent SecondListActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.SecondListActivity.class);
            MainActivity.this.startActivity(SecondListActivityIntent);

        } else if (id == R.id.nav_map) {

            // Handle the camera action

            Intent MapsActivityIntent = new Intent(MainActivity.this, MapsActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(MapsActivityIntent);

            //Intent ListActivityIntent = new Intent(MainActivity.this, ListActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            //MainActivity.this.startActivity(ListActivityIntent);

        } else if (id == R.id.nav_results) {
            // Handle the camera action
            Intent ResultsActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.ResultsActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(ResultsActivityIntent);

        } /*else if (id == R.id.nav_training) {
            // Handle the camera action
            Intent TrainingActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.TrainingActivity.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(TrainingActivityIntent);

        } */
         else if (id == R.id.nav_share) {
            // Handle the camera action
            Intent AndroidBarcodeQRExampleIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.AndroidBarcodeQrExample.class);
            //ListActivity.putExtra("key", value); //Optional parameters
            MainActivity.this.startActivity(AndroidBarcodeQRExampleIntent);

        } else if (id == R.id.nav_send) {
            // Handle the camera action

                    Uri uri = Uri.parse("http://www.die-web-agenten.de/en/kontaktaufnahme/");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void OpenListActivity() {
        Intent SecondListActivityIntent = new Intent(MainActivity.this, de.die_web_agenten.www.batprice.SecondListActivity.class);
        //ListActivity.putExtra("key", value); //Optional parameters
        MainActivity.this.startActivity(SecondListActivityIntent);

    }

    public void openDialog() {
        final Dialog dialog = new Dialog(this); // Context, this, etc.
        dialog.setContentView(R.layout.dialog_demo);
        dialog.setTitle(R.string.dialog_title);
        dialog.show();
    }

    public void cancelDialog(Dialog dialog) {
        dialog.dismiss();
    }

}

This is the corresponding dialog demo layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/dialog_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/dialog_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/dialog_info">

        <Button
            android:id="@+id/dialog_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:text="Cancel"
            android:onClick="cancelDialog"/>

        <Button
            android:id="@+id/dialog_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:text="Check voucher"/>

        <Button
            android:id="@+id/buttonAlert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Alert Box" />
    </LinearLayout>
</RelativeLayout>
Andrii Omelchenko
  • 12,030
  • 12
  • 40
  • 70
Die Webagenten
  • 438
  • 4
  • 15

8 Answers8

3

you are implementing it in wrong way. You can do this like

private Dialog dialog;

public void openDialog() {
dialog = new Dialog(this); // Context, this, etc.
dialog.setContentView(R.layout.dialog_demo);
dialog.setTitle(R.string.dialog_title);
dialog.show();

}

public void cancelDialog(View view) {
dialog.dismiss();
}

cancelDialog method requires View type of argument and you are trying to pass it as Dialog. That's why your app is crashing. Hope it will help you out.

Rahul Sharma
  • 8,050
  • 6
  • 18
  • 29
1

this may be like this

Dialog dialog;
public void openDialog() {
    dialog = new Dialog(this); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    dialog.show();
}

public void cancelDialog() {
    dialog.dismiss();
}
Ganesh Pokale
  • 1,503
  • 10
  • 23
0

Your cancelDialog method expects an argument of type Dialog and your error message tells you that a method with argument type View could not be found.

My android days have been over for a while, but i think you need to accept the View as argument (which is the view the button is part of) and close that, instead of just dismissing the dialog.

Max Uppenkamp
  • 906
  • 4
  • 16
0

That is obvious, because if you define onClick on a View on XML to run a method, the method itself will require View which is the View that you define on XML, while you passing Dialog to that method. In your case, you passing Button instead of Dialog.

Just remove

public void cancelDialog(Dialog dialog) {
    dialog.dismiss();
}

and

android:onClick="cancelDialog"

on your dialog_cancel button. Then edit openDialog method to be like this:

public void openDialog() {
    final Dialog dialog = new Dialog(this); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    View vCancel = dialog.findViewById(R.id.dialog_cancel);
    vCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}
HendraWD
  • 2,646
  • 2
  • 27
  • 45
0

Try this code

Dialog dialog;
public void openDialog() {
    dialog = new Dialog(this); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    dialog.show();
}

public void cancelDialog() { 
    dialog.dismiss();
}

You are passing Button View to cancelDialog(View) instead of cancelDialog(Dialog v)

Ganesh Pokale
  • 1,503
  • 10
  • 23
0

You should extend the dialog class and put your "onclick" methods there.

This should help you: Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs

Community
  • 1
  • 1
MiLo
  • 21
  • 2
0
This should be able to help:

  private void openDialog() {

  LayoutInflater layoutInflaterAndroid = LayoutInflater.from(BaseActivity.this);
        View view = layoutInflaterAndroid.inflate(R.layout.edit_remark_dialog, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BaseActivity.this);
        alertDialogBuilder.setView(view);
        final AlertDialog alertDialog = alertDialogBuilder.create();

        Button btnEdit = (Button) view.findViewById(R.id.btn_edit);
        Button btnDelete = (Button) view.findViewById(R.id.btn_delete);
        final EditText etRemark = (EditText) view.findViewById(R.id.et_remark);
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
        TextView tvMessage = (TextView) view.findViewById(R.id.tv_msg);


        tvTitle.setText(getResources().getString(R.string.exit_app));
        tvMessage.setText(getResources().getString(R.string.are_you_sure_want_exit));
        btnEdit.setText(getResources().getString(R.string.no));
        btnDelete.setText(getResources().getString(R.string.yes));
        btnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.dismiss();
            }
        });
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
                alertDialog.dismiss();
            }
        });

        alertDialog.show();

    }
Rohit Sharma
  • 127
  • 2
  • 13
-1

Just declare dialog in class declaration and no need to pass dialog parameter in cancleDialog method. when you show dialog just call method open dialog and when you dismiss dialog call cancleDialog method

Dialog dialog;
public void openDialog() {
        dialog = new Dialog(this); // Context, this, etc.
        dialog.setContentView(R.layout.dialog_demo);
        dialog.setTitle(R.string.dialog_title);
        dialog.show();
    }

    public void cancelDialog() {
        dialog.dismiss();
    }
Divyesh Boda
  • 266
  • 2
  • 12