【问题标题】:how to check password and confirm password in field in android?如何在android中的字段中检查密码并确认密码?
【发布时间】:2017-05-13 16:34:03
【问题描述】:

我正在制作注册表单,其中有一个名为密码和确认密码的字段。我想在用户输入密码时使它们相等..但我不知道如何通过编码使它们相等..任何人都可以帮助?? 这是注册页面:

 public class RegistrationForm extends AppCompatActivity {

    EditText fn,ln,mb,em,pw,cpw,dob,gen;
    Switch sw;
    RadioGroup male,feml;
    Switch swth;
    private ProgressDialog pDialog;
    String status="";


    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
            "[a-zA-Z0-9+._%-+]{1,256}" +
                    "@" +
                    "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" +
                    "(" +
                    "." +
                    "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
                    ")+"
    );


    private static String url_create_book = "http://cloud.....com/broccoli/creatinfo.php";

    // JSON Node names
    // JSON Node names
    private static final String TAG_SUCCESS = "success";


String rval;

    JSONParser jsonParser = new JSONParser();
    private int serverResponseCode = 0;
    Context c;
    int i=0;


    Button sub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_form);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        fn=(EditText)findViewById(R.id.fnm) ;
        ln=(EditText)findViewById(R.id.lnm) ;
        mb=(EditText)findViewById(R.id.mobile) ;




        pw=(EditText)findViewById(R.id.pass) ;
        cpw=(EditText)findViewById(R.id.cpass) ;


        cpw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String passwrd = pw.getText().toString();
                if (editable.length() > 0 && passwrd.length() > 0) {
                    if(!cpw .equals(passwrd )){
                        // give an error that password and confirm password not match
                    }

                }
            }
        });





























        dob=(EditText)findViewById(R.id.dob);

       dob.setOnClickListener(new View.OnClickListener(){
                                  @Override
                                  public void onClick(View v) {
                                      int mYear, mMonth, mDay;
                                      final Calendar c = Calendar.getInstance();
                                      mYear = c.get(Calendar.YEAR);
                                      mMonth = c.get(Calendar.MONTH);
                                      mDay = c.get(Calendar.DAY_OF_MONTH);
                                      DatePickerDialog datePickerDialog = new DatePickerDialog(RegistrationForm.this,R.style.datepicker, new DatePickerDialog.OnDateSetListener() {
                                          @Override
                                          public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                              dob.setText(year + "/" + (month + 1) + "/" + dayOfMonth);
                                             // dob.setText(dayOfMonth + "/" + (month + 1) + "/" + );
                                          }
                                      }, mYear, mMonth, mDay);
                                      //forsetting minimum date for selection
                                     // datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
                                      datePickerDialog.show();
                                  }
                              });


       // RadioButton male=(RadioButton)findViewById(R.id.rgm) ;

       // RadioButton feml=(RadioButton)findViewById(R.id.rgf) ;

        Switch swth=(Switch)findViewById(R.id.mySwitch) ;


//////set the switch to ON
        swth.setChecked(false);

//////attach a listener to check for changes in state
        swth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

                if(isChecked){
                    status="true"; //edit here
                }else{
                    status="false";
                }

            }
        });


        RadioGroup rgrp=(RadioGroup)findViewById(R.id.rg);

        RadioButton radioButton;





        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        sub=(Button)findViewById(R.id.sub2);




        sub.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                RadioGroup rgrp = (RadioGroup) findViewById(R.id.rg);
                em = (EditText) findViewById(R.id.email);
                RadioButton radioButton;
                int selectedId = rgrp.getCheckedRadioButtonId();
                // find the radiobutton by returned id
                radioButton = (RadioButton) findViewById(selectedId);
                rval = radioButton.getText().toString();
                // Toast.makeText(RegistrationForm.this, rval, Toast.LENGTH_SHORT).show();

                if(validate()){
                    new CreateNewProduct().execute();
                    // startActivity(new Intent(RegistrationForm.this, Home.class));
                }
            }
            private boolean validate() {
                String checkemail = em.getText().toString();
                String pass=pw.getText().toString();
                String cpass=cpw.getText().toString();

                boolean temp=true;
                if(!EMAIL_ADDRESS_PATTERN.matcher(checkemail).matches()){
                    Toast.makeText(RegistrationForm.this,"Invalid Email Address",Toast.LENGTH_SHORT).show();
                    temp=false;
                }
                else if(!pass.equals(cpass)){
                    Toast.makeText(RegistrationForm.this,"Password Not matching",Toast.LENGTH_SHORT).show();
                    temp=false;
                }
                new CreateNewProduct().execute();
return false;
            }
        });

    }







    class CreateNewProduct extends AsyncTask<String, String, String> {
        private  String fname;
        private  String lname;
        private  String email;
        private  String passwrd;
        private  String cpasswrd;
        private String dobr;
        private String mobile;



        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RegistrationForm.this);
            pDialog.setMessage("Creating books..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            fname = fn.getText().toString();
            lname = ln.getText().toString();
            email = em.getText().toString();
            passwrd = pw.getText().toString();
            cpasswrd = cpw.getText().toString();
            dobr = dob.getText().toString();
            mobile=mb.getText().toString();
            //Toast.makeText(RegistrationForm.this,
            //dobr, Toast.LENGTH_SHORT).show();
        }




        protected String doInBackground(String... args) {


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("First_Name", fname));
            params.add(new BasicNameValuePair("Last_Name",lname));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("Gender", rval));
            params.add(new BasicNameValuePair("password", passwrd));
            params.add(new BasicNameValuePair("confirmPasw",cpasswrd));
            params.add(new BasicNameValuePair("DOB",dobr));
            params.add(new BasicNameValuePair("sms_subscrb",status));
            params.add(new BasicNameValuePair("Mobile_No",mobile));



            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_book,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), Login.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }



























    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

【问题讨论】:

  • 偷懒的方法就是检查passwrd.equals(cpasswrd)
  • 我想要一些类似的东西,比如当我输入确认密码时,如果我当时犯了任何错误,它就会给我错误
  • 使用等号比较两个字符串,password.equals(comparepassword)
  • 您可以使用此方法编写代码 textchange edittext.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) {} public void beforeTextChanged(CharSequence s, int start, int count, int after ) { } public void onTextChanged(CharSequence s, int start, //写你的代码 } });

标签: android passwords


【解决方案1】:
if (!user_password.getText().toString().equals(user_confirm_password.getText().toString()){

    Toast.makeText(this, "Confirm password is not correct", Toast.LENGTH_SHORT).show();

  }
  • 其中 user_password 和 user_confirm_password 是您的编辑文本。

【讨论】:

    【解决方案2】:
    if (edittextconfirmpassword.getText().toString().equals("")) {
                showAlertDialog("Please provide confirm Account number.");
                return;
            } else if (edittextconfirmpassword.getText().toString().length() < 9) {
                showAlertDialog("Please provide valid confirm Account number.");
                return;
            } else if (!edittextbankaccountnumber.getText().toString().equals(edittextconfirmpassword.getText().toString())) {
                showAlertDialog("Account number and Confirm Account number should be same.");
                return;
            }
    

    【讨论】:

    • 在这种情况下验证帐号的两个编辑文本
    【解决方案3】:

    在检查电子邮件模式后,您需要匹配两个字段或不匹配..像这样更改 子按钮的代码....

    sub.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                RadioGroup rgrp = (RadioGroup) findViewById(R.id.rg);
                em = (EditText) findViewById(R.id.email);
                RadioButton radioButton;
                int selectedId = rgrp.getCheckedRadioButtonId();
                // find the radiobutton by returned id
                radioButton = (RadioButton) findViewById(selectedId);
                rval = radioButton.getText().toString();
               // Toast.makeText(RegistrationForm.this, rval, Toast.LENGTH_SHORT).show();
    
    
                if(validate){
                    new CreateNewProduct().execute();
                    // startActivity(new Intent(RegistrationForm.this, Home.class));
                }  
            }
            private boolean validate() {
                boolean temp=true;
                String checkemail = em.getText().toString();
                String pass=pw.getText().toString();
                String cpass=cpw.getText().toString();
                if(!EMAIL_ADDRESS_PATTERN.matcher(checkemail).matches()){
                     Toast.makeText(Registratiomform.this,"Invalid Email Address",Toast.LENGTH_SHORT).show();
                     temp=false;
                }
                else if(!pass.equals(cpass)){
                     Toast.makeText(Registratiomform.this,"Password Not matching",Toast.LENGTH_SHORT).show();
                     temp=false;
                }
                return temp;
            }
        });
    

    【讨论】:

    • 更新了我的代码...输入相同的代码...不要在 validate() 方法中添加额外的new CreateNewProduct().execute();
    • @z.al 喜欢编码:)
    • 会尽快通知你:)
    • 你知道这有什么问题吗......stackoverflow.com/questions/41406071/…
    【解决方案4】:
    if(password.getText().toString().equals(confirmpassword.getText().toString())){
    

    用您的编辑文本名称替换密码并确认密码

    【讨论】:

      【解决方案5】:

      @z.al, 如果您想在输入确认密码时检查密码和确认密码是否相同,您必须在确认密码编辑时执行 TextWatcher文本(在你的情况下 cpw )就像

      cpw.addTextChangedListener(new TextWatcher() {
                  @Override
                  public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
      
                  }
      
                  @Override
                  public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
      
                  }
      
                  @Override
                  public void afterTextChanged(Editable editable) {
                      String passwrd = pw.getText().toString();
                      if (editable.length() > 0 && passwrd.length() > 0) { 
                          if(!cpasswrd .equals(passwrd )){
                              // give an error that password and confirm password not match
                          }
      
                      } 
                  }
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-21
        • 1970-01-01
        • 2019-04-12
        • 2012-12-02
        • 2013-03-06
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        相关资源
        最近更新 更多