Search code examples
javaandroidnumberformatexception

Format exeption errors


I have 2 activities. Activity A sends a Number to activity B and activity recieves and uses the Number. The problem is that activity B produces FormatExeption errors.

Activty A code:

EditText set_limit = findViewById(R.id.editText2);
Bundle set_limit_basic = new Bundle();
set_limit_basic.putString("limit_basic", String.valueOf(set_limit));
Intent Aintent = new Intent(A.this, B.class);
Aintent.putExtras(set_limit_basic);
startActivity(Aintent);

Activity B code:

Bundle set_limit_basic = getIntent().getExtras();
if (set_limit_basic != null) {
        String B_string = set_limit_basic.getString("limit_basic");
        if ( B_string .trim().length() == 0){
        limit_number = Integer.parseInt(B_string);

Solution

  • Several points:

    1. You shouldn't be converting set_limit to a string; set_limit is an EditText widget. Instead, you should be putting the contents of the view (the text it is displaying).
    2. There's no reason to explicitly construct your own extras bundle. Just use one of the putExtra methods defined in the Intent class.
    3. The error checking is probably better handled in activity A instead of activity B.
    4. You seem to have a logic error in activity B, in that you are only attempting to parse the limit number when the trimmed text is empty. That seems backwards.

    Putting all this together, I'd rewrite your code as follows:

    Activity A:

    EditText set_limit = findViewById(R.id.editText2);
    CharSequence text = set_limit.getText();
    if (TextUtils.isEmpty(text)) {
        // handle case of no text
    } else {
        try {
            int limit_number = Integer.parseInt(text.toString());
            Intent intent = new Intent(A.this, B.class);
            intent.putExtra("limit_basic", limit_number);
            startActivity(intent);
        } catch (NumberFormatException e) {
            // handle case of improperly formatted text
        }
    }
    

    Activity B:

    limit_number = getIntExtra("limit_basic", -1 /* or other default value */);
    
    // or, if you want to explicitly check for presence of the extra:
    if (hasExtra("limit_basic")) {
        limit_number = getIntExtra("limit_basic", -1);
    }