-2

hi i'm wonder why my if always Toast me : "names Successfully saved!" i'm try every thing.

public void btnSave_Clicked(View view) {
        TextView txtOname = (TextView)findViewById(R.id.txtOname);
        TextView txtXname = (TextView)findViewById(R.id.txtXname);
        String X = txtXname.getText().toString();
        String O = txtOname.getText().toString();
        if((X!="") && (O!="")){
            DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtOname))
                    .getText().toString());
            DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtXname))
                    .getText().toString());
            Toast.makeText(this,"names Successfully saved!",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"E",Toast.LENGTH_SHORT).show();
        }
    }
}

3 Answers3

2

Strings are reference types in Java, and thus the reference of a dynamically created empty string will be different from your variables. Another option to isEmpty is equals.

if (!x.equals("") && !o.equals(")) {
    //code
}

Though I'd probably go with isEmpty

James L.
  • 12,893
  • 4
  • 49
  • 60
0

Replace your if statement with:

if (!x.isEmpty() && !o.isEmpty()) {
    //code
}

operator == compares Object reference.

.equals() compares String value.

.isEmpty() return true if String length is 0.

Alex Kamenkov
  • 891
  • 1
  • 6
  • 16
0

Strings are objects. Object instances (the value behind them) have to be compared manually with a method to assure that the content is the same.

The == operator just compares the string references ("adresses"). So when you create 2 object instances at runtime, they have different adresses even if the content is the same. Compile-time strings on the other hand are internalized, they are put into special memory and duplicates are sorted out.

System.out.println(new String("test") == new String("test"));

This will print false, because those 2 objects get created at runtime. The new keyword in the first example mandates that a new object with a new adress is created.

System.out.println("test" == "test");

This will print true, because they are String literals, which are known at runtime, you are not explicitly stating the new keyword here either. You are simply specifying that you want those literals represented in the code somehow, so the compiler internalizes them.

HopefullyHelpful
  • 1,652
  • 3
  • 21
  • 37