Search code examples
androidonclicklistenervariable-length

How to get the length of an integer in Java (Android)


So if I had the value 1234 the output should be 4.

I've written the following code, but don't know what I did wrong. This is an App, that adds two numbers. So I've got two EditTextfields. But if an EditTextfield is left blank, the App crashes. So I thought of assigning the value of 0 to an EditTextfield, that has been left blank, because it (should) have a character length of 0.

That should get the right results:

Example, if EditTextfield "firstnumET" holds a value of 5 and "secondnumET" is left blank:

5 + 0 = 5

The problem might be


private int firstnum;
private int secondnum;
private int total;


EditText firstnumET;
EditText secondnumET;
TextView ansTV;
Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cal2_numbers);


    firstnumET = (EditText) findViewById(R.id.edittxt1);
    secondnumET = (EditText) findViewById(R.id.edittxt2);
    ansTV = (TextView) findViewById(R.id.ans);
    button = (Button) findViewById(R.id.btn);


    button.setOnClickListener(new ClickButton());



}

    private class ClickButton implements Button.OnClickListener {

    @Override
    public void onClick(View v) {


        firstnum = Integer.parseInt(firstnumET.getText().toString());
        secondnum = Integer.parseInt(secondnumET.getText().toString());

        int cache1 = Integer.toString(firstnum).length();
        int cache2 = Integer.toString(secondnum).length();
        if (cache1 == 0) {
            ansTV.setText(Integer.toString(secondnum));
        }
        if (cache2 == 0) {
            ansTV.setText(Integer.toString(firstnum));
        }



        total = firstnum + secondnum;

        ansTV.setText(Integer.toString(total));
    }
}


Solution

  • Too long for a comment, why don't you check your strings and then set them based on their length if they aren't empty.

    String firstString = firstnumET.getText().toString();
    firstNum = (firstString.trim().equals(""))? 0: firstString.length();
    
    String secondString = secondnumET.getText().toString();
    secondNum = (secondString.trim().equals(""))? 0: secondString.length();
    
    ansTV.setText(Integer.toString(firstNum + secondNum));
    

    You could obviously make it more complex than that, checking to make sure the string contains only numerical values so that you make sure you aren't getting the length of a non-numeric string.

    String.trim removes white space, this helps avoid an edit text filled with spaces.