Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Weather App (2015) Concurrency and Error Handling Configuring the Alert Dialog

Matthew Francis
Matthew Francis
6,967 Points

Why do we need an activity lifecycle for Dialogs?

Creating a dialog:

       public class AlertDialogFragment extends DialogFragment {
        public Dialog onCreateDialog(Bundle savedInstanceState) { 

            Context context = getActivity(); //get whatever activity class the dialog is created in
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(context.getResources().getString(R.string.error_title)) //getResource() not neccecary, added just in case
                    .setPositiveButton(context.getResources().getString(R.string.error_message_ok_button), null);

            AlertDialog dialog = builder.create();
            return dialog;

Why is the onCreateDialog needed? what benefits does it yield?

Extra question:

    private void alertAboutUserError(){
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(),"error_dialog"); //confused about this code

A bit puzzeled on the second arugment, why is the string needed? I've read it's a reference for dialog? how would you use it?

1 Answer

J.D. Sandifer
J.D. Sandifer
18,813 Points

The short answer is that it's the way to create your own custom Dialog object.

To learn more about it - and any Android API question - check out the Android Developers Reference. Here's the page on this specific topic: Alert Dialog.

I just googled "Android AlertDialogFragment" and it was the first link. You can read earlier on the page to learn more about DialogFragment in general.