2014-02-06 37 views
0

我正在將我的金額文本從EditText轉換爲雙格式,並試圖刪除EditText中的",",以便爲我的計算執行適當的格式。我的代碼有什麼問題,並有堆棧溢出?EditText中的TextWatcher觀察器中的StackOverflow錯誤

// Gets the two EditText controls' Editable values 

String cleanBasicTax; 
if(txtBasicTax.getText().toString().contains(",")){ 
    cleanBasicTax=txtBasicTax.getText().toString().replace(",", ""); 
} 
else{ 
    cleanBasicTax=txtBasicTax.getText().toString(); 
} 

String cleantxtSurcharge; 
if(txtSurcharge.getText().toString().contains(",")){ 
    cleantxtSurcharge=txtSurcharge.getText().toString().replace(",", ""); 
} 
else{ 
    cleantxtSurcharge=txtSurcharge.getText().toString(); 
} 

String cleanInterest; 
if(txtInterest.getText().toString().contains(",")){ 
    cleanInterest=txtInterest.getText().toString().replace(",", ""); 
} 
else{ 
    cleanInterest=txtInterest.getText().toString(); 
} 

String cleanCompromise=txtCompromise.getText().toString().replace(",", ""); 
if(txtCompromise.getText().toString().contains(",")){ 
    cleanCompromise=txtCompromise.getText().toString().replace(",", ""); 
} 
else{ 
    cleanCompromise=txtCompromise.getText().toString(); 
}   

Editable editableValueBasicTax = txtBasicTax.getText().replace(0, txtBasicTax.length(), cleanBasicTax), 
    editableValueSurcharge = txtSurcharge.getText().replace(0, txtSurcharge.length(), cleantxtSurcharge), 
    editableValueInterest = txtInterest.getText().replace(0, txtInterest.length(), cleanInterest), 
    editableValueCompromise = txtCompromise.getText().replace(0, txtCompromise.length(), cleanCompromise); 
+0

不知道爲什麼會發生stackoverflow,但此代碼需要審查肯定。爲什麼不聲明'final String comma =「,」;最後一個字符串爲空=「」;'和'字符串cleanBasicTax = txtBasicTax.getText().toString();''if(cleanBasicTax.contains(comma)){cleanBasicTax = cleanBasicTax.replace(comma,empty); } else {..}'等等.. –

回答

4

您的TextWathcer更改了它正在監視的文本,導致對觀察者的另一個調用,導致文本的另一個改變......等等,直到您用完堆棧空間調用方法。

解決此問題的一種方法是在觀察器內部運行時將boolean標誌設置爲true,並且如果該標誌設置爲終止遞歸,則立即返回。在僞代碼:

boolean mIsInWatcher = false; 

void onTextChanged(...) { 
    if (mIsInWatcher) return; 
    mIsInWatcher = true; 

    // text modifications here 

    mIsInWatcher = false; 
} 
+0

我很困惑我打電話給我的計算afterTextChanged ..你的意思是我需要將其轉移到onTextChanged ..? – DreamBigAlvin

+0

@DreamBigAlvin我改變我的代碼onTextChanged(),沒有什麼是me..I如此不同覺得取決於你的代碼,哥們.. – lynndragon

+0

@laalto曾爲perfectly..Thz ..Take +1解決我的錯誤: )我試圖找到關於該錯誤很長一段時間的stackoverflow主題,但我找不到解決方案..現在,我終於找到解決方案..真的謝謝.. – lynndragon

2

如果要調用一個TextView onTextChangeListener,並在同樣的方法替換文本,你只需進入一個循環,因爲更換將調用相同的方法。因此錯誤。

請嘗試替換其他地方的文本。