2015-01-21 101 views
-2

我正在從一個應用程序接受來自用戶的輸入並將其添加到android中的列表視圖。爲什麼我的代碼的這部分不遵循循環?

我決定要製作一個控件,讓用戶不用將空字符串添加到列表中,因爲它會使屏幕無用地混亂。我爲此編寫了這個代碼。

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; 
} 

但是,從不檢查if(){}循環。我嘗試將空字符串更改爲「測試」並在應用程序中添加測試,但仍然有效。什麼導致代碼不檢查IFELSE條件?

我不問如何比較字符串。我在問爲什麼會出現這個問題。它不是我想它是一個字符串比較問題。

+0

你也可以檢查它的長度,即textView.getText()。長度> 0 – Pavya 2015-01-21 03:53:31

回答

1

您使用的if條件不會返回true。使用這個代替:

if (!TextUtils.isEmpty(added)) 
+0

感謝這個工作。 – 2015-01-24 02:30:32

0

當您使用=操作上的任何類型的對象你比較引用因爲你在if語句創建一個新實例的引用將永遠是不同的。

你可以用這個來代替 if(added.equals(""))