Unexpected response when capturing text from a Textview

Asked

Viewed 98 times

2

I have to test a certain Textview to see if it is filled in the onCreate() of Activity and if it is filled, I have to change the image of an Imagebutton. I’m using the following code for this:

if (txt_photo_path.getText().toString() != null) {
        btnenviarfoto.setImageResource(R.drawable.enviarfotochecked);
        }

However, the code is always running. I decided to test to see why Textview is always filled, using the following, inside if:

Log.w("txt_photo_path", txt_photo_path.getText().toString()); 

What I get in my log is below

09-05 12:56:53.161  14726-14726/com.ufscar.ufscar.df100fogo W/txt_photo_path﹕ [ 09-05 12:56:53.381   576:  591 I/ActivityManager ]

Why is this happening? How to know if Textview is really empty or not?

  • 2

    txt_photo_path.getText().toString() != "" by default the TextView is always filled with the empty string "".

  • 3

    txt_photo_path.getText().toString().isEmpty() or txt_photo_path.getText().toString().length() == 0 or txt_photo_path.getText().toString().equals("") is better, never use comparator == with String, take care of the difference between String in the String Pool and instances thereof.

  • @Walkim is right, I forgot .equals(""). then you can use it like this: if (!txt_photo_path.getText().toString().equals("")) { with the exclamation mark on the back that means NOT equals.

  • 1

    I used (!txt_photo_path.getText().toString().isEmpty()) and it worked. Thank you all.

  • @Wakim formulates an answer!

1 answer

1


Apparently Textview is always filled with an empty string (""). Just swap

if (txt_photo_path.getText().toString() != null)

for

if (!txt_photo_path.getText().toString().isEmpty())

that worked perfectly.

Browser other questions tagged

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