Search code examples
javaandroidstringinteger

Issues converting int into string (resource errror)


trying to take user inputs and use that to do calculations. However from what I can understand, I didn't properly convert my int into a string so it's trying to find a resource id for the int. How would i go about fixing this?

public void calculateAndDisplay() {

        editNumString = editNumText.getText().toString();
        float num; //this num is causing the issue
        if (editNumString.equals("")){
            num = 0;
        } else {
            num = Float.parseFloat(String.valueOf(editNumString));
        }

        float unitResult = 0;
        if (unitSelect.getSelectedItem().toString().trim().equals("Miles to Kilometers")) {
            unitResult = (float) (num * 1.6093);

        } else if (unitSelect.getSelectedItem().toString().trim().equals("Kilometers to Miles")) {
            unitResult = (float) (num * 0.6214);

        } else if (unitSelect.getSelectedItem().toString().trim().equals("Inches to Centimeters")) {
            unitResult = (float) (num * 2.54);

        } else if (unitSelect.getSelectedItem().toString().trim().equals("Centimeters to Inches")) {
            unitResult = (float) (num * 0.3937);
        }
        unitResultView.setText((int) unitResult);
    }

//below is the tldr error
android.content.res.Resources$NotFoundException: String resource ID #0x0

I tried initializing num=0, setText, and String.valueOf. One of these is probably correct and I implemented it wrong.


Solution

  • The error is caused by this code

    unitResultView.setText((int) unitResult);
    

    Android interprets this integer value as a resource ID, which is causing the error. To fix it, you should convert the integer to a string before setting it on the text view.

    unitResultView.setText(String.valueOf((int) unitResult));