-3

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.

Chandan Mahto
  • 147
  • 1
  • 13

2 Answers2

2

It is a bad practice to duplicate code. Now you have duplication of method findViewById. To avoid that, you should create a global variable in the class Activity1. That will also be solution of your problem:

public class Activity1 extends AppCompatActivity {
    private final Double TIP = 10.0;
    private TextView tipView;

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

    private void setDefaultValues() {
        tipView = findViewById(R.id.tipView);
        tipView.setText(getString(R.string.main_msg_tip, Double.toString(TIP)));
    }

    public void onClickToggleButton(View view) {
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
                tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
                break;
        }
    }
}
samaromku
  • 560
  • 2
  • 7
0

You are trying to find view from inside clicked view (Ex. Button), while the "tipView" is in main view container. So update your method "onClickToggleButton" as below:

    public void onClickToggleButton(View view) {
        TextView tipView = findViewById(R.id.tipView);
        switch (view.getId()) {
            case (R.id.toggleButtonBad):
             tipView.setText(getString(R.string.main_msg_tip, Double.toString(BAD)));
            break;
        }
    }
DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27