简体   繁体   中英

Subtraction App Java

Hi I'm a college student and I'm struggling with an app I have to make. The app is a subtraction app and I can't seem to get it to work. Every time I press the subtraction button it crashes.

My code:

public void onClick(View view){

    switch (view.getId()) {
        case R.id.subtract_button:

            setContentView(R.layout.activity_main);

            EditText firstNumber = (EditText) findViewById(R.id.input_box_1);
            int num1 = Integer.parseInt(firstNumber.getText().toString());

            EditText secondNumber = (EditText) findViewById(R.id.input_box_2);
            int num2 = Integer.parseInt(secondNumber.getText().toString());

            int result = num1 - num2;

            setContentView(R.layout.activity_result);

            TextView subResult = (TextView)findViewById(R.id.result_view);
            subResult.setText(Integer.toString(result));

            break;

        case R.id.exit_button: // the 'exit' button has been pressed.
            // Delay the exit by 1 second at this time!
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //Finish the app
                    finish();
                }
            }, 1000);
            break; // End of case.

    }
}

At First Post your Logcat

  1. Problem for your wrong setContentView placing .

  2. Why multiple setContentView ?? Must be One .

Don't

switch (view.getId()) {
    case R.id.subtract_button:

        setContentView(R.layout.activity_main); // Problem here i guess

Do

  1. setContentView call in your onCreate(Bundle savedInstanceState) section.

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_activity_name);

I thought you missed button declaration check it

Button button;
button=(Button) findViewById(R.id.buttonid);

or else post ur log

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