如何验证RadioGroup为必填字段?

时间:2019-10-07 13:55:20

标签: java android

我正在制作一个应用程序,并且具有注册活动来使用Firebase注册用户。一切正常,但我不了解如何验证RadioGroup为男女性别。当我单击“注册”时,即使未选中“单选按钮”,值也会保存到数据库中。

这是我拥有的:


        first_name = (EditText) findViewById(R.id.first_name);
        last_name = (EditText) findViewById(R.id.last_name);
        register_email = (EditText) findViewById(R.id.register_email);
        register_password = (EditText) findViewById(R.id.register_password);
        confirm_password = (EditText) findViewById(R.id.confirm_password);
        male = (RadioButton) findViewById(R.id.checkBox);
        female = (RadioButton) findViewById(R.id.checkBox2);
        gender = (RadioGroup) findViewById(R.id.gender);
        login_to_account = (TextView) findViewById(R.id.login_to_account);
        signUp = (Button) findViewById(R.id.signup_button);
        pd = new ProgressDialog(this);

        login_to_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent GoToLoginActivity = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(GoToLoginActivity);
                finish();
            }
        });

        gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mGenderOptions = gender.findViewById(checkedId);

                switch (checkedId) {
                    case R.id.checkBox:
                        strGender = mGenderOptions.getText().toString();
                        break;
                    case R.id.checkBox2:
                        strGender = mGenderOptions.getText().toString();
                        break;

                    default:
                }
            }
        });

        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String firstName = first_name.getText().toString();
                String lastName = last_name.getText().toString();
                String email = register_email.getText().toString();
                String password = register_password.getText().toString();
                String confirmPassword = confirm_password.getText().toString();
                validateRegisteringFields(firstName, lastName, email, password, confirmPassword, strGender);
                registerUser(firstName, lastName, email, password, strGender);
            }
        });

    }

    private void registerUser(final String firstName, final String lastName, final String email ,final String password, final String strGender) {
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser firebaseUser = mAuth.getCurrentUser();
                            assert firebaseUser != null;
                            String userId = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userId);

                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("id", userId);
                            hashMap.put("firstName", firstName);
                            hashMap.put("lastName", lastName);
                            hashMap.put("gender", strGender);

                            reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Intent registerActivityIntent = new Intent(RegisterActivity.this, MainActivity.class);
                                        registerActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(registerActivityIntent);
                                        finish();
                                    }
                                }
                            });
                        } else {
                            Toast.makeText(RegisterActivity.this, "User already exists", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void validateRegisteringFields(final String firstName, final String lastName,
                                           final String email ,final String password,
                                           final String confirmPassword, final String strGender) {
        if (TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(strGender)) {
            Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
        } else if (password.length() < 6) {
            Toast.makeText(RegisterActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(RegisterActivity.this, "Please enter a valid email address", Toast.LENGTH_SHORT).show();
        } else if (!confirmPassword.equals(password)) {
            Toast.makeText(RegisterActivity.this, "Passwords doesn't match", Toast.LENGTH_SHORT).show();
        }
    }

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这样验证是错误的。

switch (checkedId) {
            case R.id.checkBox:
                strGender = mGenderOptions.getText().toString();
                break;
            case R.id.checkBox2:
                strGender = mGenderOptions.getText().toString();
                break;

            default:
        }

因为它将始终显示为真,所以将从您的广播按钮中读取文本字符串。
要解决此问题,请使用radioButton.isChecked();,如果选中了收音机,则返回true,否则返回false
好的,只需检查您的方法validateRegisteringFields()

if (!female.isChecked() && !male.isChecked()){
            Toast.makeText(RegisterActivity.this, "Please select your gender", Toast.LENGTH_SHORT).show();
        }