简体   繁体   中英

My App Stops When I Try To Get An Int

I'm trying to make an app that accepts an input and automatically changes it to an int. However, when it tries to obtain an int, the app automatically stops. Below is the full code...

    public class MainActivity extends Activity implements OnClickListener{  

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button calculate = (Button)findViewById(R.id.calculateTip);
            calculate.setOnClickListener(this);

        }//end onCreate

    public void onClick(View v) {

            EditText money = (EditText)findViewById(R.id.bill);
            int bill = Integer.parseInt(money.getText().toString());
            money.setText("Event Processed");

    }//end onClick

    }//end MainActivity

I suspect that the application is stopping because the value you are trying to parse is not really an integer. You should throw that code into a try catch.

ie:

    public void onClick(View v) {

       EditText money;
       try
       {
            money = (EditText)findViewById(R.id.bill);

             // This check makes sure that the EditText is returning the correct object.
            if(money != null)
            {
              int bill = Integer.parseInt(money.getText().toString());
              money.setText("Event Processed");
            }
       }
       catch(NumberFormatException e)
       {
       // If we get in here that means the inserted value was not an Integer. So do               something.
       //ie:
        money.setText("Please enter a value amount" );
        }
    }//end onClick

Regardless, you should have this code in a try catch to maintain data integrity.

Hopefully this helps! Cheers.

您确定Object是EditText的实例,并且不为null吗?

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