2017-08-25 31 views
0

我目前正在進行驗證,其中包含inputtype編號的edittext,用於顯示用戶購物車中購買的物品的數量。我想確保編輯edittext的值時,如果值爲「」,「0」或「00」等,只要它是< 1,那麼值將被設置爲「1」。帶輸入類型編號的Android EditText使文本更改的值始終> 0

我已經厭倦了下面的代碼:

 txtJumlah.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

      } 

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

      } 

      @Override 
      public void afterTextChanged(Editable s) { 
       int jumlah = Integer.parseInt(txtJumlah.getText().toString()); 
       if(txtJumlah.getText().toString().equals("") || jumlah <= 1) { 
        txtJumlah.setText("1"); 
       } 
       calculate(); 
      } 
     }); 

但它返回一個java.lang.StackOverflowError的:堆棧大小8MB

誰能幫助我?謝謝

回答

1

替換此:

if(txtJumlah.getText().toString().equals("") || jumlah <= 1) { 
    txtJumlah.setText("1"); 
} 

由:

if(txtJumlah.getText().toString().equals("") || jumlah < 1) { 
    txtJumlah.setText("1"); 
} 

上述解決方案必須解決的問題。

一個建議來優化代碼:

int jumlah = Integer.parseInt(txtJumlah.getText().toString()); 

這可能會導致ParseException(如果txtJumlah.getText().toString()是字符串,而不是數字)

+0

txtJumlah.getText()將永遠不會返回null。它將始終返回一個空字符串。唯一可能導致NullPointerException的是如果TextView爲空。即使你嘗試setText(null),它也會將它轉換爲空字符串。 – Lunkie

+0

同意,更新了答案 –

2

當您將文本設置爲「1」時,它將一次又一次地調用afterTextChanged導致無限循環。請嘗試將jumlah < 1代入您的if語句中。