1

I will take two numbers from user, but this number from EditText must be converted to int. I think it should be working, but I still have problem with compilation code in Android Studio.

CatLog show error in line with:

int wiek = Integer.parseInt(wiekEditText.getText().toString());

Below is my full Android code:

public class MyActivity extends ActionBarActivity {

    int Wynik; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        int Tmax, RT;
        EditText wiekEditText = (EditText) findViewById(R.id.inWiek);
        EditText tspoczEditText = (EditText) findViewById(R.id.inTspocz);
        int wiek = Integer.parseInt(wiekEditText.getText().toString());
        int tspocz = Integer.parseInt(tspoczEditText.getText().toString());

        Tmax = 220 - wiek;
        RT = Tmax - tspocz;
        Wynik = 70*RT/100 + tspocz;

        final EditText tempWiekEdit = wiekEditText;
        TabHost tabHost = (TabHost) findViewById(R.id.tabHost);   //Do TabHost'a z layoutu

        tabHost.setup();                         

        TabHost.TabSpec tabSpec = tabHost.newTabSpec("Calc");
        tabSpec.setContent(R.id.Calc);
        tabSpec.setIndicator("Calc");
        tabHost.addTab(tabSpec);

        tabSpec = tabHost.newTabSpec("Hints");                    
        tabSpec.setContent(R.id.Hints);
        tabSpec.setIndicator("Hints");
        tabHost.addTab(tabSpec);

        final Button Btn = (Button) findViewById(R.id.Btn);      
        Btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"blablabla"+ "Wynik",Toast.LENGTH_SHORT).show();
            }
        });

        wiekEditText.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) {

                Btn.setEnabled(!(tempWiekEdit.getText().toString().trim().isEmpty()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
       return super.onOptionsItemSelected(item);
    }
}
6
  • 1
    try wiekEditText.getText().toString().trim() Commented Aug 25, 2014 at 4:00
  • 2
    how sure are you that wiekEditText has inputted numbers in it? Commented Aug 25, 2014 at 4:00
  • please check if(wiekEditText.getText().toString().trim().length()>0){int wiek = Integer.parseInt(wiekEditText.getText().toString());} Commented Aug 25, 2014 at 4:04
  • +SparkOn with .trim() is this same error +Rod_Algonquin This app don't run so nobody have chance to put something different than numbers ;) Commented Aug 25, 2014 at 4:12
  • may be the input number conatains whitespace try printing the number and check it Commented Aug 25, 2014 at 4:16

4 Answers 4

3

Without looking the layout XML, and by reading the problem description that you want to take 2 numbers from user, I can only assume that those 2 EditTexts are empty when the activity is started.

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    EditText wiekEditText = (EditText) findViewById(R.id.inWiek);
    EditText tspoczEditText = (EditText) findViewById(R.id.inTspocz);

    // edit text are still empty...
    int wiek = Integer.parseInt(wiekEditText.getText().toString()); // error occurs!
    int tspocz = Integer.parseInt(tspoczEditText.getText().toString());

    ...

}

You probably want to parse the number after user interaction, perhaps by putting the code to OnClickListener, or TextWatcher

This example is using OnClickListener. The calculation will be done after user clicks the button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    // add 'final'
    final EditText wiekEditText = (EditText) findViewById(R.id.inWiek);
    final EditText tspoczEditText = (EditText) findViewById(R.id.inTspocz);

    // remove offending code

    final EditText tempWiekEdit = wiekEditText;
    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);

    ...

    final Button Btn = (Button) findViewById(R.id.Btn);      
    Btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // move the parsing code here
            int Tmax, RT;
            int wiek = Integer.parseInt(wiekEditText.getText().toString());
            int tspocz = Integer.parseInt(tspoczEditText.getText().toString());

            Tmax = 220 - wiek;
            RT = Tmax - tspocz;
            Wynik = 70*RT/100 + tspocz;

            Toast.makeText(getApplicationContext(),"blablabla"+ Wynik,Toast.LENGTH_SHORT).show();
        }
    });

    ...

}

-or-

to prevent the error, put default number for the first time by adding android:text="0" on the layout XML.

<EditText android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/inTspocz"
    android:layout_marginTop="25dp"
    android:hint="Your resting heart rate (Hint)" 
    android:text="0" />
Sign up to request clarification or add additional context in comments.

10 Comments

In XML it is like that <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="number" android:ems="10" android:id="@+id/inTspocz" android:layout_marginTop="25dp" android:hint="Your resting heart rate (Hint)" />
So I must change android:hint="something" for android:text="something"?
You can put both, hint for input hint (if the EditText is empty), and text for default text.
Ok, When I put android:text="0" on the layout XML. It's working fine But with android:text="some text" on the layout XML. I have error during compilation
If you put something other than number for text, the app will throw NumberFormatException since it tries to parse text, not a number. Refer to the updated answer for the example.
|
1

NuberFormatException can be thrown when you try to convert a String into a number, where that number might be an int, a float, or any other Java numeric type. Add the following statement check what is the output.

System.out.println(wiekEditText.getText().toString());

This might be help to identify what your string returns. There is no mistake in your wiekEditText.getText().toString().

2 Comments

I have this code in Android Studio and this error happen during compilation, not during perform some data in to input box.
that means System.out.println(wiekEditText.getText().toString()); returns the intended output?? Give your stacktrace.
0

Your input may contains white spaces in leading or trailing or both. You can try with

int wiek = Integer.parseInt(wiekEditText.getText().toString().trim());

Why trim()?

Eg:

   try {
        int num = Integer.parseInt(" 12 ");
        System.out.println(num);
    } catch (NumberFormatException e) {
        System.out.println("Error " + e.toString());
    }
    try {
        int num = Integer.parseInt(" 12 ".trim());
        System.out.println(num);
    } catch (NumberFormatException e) {
        System.out.println("Error " + e.toString());
    }

Out put:

   Error java.lang.NumberFormatException: For input string: " 12 "
   12

In this case if

   `wiekEditText.getText().toString()`

is null

You should use validation like

     int num = Integer.parseInt(wiekEditText.getText().toString()!=null
                                 ?wiekEditText.getText().toString().trim():"0");

4 Comments

@Quzziy what contains your input? is it null?
Yes I think it is null, when I put android:text="0" on the layout XML. Like Andrew T. told me. Then I dont have error in compilation. But then I have '0' in my inputbox not my text from "hint"
@Quzziy you can't convert null to int. you should use validation. check my updated answer.
I was change my code for yours, but I it's this same problem during compilation, On this moment only android:text="0" on the layout XML helps, but then I lost my text from android:hint
0

Make sure that the number you are trying to parse is not bigger than 2,147,483,647 or -2,147,483,647 which is the integer max value. So, in this case you may need to use

long varName = Long.parseLong(yourStringVar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.