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.

 

12 Comments

  1. sahar April 22, 2017 at 10:43 pm

    Thank you

     
    • James April 30, 2017 at 6:56 am

      You are welcome.
      Please keep visiting my website.

      Thanks
      James.

       
  2. Adam May 9, 2017 at 7:47 am

    Hye. I have a question. What if I have more than 1 checkbox? How should I approach it?

     
    • James May 10, 2017 at 6:16 am

      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.

       
      • maju February 6, 2018 at 6:18 pm

        please help me i am new to android how to save multiple checkbox state in sqlite

         
        • James February 18, 2018 at 8:18 pm

          Dear Maju,

          The above code explains the same what you have asked. Let me know if any more help is needed?

           
  3. harsh vardhan May 30, 2017 at 6:05 am

    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??

     
    • James May 31, 2017 at 5:03 pm

      Harsh,

      Have you added anything in the db to be shown in the list?

       
      • harsh vardhan June 18, 2017 at 7:22 am

        no. I didn’t. i just changed some names. thats all

         
        • harsh vardhan June 19, 2017 at 10:34 am

          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?

           
  4. Viswa October 9, 2017 at 7:57 am

    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.

     
  5. AKSHAY SATPUTE February 3, 2018 at 2:00 am

    Hi!
    Post is very useful.
    Can you write code example
    if I have to save the states of more than one checkbox button ?

     

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.