简体   繁体   中英

Application Crashed when trying to input on an edittext that has an TextChangedListener

I was trying to create an application that automatically calculate the percentage. the Percentage value will be shown in a TextView. The value that will be shown in the textview will be based on the inputted value of the user in an edittext.

I've finished creating my codes for this program but, it keeps crashing every time i tried to input some numbers in the edittext.

I hope you understand what am i saying. Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample__table);
    btnAdd = (Button)findViewById(R.id.btnAdd);
    //btn Function
    btnAdd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
         AddRow();
        }
    });
    //end of btn function

    //text changed
    tl = (TableLayout) findViewById(R.id.tl);
    row = new TableRow(this);
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(lp);
    fruit = new EditText(this);
    freq = new EditText(this);
    perc = new TextView(this);
    freq.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            ReCalculate();
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
    });
    //text changed end
}
private void AddRow(){

    row.addView(fruit);
    row.addView(freq);
    row.addView(perc);
    tl.addView(row);
}
private void ReCalculate(){
    float sum = 0f;
    int rows = tl.getChildCount();
    // Get the total
    for (int i = 0; i < rows; i++) {
        TableRow elem = (TableRow) tl.getChildAt(i);
        sum+= Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
    }
    // Recalculate every row percent
    for (int i = 0; i < rows; i++) {
        TableRow elem = (TableRow) tl.getChildAt(i);
        int amount​ = Integer.parseInt(((TextView)elem.getChildAt(1)).getText().toString());
        ((TextView)elem.getChildAt(1)).setText(String.valueOf(amount​/sum*100));
    }
}
}

If you want to detect your text's change, you can use onKeyListener:

    EditText edtText = (EditText)findViewById(R.id.editText);
    edtText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            Toast.makeText(MainActivity.this, "Text changed!", Toast.LENGTH_SHORT).show();
            return false;
        }
    });

it worked for me, hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM