1

I am creating a registration layout. Because there is too much information to put into one layout, I need to use two

When the user selects the REGISTER button, I want to display layout 1, save data to firebase and then when they select the positive button, it closes layout 1 and displays layout 2.

How can I do this?

I have two dialogs:

showVehicleDetails

AlertDialog.Builder alert_dialog = new AlertDialog.Builder(this);
    alert_dialog.setTitle("VEHICLE DETAILS");
    alert_dialog.setMessage("Please, fill in the following:");
    LayoutInflater inflate = LayoutInflater.from(this);
    View vehicle_details = inflate.inflate(R.layout.layout_vehicle_details, null);

    final MaterialEditText edtYear = vehicle_details.findViewById(R.id.year);
    final MaterialEditText edtCMNM = vehicle_details.findViewById(R.id.cmnm);
    final MaterialEditText edtPlate = vehicle_details.findViewById(R.id.plate);

    alert_dialog.setView(vehicle_details);

    alert_dialog.setPositiveButton("SUBMIT", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

            // check validation
            if (TextUtils.isEmpty(edtYear.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter year of your vehicle", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }

            if (TextUtils.isEmpty(edtCMNM.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter the Color, Make and Model of your vehicle",
                        Snackbar.LENGTH_SHORT).show();

                return;
            }

            if (TextUtils.isEmpty(edtPlate.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter your license plate number", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }

            // save to firebase/ Users/Drivers ...

            details = users;
            details.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    // get drivers id
                    for (DataSnapshot ss : snapshot.getChildren()) {
                        String id = ss.getKey();

                        String year = edtYear.getText().toString();
                        String cmnm = edtCMNM.getText().toString();
                        String plate = edtPlate.getText().toString();

                        Log.e(TAG, "year: " + year + ", cmnm: " + cmnm + ", plate: " + plate);

                        // data sent
                        details.child(id).child("year").setValue(year);
                        details.child(id).child("cmnm").setValue(cmnm);
                        details.child(id).child("plate").setValue(plate);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });

    AlertDialog dialog = alert_dialog.create();
    dialog.show();
}

showRegisterDialog

final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("REGISTER");
    builder.setMessage("Please use email to register");
    LayoutInflater inflater = LayoutInflater.from(this);
    View register_layout = inflater.inflate(R.layout.layout_register, null);

    final MaterialEditText edtEmail = register_layout.findViewById(R.id.email);
    final MaterialEditText edtPassword = register_layout.findViewById(R.id.password);
    final MaterialEditText edtName = register_layout.findViewById(R.id.usersname);
    final MaterialEditText edtPhone = register_layout.findViewById(R.id.cell);

    final MaterialAnimatedSwitch policies_switch = register_layout.findViewById(R.id.policies_switch);

    builder.setView(register_layout);

    builder.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, int which) {
            dialog.dismiss();

            // check validation
            if (TextUtils.isEmpty(edtEmail.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter email address", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }

            if (TextUtils.isEmpty(edtPhone.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter phone number", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }

            if (TextUtils.isEmpty(edtPassword.getText().toString())) {
                Snackbar.make(rootLayout, "Please enter password", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }

            if (edtPassword.getText().toString().length() < 6) {
                Snackbar.make(rootLayout, "Password too short !!!", Snackbar
                        .LENGTH_SHORT).show();

                return;
            }


            // Register new user
            auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),
                    edtPassword.getText().toString())
                    .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            // Save user to db
                            Driver driver = new Driver();
                            driver.setEmail(edtEmail.getText().toString());
                            driver.setUsersname(edtName.getText().toString());
                            driver.setCell(edtPhone.getText().toString());
                            driver.setPassword(edtPassword.getText().toString());
                            driver.setRates("4.5"); // TODO: Default added

                            // use uid to key
                            users.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .setValue(driver)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            Snackbar.make(rootLayout, "Registration successful !!!",
                                                    Snackbar.LENGTH_SHORT).show();
                                        }
                                    })

                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Snackbar.make(rootLayout, "Failed" + e.getMessage(),
                                                    Snackbar.LENGTH_SHORT).show();
                                        }
                                    });
                        }
                    })

                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Snackbar.make(rootLayout, "Failed" + e.getMessage(),
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
        }
    });

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

    final AlertDialog dialog = builder.create();

    /* If switch is on, enable REGISTER button */
    policies_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isChecked) {
            if (isChecked) {
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); // if checked, enable
            }
        }
    });

    dialog.show();

    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); // set disabled by default

}

As it stands right now, when I click on the Register button, it displays the 2nd layout showRegisterDialog.

I want it to display showVehicleDetails first and when I select the positive button SUBMIT it should show showRegisterDetails

When I run the code, in the onCreate :

btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showVehicleDetails();
            showRegisterDialog();
        }
    });

Edit

This is what happens when I press Register button, it sticks on this rather than dismiss

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
LizG
  • 2,246
  • 1
  • 23
  • 38
  • 1
    Can you start by sharing any code that you have done so far? – Tamir Abutbul Jul 06 '19 at 20:21
  • 1
    one way to do it is to create Custom Layouts for the 2 dialogues as they have different data and the steps would be as follows 1. in .setPositiveButton click (initiate saving data into firebase which you will get using dialog component content textview edittext ... etc ) 2. in the firebase on success start the second dialogue and i prefer to keep them in methods so that you can trace each of them individially , and dismiss the current dialogue which you can as you have reference of it now 3. in the second dialogue do step 1 and 2 until save and instead of initiating just dismiss dialgoue – Hossam Eldeen Onsy Jul 06 '19 at 20:24
  • @TamirAbutbul see the added code – LizG Jul 06 '19 at 20:36
  • @HossamEldeenOnsy See code added.. As you can see I have already created the custom layouts/dialogs. – LizG Jul 06 '19 at 20:47
  • 1
    Remove this `showRegisterDialog();` from the OnClickListener and put it inside onDataChange after the foreach of datasnapshot along with dialogue.dismiss() ... remove dialogue.dismiss right after the listener and put it before you put the showRegisterDialog(); Now in the showRegisterDialog put the dialogueDismiss after the `Snackbar.make(rootLayout, "Registration successful !!!", Snackbar.LENGTH_SHORT).show();` – Hossam Eldeen Onsy Jul 06 '19 at 20:57
  • @HossamEldeenOnsy I put the dialog.dismiss after the Snackbar as you stated. But I don't have a foreach, I have a for loop in the onDataChange - if I put showRegisterDialog(); dialog.dismiss(); there, the dialog.dismiss is out of scope. – LizG Jul 06 '19 at 21:09
  • 1
    Hey @LizG , I have added an answer using custom dialog classes. I believe that it can help you simplify your code and solve the problem. just remember - you can solve one problem in many many ways, this is just another way to handle your problem. – Tamir Abutbul Jul 06 '19 at 21:11
  • 1
    the dialog.dismiss is out of scope <- regarding this point you can make it final or global as you are about to alter it regarding -> But I don't have a foreach -> yes i mean the for loop in the onDataChange put it after this for loop to make sure all the data has been altered before going to next step – Hossam Eldeen Onsy Jul 06 '19 at 21:11
  • ok so I did what you said, and it worked except it didn't add the data to firebase - the data from showRegisterDialog is added but not from showVehicleDetails is NOT added – LizG Jul 06 '19 at 21:19
  • 1
    If you are creating this user the firstTime then his ID needs to be in the firebase database , if you are just adding into a node in the database itself then you will need to push data by the push method into the database then get the key and then set example is like this : https://stackoverflow.com/a/46721402/7586266 then you instead of id use the key you have fetched to add values – Hossam Eldeen Onsy Jul 06 '19 at 21:25
  • @HossamEldeenOnsy So I made the changes and it does everything it should except when I press the REGISTER button in showRegisterDialog it doesn't dismiss the dialog.. See image in EDITS – LizG Jul 06 '19 at 21:31
  • 1
    does the Register button stay dimmed ? or if you can , provide which snackbar shows , you can try the showRegisterDialgoue i altered it in the answer , you can also add dialogue.dismiss(); inside the failure callback to see if that's the reason as with the concept should work now fine regarding clicking and dismissing – Hossam Eldeen Onsy Jul 06 '19 at 21:34
  • Not showing any snackbar, it just stays on that image. Normally the Register button is disabled until all textfields are filled out and the switch is turned on. Tried your edits and still same outcome. – LizG Jul 06 '19 at 21:41
  • Ok. I am seeing the Snackbar - Registration is Successful! But the display is still the same, stuck like the image. I have to hit < Back button several times to get rid of it. – LizG Jul 06 '19 at 21:52
  • 1
    Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196088/discussion-between-hossam-eldeen-onsy-and-lizg). – Hossam Eldeen Onsy Jul 06 '19 at 22:30
  • @HossamEldeenOnsy Can you meet me back in chat. Something has gone wrong in the code... – LizG Jul 07 '19 at 00:58

2 Answers2

2

Okay i don't recommend it to be like this i prefer it to be cleaner as @Tamir expressed in his answer however here is what you need to do so you can refactor later on for cleaner and simpler code to help you take apart and debug easily.

As i explained in the comment here are the amends you will alter Regarding showVehicleDetails :

AlertDialog.Builder alert_dialog = new AlertDialog.Builder(this);
alert_dialog.setTitle("VEHICLE DETAILS");
alert_dialog.setMessage("Please, fill in the following:");
LayoutInflater inflate = LayoutInflater.from(this);
View vehicle_details = inflate.inflate(R.layout.layout_vehicle_details, null);

final MaterialEditText edtYear = vehicle_details.findViewById(R.id.year);
final MaterialEditText edtCMNM = vehicle_details.findViewById(R.id.cmnm);
final MaterialEditText edtPlate = vehicle_details.findViewById(R.id.plate);

alert_dialog.setView(vehicle_details);

alert_dialog.setPositiveButton("SUBMIT", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(final DialogInterface dialog, int which) {


        // check validation
        if (TextUtils.isEmpty(edtYear.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter year of your vehicle", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }

        if (TextUtils.isEmpty(edtCMNM.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter the Color, Make and Model of your vehicle",
                    Snackbar.LENGTH_SHORT).show();

            return;
        }

        if (TextUtils.isEmpty(edtPlate.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter your license plate number", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }

        // save to firebase/ Users/Drivers ...

        details = users;
        details.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                // get drivers id
                for (DataSnapshot ss : snapshot.getChildren()) {
                    String id = ss.getKey();

                    String year = edtYear.getText().toString();
                    String cmnm = edtCMNM.getText().toString();
                    String plate = edtPlate.getText().toString();

                    Log.e(TAG, "year: " + year + ", cmnm: " + cmnm + ", plate: " + plate);

                    // data sent
                    details.child(id).child("year").setValue(year);
                    details.child(id).child("cmnm").setValue(cmnm);
                    details.child(id).child("plate").setValue(plate);
                }
                 showRegisterDialog();
                 dialog.dismiss();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
});
AlertDialog dialog = alert_dialog.create();
dialog.show();}

and here are the amends you will alter Regarding showRegisterDialogue :

final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("REGISTER");
builder.setMessage("Please use email to register");
LayoutInflater inflater = LayoutInflater.from(this);
View register_layout = inflater.inflate(R.layout.layout_register, null);

final MaterialEditText edtEmail = register_layout.findViewById(R.id.email);
final MaterialEditText edtPassword = register_layout.findViewById(R.id.password);
final MaterialEditText edtName = register_layout.findViewById(R.id.usersname);
final MaterialEditText edtPhone = register_layout.findViewById(R.id.cell);

final MaterialAnimatedSwitch policies_switch = register_layout.findViewById(R.id.policies_switch);

builder.setView(register_layout);

builder.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(final DialogInterface dialog, int which) {

        // check validation
        if (TextUtils.isEmpty(edtEmail.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter email address", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }

        if (TextUtils.isEmpty(edtPhone.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter phone number", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }

        if (TextUtils.isEmpty(edtPassword.getText().toString())) {
            Snackbar.make(rootLayout, "Please enter password", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }

        if (edtPassword.getText().toString().length() < 6) {
            Snackbar.make(rootLayout, "Password too short !!!", Snackbar
                    .LENGTH_SHORT).show();

            return;
        }


        // Register new user
        auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),
                edtPassword.getText().toString())
                .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {
                        // Save user to db
                        Driver driver = new Driver();
                        driver.setEmail(edtEmail.getText().toString());
                        driver.setUsersname(edtName.getText().toString());
                        driver.setCell(edtPhone.getText().toString());
                        driver.setPassword(edtPassword.getText().toString());
                        driver.setRates("4.5"); // TODO: Default added

                        // use uid to key
                        users.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .setValue(driver)
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Snackbar.make(rootLayout, "Registration successful !!!",
                                                Snackbar.LENGTH_SHORT).show();
                                        dialog.dismiss();
                                    }
                                })

                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Snackbar.make(rootLayout, "Failed" + e.getMessage(),
                                                Snackbar.LENGTH_SHORT).show();
                                        dialog.dismiss();
                                    }
                                });
                    }
                })

                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Snackbar.make(rootLayout, "Failed" + e.getMessage(),
                                Snackbar.LENGTH_SHORT).show();
                                        dialog.dismiss();
                    }
                });
    }
});

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

final AlertDialog dialog = builder.create();

/* If switch is on, enable REGISTER button */
policies_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(boolean isChecked) {
        if (isChecked) {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); // if checked, enable
        }
    }
});

dialog.show();

dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); // set disabled by default

 }

and for The ClickListener you will just remove the showRegisterDialogue and it would be like this

btnRegister.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        showVehicleDetails();
    }
});
  • I have tried cleaning and rebuilding the project among other things and still the dialog is not dismissing when I click on Register. It is showing a successful snackbar and it is adding the data to firebase. Any ideas? – LizG Jul 06 '19 at 22:19
  • 1
    here is an idea after `driver.setRates("4.5");` add `dialog.dismiss();` try it and let me know what happened @LizG – Hossam Eldeen Onsy Jul 06 '19 at 22:23
  • Same, no difference – LizG Jul 06 '19 at 22:26
0

For this, I would use 2 custom dialogs classes.

Every dialog will have his class and layout, and now we need to do this:

  • Show dialog A

  • Send some data to firebase and wait for good callback

  • After we got the callback from dialog A close it and show you second dialog.

Sounds good? let's see how we write this:


Here is an example for generic custom dialog:

This will be your dialog class (or something similar, it's only an example):

public class FullSizeImageDialog extends Dialog {
private ImageView imageView;
private ProgressBar fullImageProgreesBar;
private Context dialogContext;

public FullSizeImageDialog(@NonNull Context context) {
    super(context);
    setContentView(R.layout.full_size_image_dialog);
    dialogContext = context;
    imageView = findViewById(R.id.full_size_image);
    fullImageProgreesBar = findViewById(R.id.fullImageProgreesBar);
    }
}

And this is your layout for the dialog (R.id.full_size_image in my case):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">


 <!--Place your views here-->


 </android.support.constraint.ConstraintLayout>

And when you want to show your dialog it's super easy:

FullSizeImageDialog dialog = new FullSizeImageDialog ();
dialog.show();

When the first dialog will get the callback from firebase call dismiss() for dialog A and show() for dialog B.


Why I recommend using this and not AlertDialog.Builder :

  • You can build your layout in a faster way with custom dialog.

  • No need to write a lot of code just to add views when you can have a custom layout.

  • It's easier (or so I believe) for you to see myCoolDialog.show(); rather than 50 lines of code or more in a single method.

  • Do you need to change anything regarding your dialog look and code? good, go to your separate class and change it instead of adding 20 more code lines to your activity.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • Thanks for the new way of doing this @Tamir but I would like to keep it as I have it right now as it is consistent with the dialogs I have throughout my app. I will definitely keep this in mind for the next time I create dialogs :-) – LizG Jul 06 '19 at 21:56