0

I am having a problem with this piece of code. The if statement on line 6 is being ignored during execution. I have stepped through the code at this point and the value of the variable file[position] is "subjects.dat". However, it is skipping over the steps in this and going to the related else statement. Any ideas why??

dialogButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (markComplete.isChecked()) {
                    String toDelete;
                    String[] files = fileList();
                    if (files[position] == "subjects.dat") { //the error occurs at this line
                        toDelete = files[position + 1];
                        boolean deleted = deleteFile(toDelete);
                        if (deleted) {
                            dialog.dismiss();
                        } else {
                            // Do nothing
                        }
                    } else {                            
                        toDelete = files[position];                     
                        boolean deleted = deleteFile(toDelete);
                        if (deleted) {
                            dialog.dismiss();
                        } else {
                            //Do nothing
                        }   
                    }

                }                   
            }

Thanks!

Brae
  • 484
  • 1
  • 3
  • 15

4 Answers4

6

You need to use .equals() to compare the actual value of two strings - otherwise you're checking if they're the same object.

if (files[position].equals("subjects.dat")) { 
    // do stuff
}
thegrinner
  • 11,546
  • 5
  • 41
  • 64
1

Always check String equality using equals() method. == operator cheks if two refrenece variables point to the same object.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

Strings are objects in java and when you use "==", you compare the references (pointers), which usually are different (usually because for short strings some optimization is made). Long story short, use

string.equals(anotherString)

instead of

string == anotherString
koljaTM
  • 10,064
  • 2
  • 40
  • 42
0

String - use .equals(). == will never give you true since the objects are different.

Instead of files[position] == "subjects.dat" use files[position].equals("subjects.dat")