Question

I have problem with simple activty below. I have a global variable which defines state of my checkbox in this activty. If variable = 0 then the checkbox is not checked else if it is = 1 then the checkbox is checked. When i launch activity it the checkbox state should be checked or not depending on value of that global variable. The problem is here:

if(o == 1){
       on.setChecked(true);
       czas.setEnabled(true);               
}

without on.setChecked(true) everything works fine. But when it comes to set checkbox true at the start of activity it crash the app.

Code of Activity:

public class Ustawienia extends Activity {

SeekBar czas;
CheckBox on;
EditText sekundy;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ustawienia);
        final Globalne globalVariable = (Globalne) getApplicationContext();
        sekundy = (EditText) findViewById(R.id.editText1);
        sekundy.setText("0");
        czas = (SeekBar) findViewById(R.id.seekBar1);
        int o = globalVariable.getOdswiez();            

        if(o == 1){
            on.setChecked(true);
            czas.setEnabled(true);              
        }

        czas.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                sekundy.setText(Integer.toString(progress));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }
        });
        on = (CheckBox) findViewById(R.id.checkBox1);
        on.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if ( isChecked ){
                    czas.setEnabled(true);
                    globalVariable.setOdswiez(1);
                }else{
                    czas.setEnabled(false);
                    globalVariable.setOdswiez(0);

                }

            }
        });



 } 

}

Was it helpful?

Solution

Need to initialize this

on = (CheckBox) findViewById(R.id.checkBox1);

on above

if(o == 1){
      on.setChecked(true);
      czas.setEnabled(true);              
}

Your view is not initialized and your are going to mark as checked so there is nullpointerexception occured.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top