Android with sqlite database

      No Comments on Android with sqlite database

This article will cover how to use sqlite database with android. For this article I have created a demo application which is available on my github account. The app just has a list view which contains a list of products with its price. We will fetch the products from sqlite database and display it on the screen.

To get started, lets have a look at the package structure that I used in the code base.


We will start with looking at the ProductTable. The purpose of this class is to have the information about structure of product table in database.

android.provider.BaseColumns is an interface provided by android which contains nothing but two String variables. By implementing this interface your ProductTable will by default have those two columns.

Now lets take a look at our Product model. Currently its nothing but a POJO like class but it can contain the domain logic of a product.

And now we are about to discuss the most important class of this demo project.
DataBaseHelper is the class which will create the database in the device and will maintain it using versions. This class is extended from SQLiteOpenHelper which handles the core database stuff internally for us.

DataBaseHelper has mainly two methods

  1. onCreate – This method is called first time when you create the DataBaseHelper object. And you can specify what are the tables you want to create in it or any sort of database operations that you would like to do. This method gets called only once when you first install the applications. In our implementation of onCreate method, we are seeding the products in product table.
  2. onUpgrade – This method is used for updating the database and bumping up the version of database. Once you bump up the version and user upgrades the app and starts it then this method will be called.

Now lets see what we have in our MainActivity class.  In our Activity we are creating an instance of DataBaseHelper and asking it for product’s cursor.

databaseHelper.getProductCursor() – this method queries the products table and returns a cursor object which contains all the records of that table.

SimpleCursorAdapter – This is the adaptor we use when we have to directly pick the records from the database and display it in the list. It requires five arguments to create an instance of itself.

  1. Context – Application context or Activity.
  2. A Layout file, which you want use in each row of the ListView.
  3. Cursor – to load data from database.
  4. from – these are the column names where you want to get the data from.
  5. to – these are the layout elements present in the R.layout.product_row where you want to show the data of from columns.

If you want to have a look at the resource files then probably you can clone my repo or you can take a look at it on the github itself.

Leave a Reply

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