Search code examples
javaandroidtextview

TextView SetText


I have a problem.
In line "textView.setText(money + "$");" my program crashes.
(money is int, and textView1 is ID of my TextView)

public TextView textView;
public void onCashClick(View view) {
    money++;
    textView = (TextView) view.findViewById(R.id.textView1);
    textView.setText(money + "$");
}

Solution

  • The following line makes your app crash. Because the view sent from the click is the button, not the container. Therefore, the button doesn't contain your textview. You should be getting NullPointerException on that line. Instead, you should define textView on onCreate method:

    textView = (TextView) findViewById(R.id.textView1);
    

    and only after, onCashClick call:

    on button click.

    UPDATE: change your code to the following,

    public TextView textView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        textView = (TextView) view.findViewById(R.id.textView1);
       }
    
    public void onCashClick(View view) {
            money++;
            textView.setText(money + "$");
        }