Search code examples
androidonclickcrash

onClick method error & App crashes when I press the button


I have a simple app to increase and decrease a number with button press. but unfortunately my app crashes when I press the button. Here is the MainActivity.java code :

package com.example.sparker.asafool;

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

int quantity = 1;

public void decrement(View view) {
    quantity = quantity - 1;
    displayIt(quantity);
}

public void increment(View view) {
    quantity = quantity + 1;
    displayIt(quantity);
}

public void displayIt(int xyz){
    TextView quantityTextView = (TextView)findViewById(R.id.textView);
    quantityTextView.setText(xyz);
}

}

decrement and increment methods are in the xml file.

Here is the logcat:

Here is the logcat:


Solution

  • Eventually you have to convert int into String. You can't set integer on TextView. As from the logs you can see, here O.S. thinking you passed resource id of String resource which never found and it throw ResourceNotFoundException.

    public void displayIt(int xyz) {
     TextView quantityTextView = (TextView)findViewById(R.id.textView);
     quantityTextView.setText(""+ xyz); // convert into String
    }