简体   繁体   中英

Issue with AlertDialog

I've just implemented an AlertDialog into a fragment within my Android app and it is causing my application to crash when it is shown.

Any ideas on why this might be?

Dialog

void addSiteOption() {

    String[] options = {"Auto", "Manual"};

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
    builder.setTitle("Add");
    builder.setMessage("Auto add - download. \n Manually add - no internet connection.");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int selectionIndex) {

            switch (selectionIndex)
            {
                case 0:
                    break;

                case 1:
                    break;
            }
        }
    });
    builder.show();
}

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x0

You are getting Application context here but you need to get the calling activity's context .So change your code

From this:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());

To this:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Context=container.getContext();

private void showAlert() {


            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("Are you sure to clear  history?");
            builder.setPositiveButton("sure", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM