2013-04-07 69 views
1

我想將EditText轉換爲float。我這樣做:將EditText轉換爲浮動 - android eclipse

EditText edt = (EditText) findViewById(R.id.price); 
float number = Float.valueOf(edt.getText().toString()); 

該應用程序不加載在我的設備和模擬器。在他們兩人寫:

"the application has stopped unexpectedly. please try again." 

如果我刪除此行:

float number = Float.valueOf(edt.getText().toString()); 

應用程序可以加載。

我該怎麼做?

回答

2

我的猜測是edt.getText().toString()沒有返回可以變成浮點數的值。嘗試把周圍的代碼

`

float number = 0; 
try{ 
    number = Float.valueOf(edt.getText().toString()); 
} catch (NumberFormatException e) { 
    e.printStackTrace(); 
} 

` 這應該給你一個線索,爲什麼它的凋零以下。

+0

其工作感謝 – user2254968 2013-04-07 17:13:11

0

如果EditText中沒有Number,則無法將其轉換爲浮點數,您將獲得NumberFormatException

因此,圍繞Float.valueOf方法添加一個try-catch。

0

您的應用崩潰的可能性很大,因爲您嘗試在應用剛剛啓動時將EditText的內容轉換爲浮動。此時,EditText可能爲空,或者填充了在佈局文件中設置的一些默認文本,這可能會導致NullPointerExceptionNumberFormatException

嘗試在TextWatcher獲取浮點值:

edt.addTextChangedListener(new TextWatcher() { 

    @Override 
    public void afterTextChanged(Editable s) { 
     // TODO Auto-generated method stub 
     float number = Float.valueOf(edt.getText().toString()); 
    } 

    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 

    } 

}); 
0

您正在試圖讓應用程序打開右後EditText的價值,這意味着沒有什麼進入,應用程序拋出一個NumberFormatException

只有當您確定輸入了某些內容時,例如在事件Button中,您才應該獲得在EditText中輸入的值。

0

edt必須包含文本,並且文本中的每個字符必須是數字或小數點。尤其要注意的是,空字符串「」不代表0.它不能被解釋爲浮點值,因此會導致異常。只有「0」,「0.0」等可以解釋爲零。

您應該在得到該值之前測試edt的值,並且應該正確測試catchException。您還應該將inputTypeedt設置爲十進制。

0
EditText edt = (EditText) findViewById(R.id.price); 
float number= Float.parseFloat(edt.getText().toString());