Sprawdź, czy EditText jest pusty. [zamknięte]

Mam 5 EditTexts w Androidzie dla użytkowników do wprowadzenia. Chciałbym wiedzieć, czy mogę mieć metodę sprawdzania wszystkich 5 EditTexts, jeśli są null. Jest na to jakiś sposób??

Author: mmBs, 2011-06-09

30 answers

Kiedyś zrobiłem coś takiego;

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
    Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
    return;
}
 323
Author: cvaldemar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-09 09:17:22
private boolean isEmpty(EditText etText) {
    if (etText.getText().toString().trim().length() > 0) 
        return false;

    return true;
}

Lub według audrius

  private boolean isEmpty(EditText etText) {
        return etText.getText().toString().trim().length() == 0;
    }

If funkcja return false oznacza, że edittext jest not empty i zwraca true oznacza, że edittext to empty...

 162
Author: SBJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:41

Do walidacji EditText użyj EditText#setErrormetody show error oraz do sprawdzania pustej lub zerowej wartości użyj wbudowanej klasy Androida TextUtils.isEmpty (strVar) które zwracają true, jeśli strVar ma wartość null lub zero

EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();

 if(TextUtils.isEmpty(strUserName)) {
    etUserName.setError("Your message");
    return;
 }

Obraz zaczerpnięty z wyszukiwarki Google

 127
Author: MilapTank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-20 10:34:01

Spróbuj tego:

EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}

Lub użyj klasy TextUtils w ten sposób:

if(TextUtils.isEmpty(strUserName)) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}
 33
Author: Houcine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-10 21:34:36

Za późno na imprezę, ale muszę tylko dodać własne Tekstury Androida.isEmpty (CharSequence str)

Zwraca true, jeśli łańcuch jest null lub 0-length

Więc jeśli umieścisz swoje pięć EditText na liście, Pełny kod będzie:

for(EditText edit : editTextList){
    if(TextUtils.isEmpty(edit.getText()){
        // EditText was empty
        // Do something fancy
    }
}
 26
Author: Qw4z1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-22 07:52:51

Inne odpowiedzi są poprawne, ale zrób to w krótki sposób jak

if(editText.getText().toString().isEmpty()) {
     // editText is empty
} else {
     // editText is not empty
}
 16
Author: Xar E Ahmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-08 06:21:27

Try this

TextUtils.isEmpty(editText.getText());
 8
Author: martyglaubitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 13:56:45

Możesz użyć length() z EditText.

public boolean isEditTextEmpty(EditText mInput){
   return mInput.length() == 0;
}
 7
Author: JPMagalhaes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 13:54:22

Zazwyczaj robię to, co proponuje SBJ, ale na odwrót. Po prostu łatwiej zrozumieć mój kod, sprawdzając pozytywne wyniki zamiast podwójnych negatywów. Możesz pytać o to, jak sprawdzić puste EdiTexts, ale naprawdę chcesz wiedzieć, czy ma jakąś zawartość, a nie, że nie jest pusta.

Tak:

private boolean hasContent(EditText et) {
    // Always assume false until proven otherwise
    boolean bHasContent = false; 

    if (et.getText().toString().trim().length() > 0) {
        // Got content
        bHasContent = true;
    }
    return bHasContent;
}

As SBJ wolę zwracać domyślnie "has no content" (or false), aby uniknąć wyjątków, ponieważ borked my content-check. W ten sposób będziesz mieć całkowitą pewność, że true została "zatwierdzona" przez twoje czeki.

Myślę też, że if nazywanie go też wygląda trochę czystiej:

if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}

Jest to w dużym stopniu zależne od preferencji, ale uważam, że jest to łatwiejsze do odczytania. :)

 5
Author: sigcontSE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:41

Używam tej metody, która używa trim(), aby uniknąć spacji:

EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
    Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
    return;
}

Przykład jeśli masz kilka EditText

if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
        Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
        return;
}
 4
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-21 19:27:55
if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

Możesz używać TextUtils.jest jak mój przykład ! Powodzenia

 4
Author: Erik Chau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-11 07:40:31
private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}
 3
Author: LMK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-15 04:54:00

Dlaczego po prostu nie wyłączyć przycisku, jeśli EditText jest pusty? IMHO to wygląda bardziej profesjonalnie:

        final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);  
        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
        txtFrecuencia.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            toggle.setEnabled(txtFrecuencia.length() > 0);
        }

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

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

        }
       });
 3
Author: Igor Zelaya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-21 23:18:56

Użyłem TextUtils do tego:

if (TextUtils.isEmpty(UsernameInfo.getText())) {
    validationError = true;
    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
 3
Author: wildapps,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-30 04:37:14

Możesz również sprawdzić wszystkie łańcuchy EditText w jednym warunku If: tak jak to

if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
                Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
            }
 2
Author: Mirza Awais Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-20 10:33:32

Chciałam zrobić coś podobnego. Ale pobieranie wartości tekstu z edytuj tekst i porównywanie go jak (str=="") nie działało dla mnie. Więc lepszym rozwiązaniem było:

EditText eText = (EditText) findViewById(R.id.etext);

if (etext.getText().length() == 0)
{//do what you want }
Zadziałało jak czar.
 2
Author: TheOddAbhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-08 20:00:50

Wypróbuj to z użyciem warunków If ELSE If. Możesz łatwo zweryfikować swoje pola editText.

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }
 2
Author: Sami Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-16 09:32:15

Można wywołać tę funkcję dla każdego tekstu edycji:

public boolean isEmpty(EditText editText) {
    boolean isEmptyResult = false;
    if (editText.getText().length() == 0) {
        isEmptyResult = true;
    }
    return isEmptyResult;
}
 2
Author: dreinoso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-03 15:29:55
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);

String UserID = txtUserID.getText().toString();

if (UserID.equals("")) 

{
    Log.d("value","null");
}

Zobaczysz wiadomość w LogCat....

 1
Author: Jothi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-20 06:29:59

Użyj TextUtils.isEmpty("Text here"); dla kodu jednowierszowego

 1
Author: Anand Savjani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-16 13:11:22
EditText edt=(EditText)findViewById(R.id.Edt);

String data=edt.getText().toString();

if(data=="" || data==null){

 Log.e("edit text is null?","yes");

}

else {

 Log.e("edit text is null?","no");

}

Zrób tak dla wszystkich pięciu edycji tekstu

 0
Author: Aamirkhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-15 12:35:55

"Sprawdź to jestem pewien, że ci się spodoba."

log_in.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        username=user_name.getText().toString();
        password=pass_word.getText().toString();
        if(username.equals(""))
        {
            user_name.setError("Enter username");
        }
        else if(password.equals(""))
        {
            pass_word.setError("Enter your password");
        }
        else
        {
            Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
            startActivity(intent);
        }
    }
});
 0
Author: Aris_choice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-11 08:47:55

Możesz użyć setOnFocusChangeListener, sprawdzi kiedy zmiana ostrości

        txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean arg1) {
            if (arg1) {
                //do something
            } else {
                if (txt_membername.getText().toString().length() == 0) {
                    txt_membername
                            .setError("Member name is not empty, Plz!");
                }
            }
        }
    });
 0
Author: hoang lam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-26 02:34:46
if ( (usernameEditText.getText()+"").equals("") ) { 
    // Really just another way
}
 0
Author: Sydwell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-10 12:17:41

Wolę używać wiązania listy ButterKnife , a następnie stosować akcje na liście. Na przykład, w przypadku EditTexts, mam następujące akcje niestandardowe zdefiniowane w klasie użytkowej (w tym przypadku ButterKnifeActions)

public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = true;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
    }
    return hasProperty;
}

public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = false;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
    }
    return hasProperty;
}

public interface Check<V extends View> {
    boolean checkViewProperty(V view, int index);
}

public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
    @Override
    public boolean checkViewProperty(EditText view, int index) {
        return TextUtils.isEmpty(view.getText());
    }
};

I w kodzie widoku, przywiązuję EditText do listy i stosuję akcje, gdy muszę sprawdzić widoki.

@Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
    Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}

I oczywiście ten wzorzec można rozszerzyć do sprawdzania dowolnej właściwości na dowolnej liczbie widoków. Jedynym minusem, jeśli można to tak nazwać, jest redundancją widoków. Oznacza to, że aby użyć tych EditText, trzeba będzie powiązać je z pojedynczymi zmiennymi, tak aby można było odwoływać się do nich po nazwie lub trzeba było odwoływać się do nich po pozycji na liście (edits.get(0), itd.). Osobiście, po prostu powiązać każdy z nich dwa razy, raz do jednej zmiennej i raz do listy i użyć, co jest odpowiednie.

 0
Author: Saad Farooq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 16:54:21

To editText is empty spróbuj w inny prosty sposób:

String star = editText.getText().toString();

if (star.equalsIgnoreCase("")) {
  Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}
 0
Author: Guru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-06 22:06:48

Wypróbuj to: its w Kotlinie

//button from xml
button.setOnClickListener{                                         
    val new=addText.text.toString()//addText is an EditText
    if(new=isNotEmpty())
    {
         //do something
    }
    else{
        new.setError("Enter some msg")
        //or
        Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
    }
}

Dziękuję

 0
Author: Sharmad Desai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-02 21:46:35

Następujące działa dla mnie wszystkie w jednym stwierdzeniu:

if(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

Najpierw pobieram tekst z EditText, a następnie konwertuję go na ciąg znaków, a na koniec porównuję go z "" za pomocą metody .equals.

 0
Author: Maihan Nijat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-24 00:22:46

Ta funkcja działa dla mnie

Private void checkempForm () {

    EditText[] allFields = { field1_txt, field2_txt, field3_txt, field4_txt};
    List<EditText> ErrorFields =new ArrayList<EditText>();//empty Edit text arraylist
            for(EditText edit : allFields){
                if(TextUtils.isEmpty(edit.getText())){ 

            // EditText was empty
             ErrorFields.add(edit);//add empty Edittext only in this ArayList
            for(int i = 0; i < ErrorFields.size(); i++)
            {
                EditText currentField = ErrorFields.get(i);
                currentField.setError("this field required");
                currentField.requestFocus();
            }
            }
            }
 0
Author: taha mosaad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-31 14:38:54

Za pomocą tego krótkiego kodu możesz usunąć puste miejsce na początku i końcu łańcucha. Jeśli łańcuch jest ""zwróć komunikat" Błąd " w przeciwnym razie masz ciąg

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}
 0
Author: Emiliano Spirito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-28 07:37:32