dimanche 29 octobre 2017

How to save a checkbox state in database in android

I am trying to save a checkbox state in my database and retrieve it later but it doesn't seem to work. I get now errors in my log and am hoping some one would be able to assist.

Here is my code for my checkbox:

 <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/check1"
        android:text="test"
        android:layout_below="@+id/textViewAge"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="15dp" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/check2"
        android:text="test2"
        android:layout_below="@+id/check1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="11dp" />

Then in my CreateOrEditJobCards.java:

checkA = (CheckBox) findViewById(R.id.check1);
    checkA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            // TODO Auto-generated method stub
            if(checked)
            {
                SaveString="Yes";
            }
            else
            {
                SaveString="No";
            }
        }
    });
    checkB = (CheckBox) findViewById(R.id.check2);
    checkB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            // TODO Auto-generated method stub
            if(checked)
            {
                SaveStringA="Yes";
            }
            else
            {
                SaveStringA="No";
            }
        }
    });

......

if(personID > 0) {
        saveButton.setVisibility(View.GONE);
        buttonLayout.setVisibility(View.VISIBLE);

        Cursor rs = dbHelper.getPerson(personID);
        rs.moveToFirst();
        String personName = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_NAME));
        String personGender = rs.getString(rs.getColumnIndex(DBHelper.PERSON_COLUMN_GENDER));
        SaveString = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_A));
        SaveStringA = rs.getString(rs.getColumnIndex(DBHelper.PERSON_CHECKBOX_B));
        int personAge = rs.getInt(rs.getColumnIndex(DBHelper.PERSON_COLUMN_AGE));
        if (!rs.isClosed()) {
            rs.close();
        }

        nameEditText.setText(personName);
        nameEditText.setFocusable(false);
        nameEditText.setClickable(false);

        genderEditText.setText(personGender);
        genderEditText.setFocusable(false);
        genderEditText.setClickable(false);

        ageEditText.setText((personAge + ""));
        ageEditText.setFocusable(false);
        ageEditText.setClickable(false);

        checkA.setChecked(Boolean.parseBoolean(String.valueOf(SaveString)));
        checkA.setFocusable(false);
        checkA.setClickable(false);

        checkB.setChecked(Boolean.parseBoolean(String.valueOf(SaveStringA)));
        checkB.setFocusable(false);
        checkB.setClickable(false);
    }
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.saveButton:
            persistPerson();
            return;
        case R.id.editButton:
            saveButton.setVisibility(View.VISIBLE);
            buttonLayout.setVisibility(View.GONE);
            nameEditText.setEnabled(true);
            nameEditText.setFocusableInTouchMode(true);
            nameEditText.setClickable(true);

            genderEditText.setEnabled(true);
            genderEditText.setFocusableInTouchMode(true);
            genderEditText.setClickable(true);

            ageEditText.setEnabled(true);
            ageEditText.setFocusableInTouchMode(true);
            ageEditText.setClickable(true);

            checkA.setEnabled(true);
            checkA.setFocusableInTouchMode(true);
            checkA.setClickable(true);

            checkB.setEnabled(true);
            checkB.setFocusableInTouchMode(true);
            checkB.setClickable(true);


            return;
        case R.id.deleteButton:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.deletePerson)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dbHelper.deletePerson(personID);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Delete Job Card?");
            d.show();
            return;
    }
}

public void persistPerson() {
    if(personID > 0) {
        if(dbHelper.updatePerson(personID,
                nameEditText.getText().toString(),
                genderEditText.getText().toString(),
                checkA.getText().toString(),
                checkB.getText().toString(),

                Integer.parseInt(ageEditText.getText().toString()))) {

            Toast.makeText(getApplicationContext(), "Job Card Update Successful", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        else {
            Toast.makeText(getApplicationContext(), "Job Card Update Failed", Toast.LENGTH_SHORT).show();
        }
    }
    else {
        if(dbHelper.insertPerson(nameEditText.getText().toString(),
                genderEditText.getText().toString(),
                checkA.getText().toString(),
                checkB.getText().toString(),

                Integer.parseInt(ageEditText.getText().toString()))) {
            Toast.makeText(getApplicationContext(), "Job Card Inserted", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Could not Insert Job Card", Toast.LENGTH_SHORT).show();
        }
        Intent intent = new Intent(getApplicationContext(), JobCardMainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
}
}

And in my DBHelper.java

public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_GENDER = "gender";
public static final String PERSON_COLUMN_AGE = "age";
public static final String PERSON_CHECKBOX_A = "checka";
public static final String PERSON_CHECKBOX_B = "checkb";

public DBHelper(Context context) {
    super(context, DATABASE_NAME , null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "CREATE TABLE " + PERSON_TABLE_NAME +
                    "(" + PERSON_COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    PERSON_COLUMN_NAME + " TEXT, " +
                    PERSON_COLUMN_GENDER + " TEXT, " +
                    PERSON_CHECKBOX_A + " TEXT, " +
                    PERSON_CHECKBOX_B + " TEXT, " +
                    PERSON_COLUMN_AGE + " INTEGER)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);
    onCreate(db);
}

public boolean insertPerson(String name,
                            String gender,
                            String checka,
                            String checkb,
                            int age) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);
    contentValues.put(PERSON_CHECKBOX_A, checka);
    contentValues.put(PERSON_CHECKBOX_B, checkb);

    db.insert(PERSON_TABLE_NAME, null, contentValues);
    return true;
}

public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PERSON_TABLE_NAME);
    return numRows;
}

public boolean updatePerson(Integer id,
                            String name,
                            String gender,
                            String checka,
                            String checkb,
                            int age) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(PERSON_COLUMN_NAME, name);
    contentValues.put(PERSON_COLUMN_GENDER, gender);
    contentValues.put(PERSON_COLUMN_AGE, age);
    contentValues.put(PERSON_CHECKBOX_A, checka);
    contentValues.put(PERSON_CHECKBOX_B, checkb);
    db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deletePerson(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(PERSON_TABLE_NAME,
            PERSON_COLUMN_ID + " = ? ",
            new String[] { Integer.toString(id) });
}

public Cursor getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("SELECT * FROM " + PERSON_TABLE_NAME + " WHERE " +
            PERSON_COLUMN_ID + "=?", new String[]{Integer.toString(id)});
    return res;
}

public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM " + PERSON_TABLE_NAME, null );
    return res;
}
}

Basically in this app the user would select "add new jobcard" then would fill in the form and hit save. This then is displayed in a list view in number order. When the user would then select the form created earlier they can then hit send and it will then email the form (I am still working on that and code is not in above)

However like I said earlier, everything else in the form works and saves but can't seem to get the checkbox to save the state it was checked

Could some one please have a look at mu code and point out where I have gone wrong and assist?

Thanks




Aucun commentaire:

Enregistrer un commentaire