Anindya Roy Anindya Roy - 22 days ago 6
Android Question

cannot understand why the app crashes when the following code is run

Below is the code for mainactivity for a calculator app. During debug a message pops up saying "Unfortunately the app has stopped". Can anyone help me with this? plzzz cannot figue out the reason
MainActivity

package com.example.anindyaroy.calculator;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

EditText First = (EditText)findViewById(R.id.FirstNum);
EditText Second = (EditText)findViewById(R.id.SecondNum);
EditText Operator = (EditText)findViewById(R.id.Operater);
Button b = (Button)findViewById(R.id.button);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(this);
}
public void onClick(View view)
{
TextView value= (TextView)findViewById(R.id.Value);
double first = Double.parseDouble(First.getText().toString());
double second = Double.parseDouble(Second.getText().toString());
String operator = Operator.getText().toString();
char c = operator.charAt(0);
double result=0.0;
switch(c)
{
case '+':
result = first+second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first/second;
break;
case '%':
result = first%second;
break;
default:
value.setText("Invalid");
}
value.setText(String.valueOf(result));
}
}

Answer

You need to call functions findViewById(R.id.your_view) inside onCreate() method after setContentView(R.layout.your_layout) function call.

You need to do this because findViewById(R.id.your_view) expects to be called when view is created by activity in order to successfully find views that you need.