2015-07-12 20 views
-1

我只是開發android應用程序的初學者。 我有我的.java文件中的這段代碼。我所需要的是,如果EditText字段1或2爲空,則使用Toast消息彈出,否則將顯示result.setText()。但是,當我試圖模擬這一點,並且一個或兩個EditText字段爲空時,程序崩潰並停止。請幫忙!謝謝 !如何在開發android應用程序時檢查編輯文本的內容

EditText height = (EditText)findViewById(R.id.editText1); 
    EditText weight = (EditText)findViewById(R.id.editText2); 
    EditText result = (EditText)findViewById(R.id.editText3); 

    if(height.getText().toString()== "" || weight.getText().toString()==""){ 
      Toast.makeText(this, "Error! Height or Weight is empty! ",Toast.LENGTH_SHORT).show(); 
}else{ 
    result.setText("Accepted."); 
} 
+0

做'如果(TextUtils.isEmpty(height.getText()的toString()));' –

+0

郵政錯誤 – Psypher

+0

的日誌語法沒有錯誤,這是當我嘗試運行在模擬器中的代碼,當它們中的任何一個都是空的時候,只是說「不幸的是,程序已經停止。」 –

回答

0
EditText heightEditText = (EditText)findViewById(R.id.editText1); 
height = heightEditText.getText().toString(); 
if (height.matches("") || TextUtils.isEmpty(height)) { 
    Toast.makeText(this, "Error! Height or Weight is empty!", Toast.LENGTH_SHORT).show(); 
    return; 
} 
+0

我試過這個,但發生了同樣的事情。「不幸的是,該程序已停止。」 –

0

試試這個。

if (height.getText().toString().trim().length() == 0) 
    { 
    Toast.makeText(MainActivity.this, "Please enter height", Toast.LENGTH_LONG).show(); 
    } 
    else if (weight.getText().toString().trim().length() == 0) {    
    Toast.makeText(MainActivity.this, "Please enter height", Toast.LENGTH_LONG).show(); 
    } 
    else { 
    result.setText("Accepted."); 
} 
相關問題