Reputation: 77
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 + "$");
}
Upvotes: 0
Views: 3764
Reputation: 792
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 + "$");
}
Upvotes: 2
Reputation: 3252
Simply remove view
that is before findViewByID to be like this
textView = (TextView) findViewById(R.id.textView1);
Upvotes: 0
Reputation: 4143
Cause the view you are using for binding the text view is the clicked button, instead of using view.findViewById() if your are in a activity just use findViewById and if your are in a fragment use your rootView.
Upvotes: 0