I am trying to get a TextView object using view.findViewById() in a function which is called when a button is clicked. In the onClickButton() null is returned whereas in other function setDefaultValues() it works fine.
Activity1.java
public class Activity1 extends AppCompatActivity {
private final Double TIP = 10.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
setDefaultValues();
}
private void setDefaultValues() {
TextView tipView = findViewById(R.id.tipView);
tipView.setText(getString(R.string.main_msg_tip,Double.toString(TIP)));
}
public void onClickToggleButton(View view){
TextView tipView = view.findViewById(R.id.tipView);
switch (view.getId()) {
case (R.id.toggleButtonBad):
tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
break;
}
}
When testing the app the following error message was shown:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object referenceat com.example.chandan.learning.Activity1.onClickToggleButton
Edit : The activity_1.xml
file does contain the TextView
with tipView
id so the theory that element is not present in the XML file is out of the window.