2013-02-24 41 views
0

有沒有什麼方法可以預定義字符串的值,以便在任何字段爲空時不會出現錯誤? 所有porcentagem 1,2和3都是可選的,因此不要求用戶輸入一些數據,而是預先定義值以避免產生數值。初學者問題。空字段導致錯誤「意外停止」

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    cpc_inicial = (EditText) findViewById(R.id.cpc_inicial); 
    porcentagem1 = (EditText) findViewById(R.id.porcentagem1); 
    porcentagem2 = (EditText) findViewById(R.id.porcentagem2); 
    porcentagem3 = (EditText) findViewById(R.id.porcentagem3); 
    cpc_final = (TextView) findViewById(R.id.cpc_final); 
    botao1 = (Button) findViewById(R.id.botao1); 

    cpc_inicial.setInputType(InputType.TYPE_CLASS_NUMBER); 
    porcentagem1.setInputType(InputType.TYPE_CLASS_NUMBER); 
    porcentagem2.setInputType(InputType.TYPE_CLASS_NUMBER); 
    porcentagem3.setInputType(InputType.TYPE_CLASS_NUMBER); 

    botao1.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      if(porcentagem3 != null) {    

      float cpc = Float.parseFloat(cpc_inicial.getText().toString()); 
      float v1 = Float.parseFloat(porcentagem1.getText().toString()); 
      float v2 = Float.parseFloat(porcentagem2.getText().toString()); 
      float v3 = Float.parseFloat(porcentagem3.getText().toString()); 
      TextView cpcfinal = cpc_final; 

      if(cpc > 0.0 && v1 != 0.0 && v2 != 0.0 && v3 != 0.0) 
      { 
      soma = (cpc*v1/100)+cpc; 
      soma = soma*(v2/100)+soma; 
      soma = soma*(v3/100)+soma; 

      String sum = Float.toString(soma); 
      cpcfinal.setText(sum); 

      } 
      } else 
      { 
      TextView cpcfinal = cpc_final; 
      soma = 0; 
      cpcfinal.setText("ops!"); } 
     } 
    }); 
} 

感謝

回答

2

每次提交表格時,都應檢查每個字段是否有適當的值。例如,如果你想查詢天氣可選字段的值或者沒有,你應該做這樣的事情:

String optionalText = optionalFieldName.getText().toString(); 
if (optionalText.equals("some expected value")) { 
    //Do something with the value here. 
} 

當然,你需要做的每一個可選字段類似的東西,而真正應該也做了逆對於不是選項是安全的,也許是警告用戶該字段是必須的,例如字段:

String text = fieldName.getText().toString(); 
if (text.equals("")) { 
    //field is empty, so warn the user that it is required. 
} 

如果你正在尋找的值應該是自然數,那麼你應該這樣做:

String text = field.getText().toString(); 
if (!text.equals("")) { 
    //Field has at least some text in it. 
    try { 
     float val = Float.parseFloat(text); 
    }catch (NumberFormatException ex) { 
    //Enterered text was not a float value, so you should do something 
    // here to let the user know that their input was invalid and what you expect 
    } 

    //Do something with the value 
} 
+1

我編輯了我的答案以反映需要float值的場景。 – jonbonazza 2013-02-24 00:43:33

1

要麼使用android:text="..."屬性值添加到您的XML佈局或使用TextUtils.isEmpty(...)來檢測,如果字符串爲空,並指定一個默認值自己。