How can I replace "String.isEmpty()" in Java?

Asked

Viewed 602 times

5

I got the following:

    data = new Json().execute(URL).get();

    System.out.println(data);

    if (!data.isEmpty()) { //erro neste data.isEmpty

I have a mistake:

has an error: Call requires API level 9 (Current min is 8): java.lang.String#isEmpty

4 answers

7


The easiest way to know if a string is empty is checking if its size is zero, which is what Java does in the method isEmpty() in standard Java, so you can also do this:

if (data.length() != 0)
  • Android Apis below 9 have this limitation even, they do not implement the isEmpty(), I’m not sure why.

  • @Piovezan had not even thought it could be Android. Still it’s crazy, because it exists since the 6.

7

  • There is a difference between "Empty" string ( empty string) and "Blank string" (I don’t know a good translation, but it would be a string composed of space characters). Thus "".isEmpty() == true, but " ".isEmpty() == false. Using trim() you can turn a Blank string into an Empty string by entering an error.

3

Whereas date is a String you can do so:

      if(!"".equals(data))      
  • You’d have to do at least one data.trim(). If data for " " (have a space) your checking will not work.

  • 2

    @In fact this answer is more certain than that of Felipe (in fact error of Ascorbin in the OS), at least in part of it, after all if it gives a trim() is because the string had a space and was not empty.

  • 1

    Another reason for this to be more advised is that it will never give nullpointer.

0

It may be so:

if (str.equals("") { //commands here }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.