2016-07-15 53 views
-1

我得到了這個問題,我有三個if語句,每個人都有IF String == null或String ==「」,甚至getText不給任何值,這些不會激活。if(String == null or String ==「」)not activate

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 


    switch (item.getItemId()) { 

     case R.id.action_two: 

      final String hei = h.getText().toString(); 
      final String wei = w.getText().toString(); 
      String waist = wc.getText().toString(); 


      if (hei == null || wei == null){ 
       final Animation animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein); 
       checker.setText("Please, put your information in these spots!"); 
       checker.startAnimation(animationFadeIn); 



      } 

      else if (waist == null){ 

       AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       builder.setTitle("Are you sure?"); 
       builder.setMessage("If you let Waist circumference empty, we will ask it from you later.") 
         .setCancelable(true) 
         .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 

           Intent i = new Intent(getApplicationContext(), number3.class); 
           i.putExtra("height" , hei); 
           i.putExtra("weight" , wei); 
           startActivity(i); 
           overridePendingTransition(R.anim.slide_in, R.anim.slide_out); 

          } 


         }); 
       AlertDialog alert = builder.create(); 
       alert.show(); 




      } 

      else{ 

       Log.d("BMI Height" , String.valueOf(wei)); 
       Log.d("BMI Weight" , String.valueOf(hei)); 
       Intent i = new Intent(getApplicationContext(), healthcalculator3.class); 
       i.putExtra("height" , hei); 
       i.putExtra("WC" , waist); 
       i.putExtra("weight" , wei); 
       startActivity(i); 
       overridePendingTransition(R.anim.slide_in, R.anim.slide_out); 


      } 

即使所有這些(腰,魏,HEI)爲空或不重視,它僅激活最後ELSE和機認爲他們有一些數據/值。

+0

代替==使用[this](https://docs.o racle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)) – Rashin

+0

設置hei =「」;並檢查與hei.equalsIgnoreCase(「」) –

+0

看到我更新的答案 –

回答

0

最好的辦法是用stringInstance.equals("what to compare"),因此您的代碼將是:

hei.equals("") 

您也可以使用字符串的長度:

hei.length() > 0 
+0

getLength不存在 –

+0

Ouch,錯誤。謝謝。我編輯了我的答案... – Horm

1
Try this check 

    if(!TextUtils.isEmpty(string){ 
     //body here 
    } 
+1

如何可以字符串都爲空和等於「」? – Joni

1

您也可以嘗試比較字符串這個喜歡

if (hei == null || wei == null || hei.equals("") || wei.equals("")){ 
    // your body here 
}