Skip to content Skip to sidebar Skip to footer

Android App Crashes On Button Click

I have been attempting to make my first android application (a simple temperature converter) in Eclipse, but when I click the button on my phone the app crashes. Here is the full j

Solution 1:

Initialize your Buttons first then set onclicklistener to them

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //initialize views here 
    EditText mEdit = (EditText) findViewById(R.id.editText1);
    TextView myTextView = (TextView) findViewById(R.id.label);
    Button yourButton = (Button) findViewByid(R.id.youridforbutton);
    //set onclicklistener for your button
    yourbutton.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number = mEdit.getText().toString();
                number2 = Integer.parseInt(number);

                if (F = true) {
                    output = number2 * 9 / 5 + 32;
                } else {
                    output = number2 - 32 * 5 / 9;
                }

                myTextView.setText("" + output);
            }
        });

}

Similarly set the other button also


Solution 2:

You need to cast output to String

myTextView.setText(String.valueOf(output));

setText method is overloaded and when You pass an integer to it it expects it to be an id of resource.


Solution 3:

You can not set Integers to TextViews. You have to convert them into Strings.

myTextView.setText(String.valueOf(output));

Solution 4:

You need to tell the click listener to listen to a particular button. So, in other words set an OnItemClickListener on the button. Something as follows:

Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    // do the "on click" action here
  }
});

Hope this helps. If not, then please comment with further issue.


Post a Comment for "Android App Crashes On Button Click"