Hello……..
This post is just a simple demonstration to show a way to store a checkbox value in a database and reload it. Here I am storing only a value of a single checkbox and reloading it. But you can make changes in the code to save the id and value of the checkbox in the database and reload the values accordingly.
For the Sqlite functions I am creating a file that has the table and the function for inserting and other manipulations.
package com.coderzheaven.pack; import java.util.Set; import java.util.Map.Entry; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class MyTable { private String TABLE_NAME = "my_table"; int DATABASE_VERSION = 1; private String _ID = "id"; private String _CHK_VALUES = "checkbox_value"; public String getTableName(){ return TABLE_NAME;} public int getDatabaseVersion() { return DATABASE_VERSION;} public String getID() { return _ID; } public String getScore() { return _CHK_VALUES; } public String getDatabaseCreateQuery() { final String DATABASE_CREATE = "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + _CHK_VALUES + " TEXT NOT NULL)"; return DATABASE_CREATE; } } class dbOperation { static String DB_TABLE ; static int DB_VERSION = 1; static String[] DATABASE_CREATE; private Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public dbOperation(Context ctx,String[] query) { this.context = ctx; DATABASE_CREATE = query; DBHelper = new DatabaseHelper(context); } public dbOperation(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } public dbOperation(String tablename) //for inner calling { DB_TABLE = tablename; DBHelper = new DatabaseHelper(context); } public dbOperation open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } public void close() { DBHelper.close(); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, "mydb.db", null, DB_VERSION); } public void onCreate(SQLiteDatabase db) { try { for (String s : DATABASE_CREATE) { db.execSQL(s); } } catch (Exception e) { System.out.println("Error creating items Per screen in the constructor" + e.getMessage()); } } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE); onCreate(db); } } public long insertTableData(String tablename,ContentValues values) throws SQLException { DB_TABLE = tablename; ContentValues initialValues2 = new ContentValues(); Set<Entry<String, Object>> s = values.valueSet(); String new_val = ""; for (Entry<String, Object> entry : s) { new_val = values.getAsString(entry.getKey()); initialValues2.put(entry.getKey(), new_val); } return db.insert(DB_TABLE, null, initialValues2); } public boolean deleteTableData(String tablename,String condition) throws SQLException { DB_TABLE = tablename; return db.delete(DB_TABLE, condition, null) > 0; } public Cursor getAllTableData(String tablename,String[] fields) throws SQLException { DB_TABLE = tablename; return db.query(DB_TABLE, fields,null, null, null, null, null); } public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException { DB_TABLE = tablename; Cursor mCursor = db.query(false, DB_TABLE, dbFields,condition, null,null,null, order, limit); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public boolean updateTable(String tablename,ContentValues args,String condition) { DB_TABLE = tablename; return db.update(DB_TABLE, args,condition , null) > 0; } public int lastInsertedID(String tablename) { int retVar=0; Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null); if (mCursor != null) { mCursor.moveToFirst(); retVar =Integer.parseInt(mCursor.getString(0)); } mCursor.close(); mCursor.deactivate(); return retVar ; } }
Noe the main java source code for implementing this.
package com.coderzheaven.pack; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; public class SaveCheckBoxDemo extends Activity { CheckBox ch; Button save, reload; int checked = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initializeDB(); save = (Button)findViewById(R.id.Button01); reload = (Button)findViewById(R.id.Button02); ch = (CheckBox)findViewById(R.id.CheckBox01); ch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ checked = 1; }else{ checked = 0; } } }); save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateTable(checked); Toast.makeText(getApplicationContext(), "Saved '"+ checked + "' in DB", Toast.LENGTH_SHORT).show(); } }); reload.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("getData(1) : " + getData(1)); Toast.makeText(getApplicationContext(), "value from DB : " + getData(1), Toast.LENGTH_SHORT).show(); if(getData(1).equalsIgnoreCase("0")) ch.setChecked(false); else ch.setChecked(true); } }); } public void initializeDB(){ MyTable user = new MyTable(); String[] tableCreateArray = { user.getDatabaseCreateQuery() }; dbOperation operation = new dbOperation(this,tableCreateArray); operation.open(); operation.close(); } /*** SAVE THE DATA IN DB - GIVE FILENAME AND DATA ***/ public void saveData(int data){ dbOperation operationObj = new dbOperation(this); operationObj.open(); MyTable Fields = new MyTable(); ContentValues initialValues = new ContentValues(); initialValues.put(Fields.getScore(), data); operationObj.insertTableData(Fields.getTableName(),initialValues); operationObj.close(); } /*** GET THE DATA FROM DB ,PARAMS - FILENAME -> GET THE DATA ***/ public String getData(int id){ String _data = ""; dbOperation operationObj = new dbOperation(this); operationObj.open(); MyTable fields = new MyTable(); String condition2 = fields.getID() + " ='" + id + "'"; String[] dbFields4 = {fields.getScore()}; Cursor cursor2 = operationObj.getTableRow(fields.getTableName(),dbFields4,condition2,fields.getID() + " ASC ","1"); if(cursor2.getCount() > 0) { cursor2.moveToFirst(); do{ _data = cursor2.getString(0); }while(cursor2.moveToNext()); }else{ _data = "error"; } cursor2.close(); cursor2.deactivate(); operationObj.close(); return _data; } /*** SAVE OR UPDATE DB -> GIVE THE FILENAME AND DATA ***/ public void updateTable(int updt_data){ dbOperation operationObj = new dbOperation(this); operationObj.open(); MyTable Fields = new MyTable(); //check for the value to update if no value then insert. String file_ = getData(1); if(file_.equals("error")){ saveData(updt_data); }else{ String condition = Fields.getID() +" = '1'"; ContentValues initialValues = new ContentValues(); initialValues.put(Fields.getScore(), updt_data); operationObj.updateTable(Fields.getTableName(),initialValues,condition); } operationObj.close(); } }
Now the xml file main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Saving CheckBox Value in database and reloading it." /> <CheckBox android:text="Coderzheaven" android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </CheckBox> <Button android:text="Save CheckBox Value in DB" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> <Button android:text="Load CheckBox Value from DB" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout>
OK Done. Here what I have done is simply saving ‘1’ if the checkbox is checked and ‘0’ if not checked.
Thank you
You are welcome.
Please keep visiting my website.
Thanks
James.
Hye. I have a question. What if I have more than 1 checkbox? How should I approach it?
you an add OnCheckListener for the other checkbox and in the callback you can save the values in the DB. Let me know if you have any issues.
Thank
James.
please help me i am new to android how to save multiple checkbox state in sqlite
Dear Maju,
The above code explains the same what you have asked. Let me know if any more help is needed?
i copied your code as it is with some slight modification in android studio. There are no errors. When i run the app it gets opened but it shows a blank page. the checkboxes and the buttons do not appear. What is the reason??
Harsh,
Have you added anything in the db to be shown in the list?
no. I didn’t. i just changed some names. thats all
ohk. now i am able to see the mainscreen. but when i click on the checkbox nothing is happening. where is the database and will i be able to see it once we submit the value?
Cool Post. I looked for this two weeks. finally i got thanks for it. But i need this concept will setup into RecyclerView i tired when i click on on checkbox remaining all are also marked let me know what the things i need to include with your code pls let me know.
Hi!
Post is very useful.
Can you write code example
if I have to save the states of more than one checkbox button ?
Hi…I have created registration form using sqlite..i used checkedbox in that….when the registration is successful, it shows registration is successful” and then again a new empty registration form,,but the checkbox still shows me “checked” instead of unchecked after inserting data…plz help me if you know
Here my code is
public void EmptyEditTextAfterDataInsert(){
Name.getText().clear();
Email.getText().clear();
Password.getText().clear();
PhoneNumber.getText().clear();
SurName.getText().clear();
DOB.getText().clear();
checkbox1.getText().clear();
}
the above code is not working for checkbox
you can call checkbox1.setChecked(false)
it still shows error………cannot resolve method setChecked(boolean);