dimanche 1 novembre 2015

Sudden crash when click on CheckBoxes (NPE exception)

when I try to run this code, the app crashed from the start.

I have two checkboxes and onclick I am appending a given value to a String. Later on I am sharing this string through a SHARE Intent.

public class MainActivity extends AppCompatActivity {

Button button;
String result ="";
CheckBox checkBox1;
CheckBox checkBox2;
View.OnClickListener checkBoxListener;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    final int value1 = 300;
    final double value2 = 3.14;
    final short value3 = 5;
    final char value4 = 'A';
    checkBox1 = (CheckBox) findViewById(R.id.checkbox);
    checkBox2 = (CheckBox) findViewById(R.id.checkBox2);

    // Create StringBuilder and add four values to it.
    final StringBuilder builder = new StringBuilder();


    checkBoxListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(checkBox1.isChecked()){
                builder.append(value1).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
            if(checkBox2.isChecked()){
                builder.append(value2).append("\n");
                Toast.makeText(MainActivity.this, "item selected", Toast.LENGTH_LONG).show();
            }
        }
    };
    checkBox1.setOnClickListener(checkBoxListener);
    checkBox1.setOnClickListener(checkBoxListener);

My layout is rather simple. Only two checkboxes with the right IDs and a button to trigger the share intent. Any idea?




Aucun commentaire:

Enregistrer un commentaire