Where to place sign in credentials check - android Dialog

亡梦爱人 提交于 2020-07-10 09:27:13

问题


I am trying to create a login credential screen when user clicks on a setting button. And if login credentials looks right then it should to settings screen. This is the official tutorial i am following.

I am managed to create a dialog and it showing the window once the button is clicked. I also passing back the dialog to the Dialog host and here is the code snippet.

// Dialog Fragment
public class SignInDialogFragment extends AppCompatDialogFragment {
    // Use this instance of the interface to deliver action events
    private SignInDialogListener listener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.dialog_signin, null))
            .setPositiveButton("Sign in ", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // Send the positive button event back to the host activity
                    listener.onDialogPositiveClick(SignInDialogFragment.this);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    SignInDialogFragment.this.getDialog().cancel();
                }
            });

        return builder.create();
    }

    public interface SignInDialogListener {
        void onDialogPositiveClick(SignInDialogFragment dialog);
    }

    // Override the Fragment.onAttach() method to instantiate the LoginDialogListener
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            listener = (SignInDialogListener) context;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(context.toString()
                    + " must implement NoticeDialogListener");
        }
    }
}

// Main activity
public class IdleActivity extends BaseActivity implements SignInDialogFragment.SignInDialogListener {
  protected void onCreate(Bundle savedInstanceState) {
    ...
    ...
    FloatingActionButton settingsButton = findViewById(R.id.floatingButtonTools);
    buttonTools.setOnClickListener(v-> {
            showSignInDialog();
        });
   ...
   ...
  }

  private void showSignInDialog() {
    // Create an instance of the dialog fragment and show it
    SignInDialogFragment signInDialog = new SignInDialogFragment();
    signInDialog.show(getSupportFragmentManager(), "signin");
  }

  @Override
    public void onDialogPositiveClick(SignInDialogFragment dialog) {

  }
}

For now i am thinking some hard coded check in credential like this and latter i will move it to a service call.

if(user.isequals("abcd") && password .isequals("1234")) {
  Intent intent = new Intent(getApplicationContext(), 
                       SettingsActivity.class);
 startActivity(intent);
}
  1. I am not sure where should i place this code this credential check code ? In the "main activity" or in the "Sign in dialog fragment class"
  2. I see that when ever i click on positive or negative button , its closing the dialog window and returning to the main activity irrespective of sign in credentials correct or wrong. I would like to display the credential dialog screen until they enter the correct credentials.
  3. I see that there is a same print out happening in "run tab" and its happening continuously and repeatedly throughout the life cycle of the dialog window is on the screen

回答1:


TL;DR - Android Dialog Fragments by default close when a user clicks any button or list option in them. To prevent that, you need to override the onDismiss() method and continue with the default dismiss behaviour only if the user has entered the correct credentials.

According to the official Android documentation on dialog fragments,

When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.

The system also dismisses the dialog when the user touches an item in a dialog list, except when the list uses radio buttons or checkboxes. Otherwise, you can manually dismiss your dialog by calling dismiss() on your DialogFragment.

In case you need to perform certain actions when the dialog goes away, you can implement the onDismiss() method in your DialogFragment.

You can also cancel a dialog. This is a special event that indicates the user explicitly left the dialog without completing the task. This occurs if the user presses the Back button, touches the screen outside the dialog area, or if you explicitly call cancel() on the Dialog (such as in response to a "Cancel" button in the dialog).

As shown in the example above, you can respond to the cancel event by implementing onCancel() in your DialogFragment class.

So, you must check if your user's credentials are correct in the listener.onDialogPositiveClick() method. Then, you must update a boolean value, say hasUserEnteredCorrectCredentials to true. Then, you must override onDismiss() and allow it to dismiss the dialog only if hasUserEnteredCorrectCredentials is true, else keep the dialog open and show the user an error.

Remember, you will have to find a way to update the boolean hasUserEnteredCorrectCredentials from the place where you override the interface method.

So your code will become -

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDialogFragment;

public class SignInDialogFragment extends AppCompatDialogFragment {

    // Use this instance of the interface to deliver action events
    private SignInDialogListener listener;
    // This boolean checks whether the credentials are correctly entered
    private boolean hasUserEnteredCorrectCredentials = false;

    // Called when the dialog fragment is created.
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Initialise an alert dialog builder
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the activity's default layout inflater to inflate the dialog fragment
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        // Set the view to the inflated fragment
        builder.setView(inflater.inflate(R.layout.dialog_signin, null))
                // Set the positive button's text and onClickListener
                .setPositiveButton("Sign in", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // Send the positive button event back to the host activity
                        // TODO - Find a way to set hasUserEnteredCorrectCredentials to true if the credentials are correct.
                        listener.onDialogPositiveClick(SignInDialogFragment.this);
                    }
                })
                // Set the positive button's text and onClickListener
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // Cancel the dialog
                        SignInDialogFragment.this.getDialog().cancel();
                    }
                });

        // Return the created dialog to the host activity
        return builder.create();
    }

    // Interface to manage clicks on the dialog's buttons
    public interface SignInDialogListener {
        // ClickListener for the positive button
        void onDialogPositiveClick(SignInDialogFragment dialog);
    }

    // Override the Fragment.onAttach() method to instantiate the SignInDialogListener
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            listener = (SignInDialogListener) context;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(context.toString()
                    + " must implement SignInDialogListener");
        }
    }

    // Called when the user clicks a button, or when the user selects an option in a list dialog
    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        // Dismiss the dialog only if the user has entered correct credentials
        if (hasUserEnteredCorrectCredentials) {
            super.onDismiss(dialog);
        }
    }
}

Hope this helps!



来源:https://stackoverflow.com/questions/58763610/where-to-place-sign-in-credentials-check-android-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!