samedi 12 octobre 2019

CheckBox return only false even it is checked(ticked) in Android

In my app, there are 2 check boxes to get the type of the user (Eg: Student or Teacher). I know I should use a radio button instead of a check box, but my question in tutorial asked to use a checkbox(So please ignore about radio button for now).

Even I check a checkbox, isChecked() method return false.

Here is the xml

        android:id="@+id/chkTeacher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="157dp"
        android:layout_marginLeft="157dp"
        android:layout_marginTop="56dp"
        android:text="Teacher"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/regPassword" />

    <CheckBox
        android:id="@+id/chkStudent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="157dp"
        android:layout_marginLeft="157dp"
        android:layout_marginTop="20dp"
        android:text="Student"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chkTeacher" />

Here is the coding


    EditText username, password;
    CheckBox teacher, student;
    DBHelper dbHelper = new DBHelper(this);
    String type;

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

        username = findViewById(R.id.regUserName);
        password = findViewById(R.id.regPassword);
        teacher = (CheckBox) findViewById(R.id.chkTeacher);
        student = (CheckBox) findViewById(R.id.chkStudent);

        if (teacher.isChecked() == true){
            type = "teacher";
        }
        else{
            type = "student";
        }
    }

How can I fix this? Thank you for your valuable time!




Aucun commentaire:

Enregistrer un commentaire