Edittext: Error solved then enable the send button

2019-03-06 16:29发布

问题:

i have five edittext fields which is checking the fields and restricts some data when entered wrong as shown below code but now if i enter wrong data in edittext then it will enter the information into database so i want to disable the button if there are errors in any edittext . The error might be in 1 to 5 edittext it has to disable the send button. It has to only enable the send button when there are no errors in the edittext fields

public class MaINActivity extends Activity {

    String result = null;
    InputStream is = null;
    String valid_email = null;
    String valid_name = null;
    String valid_last = null;
    String valid_age = null;
    String v5,v1,v2,v3,v4,v6;
    String valid_confirm = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_subscribe);

    final EditText editText = (EditText)findViewById(R.id.firstname);

    final EditText editText1 = (EditText)findViewById(R.id.lastname);

    final EditText editText2 = (EditText)findViewById(R.id.age1);

    final EditText editText3 = (EditText)findViewById(R.id.email);

    final EditText editText4 = (EditText)findViewById(R.id.confirm);

    editText2.addTextChangedListener(new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_Age(editText2);
        }

        private void Is_Valid_Age(EditText editText2) {

            if(editText2.length() == 0 || editText2.equals("") || editText2 == null || "".equals(editText2.getText().toString())) {
                valid_age = null;
            }else {
                valid_age = editText2.getText().toString();
            }
        }

    });
    editText1.addTextChangedListener(new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {


        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_Last_Name(editText1);

        }

        private void Is_Valid_Last_Name(EditText editText1) throws NumberFormatException {

            if (editText1.getText().toString().length() <= 0) {
                editText1.setError("Accept Alphabets Only.");
                valid_last = null;
            } else if (!editText1.getText().toString().matches("[a-zA-Z ]+")) {
                editText1.setError("Accept Alphabets Only.");
                valid_last = null;
            } else if(editText1.length() == 0 || editText1.equals("") || editText1 == null || "".equals(editText1.getText().toString())) {
                valid_last = null;
            }else {
                valid_last = editText1.getText().toString();
            }

        }

    });

    editText.addTextChangedListener(new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {


        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


        }

        @Override
        public void afterTextChanged(Editable s) {
            Is_Valid_First_Name(editText);

        }

        private void Is_Valid_First_Name(EditText editText) throws NumberFormatException {

            if (editText.getText().toString().length() <= 0) {
                editText.setError("Accept Alphabets Only.");
                valid_name = null;
            } else if (!editText.getText().toString().matches("[a-zA-Z ]+")) {
                editText.setError("Accept Alphabets Only.");
                valid_name = null;
            } else if(editText.length() == 0 || editText.equals("") || editText == null || "".equals(editText.getText().toString())) {
                valid_name = null;
            }else {
                valid_name = editText.getText().toString();
            }

        }
    }); 

    editText3.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            Is_Valid_Email_Address(editText3);
        }

        public void Is_Valid_Email_Address(EditText editText3) {
            if (editText3.getText().toString() == null) {
                editText3.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(editText3.getText().toString()) == false) {
                editText3.setError("Invalid Email Address");
                valid_email = null;
            } else if(editText3.length() == 0 || editText3.equals("") || editText3 == null || "".equals(editText3.getText().toString())) {
                valid_email = null;
            }else {
                valid_email = editText3.getText().toString();
            }
        }
    });

    editText4.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {


        }

        @Override
        public void afterTextChanged(Editable s) {

            Is_Valid_Confirm_Address(editText4);
        }


        public void Is_Valid_Confirm_Address(EditText editText4) {
            if (editText4.getText().toString() == null) {
                editText4.setError("Invalid Email Address");
                valid_confirm = null;
            } else if (isEmailValid(editText4.getText().toString()) == false) {
                editText4.setError("Invalid Email Address");
                valid_confirm = null;
            } else if (editText4.getText().toString().equals(editText3.getText().toString())) {

                valid_confirm = editText4.getText().toString();
            } else if(editText4.length() == 0 || editText4.equals("") || editText4 == null || "".equals(editText4.getText().toString())) {
                valid_confirm = null;
            } else {
                editText4.setError("Confirm Email is Not Matching");
                valid_confirm = null;
            } 

        }
    });

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener(){

        @SuppressLint("NewApi")
        @Override
        public void onClick(View view) {

            v1 = editText.getText().toString();
            v2 = editText1.getText().toString();
            v3 = editText2.getText().toString();
            v4 = editText3.getText().toString();
            v5 = editText4.getText().toString();  


            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("firstname",v1));
            nameValuePairs.add(new BasicNameValuePair("lastname",v2));
            nameValuePairs.add(new BasicNameValuePair("age",v3));
            nameValuePairs.add(new BasicNameValuePair("email_address",v4));
            nameValuePairs.add(new BasicNameValuePair("confirm_email_address",v5));



            StrictMode.setThreadPolicy(policy);

            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("localhost/Android/Insert.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                Log.e("log_tag", "connection success ");
                Toast.makeText(getApplicationContext(), "Subscription Successfull.Thank You for Subscribing you have now been added to our Mailing Lists", Toast.LENGTH_LONG).show();
            }
            catch(Exception e)
            {
                Log.e("log_tag", "Error in http connection "+e.toString());
                Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
            }
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) 
                {
                        sb.append(line + "\n");
                        Intent i = new Intent(getBaseContext(),SecondActivity.class);
                        startActivity(i);
                }
                is.close();

                result=sb.toString();
            }
            catch(Exception e)
            {
               Log.e("log_tag", "Error converting result "+e.toString());
            }
            try
            {   
                    JSONObject json_data = new JSONObject(result);
                    CharSequence w= (CharSequence) json_data.get("result");

                    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();
            }
            catch(JSONException e)
            {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
            }
        }


    });

}

    private boolean isEmailValid(String email) {

        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }}

回答1:

Try this way,hope this will help you to solve your problem.

activity_subscribe.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="5dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <EditText
                android:id="@+id/edtFirstName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="FirstName"
                android:layout_marginTop="5dp"/>

            <EditText
                android:id="@+id/edtLastName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="LastName"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtAge"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Age"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email"
                android:inputType="textEmailAddress"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Password"
                android:layout_marginTop="5dp"/>
            <EditText
                android:id="@+id/edtConfirmPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Confirm Password"
                android:layout_marginTop="5dp"/>
            </LinearLayout>
        </ScrollView>
    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"/>

</LinearLayout>

SubscribeActivty.java

public class SubscribeActivty extends Activity {

    InputStream is = null;
    private EditText edtFirstName;
    private EditText edtLastName;
    private EditText edtAge;
    private EditText edtEmail;
    private EditText edtPassword;
    private EditText edtConfirmPassword;
    private Button btnSubmit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscribe);

        edtFirstName = (EditText) findViewById(R.id.edtFirstName);
        edtLastName = (EditText) findViewById(R.id.edtLastName);
        edtAge = (EditText) findViewById(R.id.edtAge);
        edtEmail = (EditText) findViewById(R.id.edtEmail);
        edtPassword = (EditText) findViewById(R.id.edtPassword);
        edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        btnSubmit.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View view) {

                boolean isValid = true;
                if (edtFirstName.getText().toString().length() <= 0) {
                    edtFirstName.setError("Value  Required");
                    isValid = false;
                } else if (!edtFirstName.getText().toString().matches("[a-zA-Z ]+")) {
                    edtFirstName.setError("Accept Alphabets Only.");
                    isValid = false;
                }

                if (edtLastName.getText().toString().length() <= 0) {
                    edtLastName.setError("Value  Required");
                    isValid = false;
                } else if (!edtLastName.getText().toString().matches("[a-zA-Z ]+")) {
                    edtLastName.setError("Accept Alphabets Only.");
                    isValid = false;
                }

                if (edtEmail.getText().toString().length() <= 0) {
                    edtEmail.setError("Value  Required");
                    isValid = false;
                } else if (!isEmailValid(edtEmail.getText().toString())) {
                    edtLastName.setError("Invalid Email.");
                    isValid = false;
                }

                if (edtAge.getText().toString().length() <= 0) {
                    edtAge.setError("Value  Required");
                    isValid = false;
                } else if (!edtAge.getText().toString().matches("[0-9 ]+")) {
                    edtAge.setError("Accept Numbers Only.");
                    isValid = false;
                }

                if (edtPassword.getText().toString().length() <= 0) {
                    edtPassword.setError("Value  Required");
                    isValid = false;
                }

                if (edtConfirmPassword.getText().toString().length() <= 0) {
                    edtConfirmPassword.setError("Value  Required");
                    isValid = false;
                } else if (!edtConfirmPassword.getText().toString().equals(edtPassword.getText().toString())) {
                    edtConfirmPassword.setError("Password Mismatch.");
                    isValid = false;
                }


                if (isValid) {
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                    nameValuePairs.add(new BasicNameValuePair("firstname", edtFirstName.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("lastname", edtLastName.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("age", edtAge.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("email", edtEmail.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("password", edtPassword.getText().toString()));

                    submitDataOnServer(nameValuePairs);
                }
            }

        });

    }

    public void submitDataOnServer(final ArrayList<NameValuePair> nameValuePairs){
        new AsyncTask<Void,Void,String>(){
            @Override
            protected String doInBackground(Void... params) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("localhost/Android/Insert.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    Log.e("log_tag", "connection success ");
                    Toast.makeText(getApplicationContext(), "Subscription Successfull.Thank You for Subscribing you have now been added to our Mailing Lists", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Log.e("log_tag", "Error in http connection " + e.toString());
                    Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
                }
                try {

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();

                    return sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                try {
                    JSONObject json_data = new JSONObject(result);
                    CharSequence w = (CharSequence) json_data.get("result");

                    Toast.makeText(getApplicationContext(), w, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }


    public boolean isEmailValid(final String mailAddress) {
        Pattern pattern;
        Matcher matcher;
        final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(mailAddress);
        return matcher.matches();
    }
}