Android check null or empty string in Android

前端 未结 10 1444
梦如初夏
梦如初夏 2020-12-13 12:07

In my trying AsyncTask I get email address from my server. In onPostExecute() I have to check is email address empty or null

相关标签:
10条回答
  • 2020-12-13 12:19

    My simple solution to test if a string is null:

    if (s.equals("null")){ ..... }

    There are two cases.

    The variable (of type String) is null(doesn't exists): == works.

    The variable has a null value, *.equals("null") gives te right boolean value.

    See the picture.

    0 讨论(0)
  • 2020-12-13 12:22

    All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

     String nullString = null;
     String empty = new String();
     boolean test = "".equals(empty); // true 
     System.out.println(test); 
     boolean check = "".equals(nullString); // false 
     System.out.println(check);
    
    0 讨论(0)
  • 2020-12-13 12:32

    if you check null or empty String so you can try this

    if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
        DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
    }
    
    0 讨论(0)
  • 2020-12-13 12:33

    This worked for me

    EditText   etname = (EditText) findViewById(R.id.etname);
     if(etname.length() == 0){
                        etname.setError("Required field");
                    }else{
                        Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
                    }
    

    or Use this for strings

    String DEP_DATE;
    if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
    }
    
    0 讨论(0)
  • 2020-12-13 12:36

    Checking for empty string if it is equal to null, length is zero or containing "null" string

    public static boolean isEmptyString(String text) {
            return (text == null || text.trim().equals("null") || text.trim()
                    .length() <= 0);
        }
    
    0 讨论(0)
  • 2020-12-13 12:37

    Incase all the answer given does not work, kindly try

    String myString = null;
    
    if(myString.trim().equalsIgnoreCase("null")){
        //do something
    }
    
    0 讨论(0)
提交回复
热议问题