-2

I am working on an app that takes in input from the user and adds it to a list view in android.

i decided I wanted to make a control to keep the user from adding empty strings to the list, as it would clutter the screen uselessly. I wrote this code for that.

    public void addClaims(View v){
    ClaimListController ct = new ClaimListController();
    EditText textView = (EditText) findViewById(R.id.add_claim_field);
    String added = textView.getText().toString();

    if (added != ""){
        final String t = format("added",added);
        ct.addClaim(new Claim(added));
        Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
        textView.setText("");
        //Intent intent = new Intent(MainActivity.this, AddClaim.class);
        //startActivity(intent);
    }else{
        Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
    }
}
private String format(String string, String added) {
    String formats = string +" "+ added; 
    return formats;
}

however, the if(){} loop is never checked. I tried changing the empty string to "test" and adding test in the app, and it still worked. what is causing the code to NOT check the IF and ELSE conditions?

I am not asking how to compare strings. I am asking why this problem is occurring. it did not occur to me that it was a string comparison issue.

app_maker
  • 29
  • 8

2 Answers2

1

The if condition you are using will not return true. Use this instead:

if (!TextUtils.isEmpty(added))
Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
0

When you use the != operator on any kind of object you compare the references and since you create a new instance in the if-statement the references will always be different.

You can use this instead if(added.equals(""))