Android SQLite Database Example

Android Tutorial For Beginners : Android SQLite Database Example Tutorial

In many occasions you will need a way to maintain your application data, which can be later accessed or altered. In that situation you possibly can make use of SQLiteDatabase in your application. Lets check out this in this Android SQLite Database Example of Android Tutorial For Beginners Series.

Take a Look at this Advanced Tutorial on Android SQLite Database using Custom Cursor Adapter ListView

Contact List View

Android SQLite Database : Why SQLite for Android?

  • SQLite is really a quick and compact android database technology which incorporates SQL syntax to create queries and also handle data.
  • Android SDK by itself provides the SQLite support which without doubt making the setup as well as utilization process within our applications with no trouble.

Android SQLite Database : Need of SQLiteOpenHelper

Whenever we make use of an Android SQLite Database all of us undoubtedly require the help of SQLiteOpenHelper to handle our data.SQLiteOpenHelper is surely an superb destination to place some initial values right into the android sqlite database when it is built.

The important bits of details, you simply must provide for the android sqlite database

  • name
  • version number
At any time when the particular android sqlite database is actually accessed, it is going to take a look at the version number, in case the version number within the storage is not really match up the existing version then the onUpgrade() process will likely be called.

Android SQLite Database : Create Database

Create a database named country with name, cap, code fields and _id field as primary key which is usually auto increment.


public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE country (_id integer primary key autoincrement,name, cap, code);";
db.execSQL(createQuery);
}

Android SQLite Database : Open a Database


public void open() throws SQLException {
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}

Android SQLite Database : Close a Database


public void close() {
if (database != null)
database.close();
}

Android SQLite Database : Insert Values to Database
public void insertContact(String name, String cap, String code) {
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
open();
database.insert("country", null, newCon);
close();
}
Android SQLite Database : Read Database
public Cursor getAllContacts() {
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id) {
return database.query("country", null, "_id=" + id,
null, null, null, null);
}
Android SQLite Database : Update Database
public void updateContact(long id, String name, String cap,String code) {
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
Delete Database


public void deleteContact(long id) {
open();
database.delete("country", "_id=" + id, null);
close();
}

Android SQLite Database Example : World Countries Information Book App

  • World Countries Information Book App – you can create countries by giving its name, capital, telephone code, currency, languages speaking, …
  • Pressing the actual device’s menu button while looking at a contact’s information shows a menu that contains Edit Country and Delete Country choices.
  • In case the user selects to modify the particular country item from the android sqlite database, the actual application starts an Activity which displays the existing details within EditTexts.
  • In case the user makes a decision to delete the particular country item from android sqlite database, a dialog which requires the user to ensure the remove operation.
  • Touching the device’s menu button when looking at the contact list shows a menu that contains an Add Country item option—touching which option begins an Activity intended for adding a brand new country item to android sqlite database.
  • Pressing the Save Country Button will save the new country item to our android sqlite database as well as return the user towards the main contact screen which displays the list of country items.
Adding a new Country Item
  • The country list will likely be empty when you run the application for the very first time. Then If you want to add a new country information press the menu button then the Add menu item.
  • Once you add the particular country details, then touch the save button to store the country item info in the android sqlite database. Then go back to the application’s main screen.
  • If you desire to add more country details then you can. Finally Press the back button to return the main screen of the application which displays the all country item details via android sqlite database.
Viewing a Country Item’s Information
  • By touching the existing country to see the country’s informations.
Android SQLite Database : Editing a Country Item’s Information
  • While seeing the country item’s detail, you can edit the country item’s details by touching the edit menu item. Then you can save the changes through the save button which insert the values to our android sqlite database.
Deleting a Country Item
  • While viewing the country item’s details, touch the Delete Country menu item to delete a particular country. Finally confirm this action in the dialog. Then the country item will be removed from the android sqlite database.
Creating Styles for the Country Item
  • You can write a style.xml file which can define GUI component style attribute. You can then apply these styles to the desire components. If you make changes to the style.xml file then it will be applied to the App GUI components automatically.

The following styles.xml is going to be used in the layout view_country.xml
styles.xml

<resources>
    <style name="StyleLabel">
      <item name="android:layout_width">wrap_content
      <item name="android:layout_height">wrap_content
      <item name="android:gravity">right
      <item name="android:textSize">14sp
      <item name="android:textColor">@android:color/white
      <item name="android:layout_marginLeft">5dp
      <item name="android:layout_marginRight">5dp
      <item name="android:layout_marginTop">5dp
   </style>
   <style name="StyleText">
      <item name="android:layout_width">wrap_content
      <item name="android:layout_height">wrap_content
      <item name="android:textSize">16sp
      <item name="android:textColor">@android:color/white
      <item name="android:layout_margin">5dp
      <item name="android:background">@drawable/textview_border
   </style>
</resources>
TextView Background style

Here we are going to define a border to the TextView, In android by default TextViews don’t have a border. We can use a drawable as the TextView’s android:background attribute. It can be an image or an XML representation of a shape. You can place these in the drawable folder.

textview_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
   <corners android:radius="5dp"/>
   <stroke android:width="1dp" android:color="#31fcff"/>
   <padding android:top="10dp" android:left="10dp" android:bottom="10dp" android:right="10dp"/>
</shape>
Defining the ListView’s Items Format

To display the number of contact list items we are going to make use of ListView Item. It can be scrollable if the complete list is too large to be displayed on the screen.

country_list.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/countryTextView"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:padding="8dp"
   android:textSize="20sp"
   android:textColor="@android:color/white"
   android:minHeight="?android:attr/listPreferredItemHeight"
   android:gravity="center_vertical"/>
Specifying menu Resources in XML

With regard to this particular application, we’re going to make use of menu resources in XML to specify the actual MenuItems.

country_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:id="@+id/addCountryItem"
      android:title="@string/add_menu"
      android:icon="@drawable/menu_add"
      android:titleCondensed="@string/add_menu"
      android:alphabeticShortcut="e"/>
</menu>
view_country_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   <item
      android:id="@+id/editItem"
      android:title="@string/edit_menu"
      android:orderInCategory="1"
      android:alphabeticShortcut="e"
      android:titleCondensed="@string/edit_menu"
      android:icon="@drawable/menu_edit"/>
   <item
      android:id="@+id/deleteItem"
      android:title="@string/delete_menu"
      android:orderInCategory="2"
      android:alphabeticShortcut="d"
      android:titleCondensed="@string/delete_menu"
      android:icon="@drawable/menu_delete"/>
</menu>
Each menu resource XML file contains a root menu component along with every single MenuItem.
  • android:title and android:titleCondensed — all these specify the text to show within the MenuItem. In case the title text to display is actually long to show properly you need to use the condensed title.
  • android:icon — specifies a Drawable to show off within the MenuItem over a title text message. In this particular example’s MenuItems, we make use of three of the icons that I downloaded from the net. They’re found in res/drawable-hdpi folder.
  • android:alphabeticShortcut — specifies a shortcut letter which the user can certainly press to choose the actual menu item.
  • android:orderInCategory — Specifies the MenuItems actual order to show up.
World Countries Android SQlite Database Connector Class

Android SqliteDatabase names needs to be unique inside a particular application however do not need to be unique throughout apps. A SQLiteDatabase object offers read/write access to a Android SQLite database. DatabaseConnection’s constructor provides an impressive new object of class DatabaseOpenHelper, which is to be helpful to open up or even create the android sqlite database.

DatabaseConnector.java

package com.example.worldcountrybook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}

Method insertContact inserts a brand new contact with the actual provided details inside the android sqlite database. We initially place each and every bit of contact information right into a new ContentValues object, which usually keeps a map of key–value pairs—the android sqlite database’s column names are definitely the keys. After that open up the android sqlite database, insert the brand new contact and even close the actual android sqlite database.

public void insertContact(String name, String cap, String code)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String cap,String code)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null, null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
  • Method updateContact is identical to method insertContact, except that it calls Android SQLite Database’s update method to update an existing contact.
  • Method getAllContacts makes use of Android SqLite Database’s query method in order to obtain a Cursor which gives you access to the IDs and also names of all of the contacts within the android sqlite database table.
  • The Cursor returned through method query consists of all of the table rows which match the actual method’s arguments—the so-called result set. The actual Cursor lies prior to the very first row of the result set—Cursor’s various move methods enables you to move the Cursor with the result set with regard to processing.
  • Method getOneContact additionally uses SqLiteDatabase’s query strategy to query the database. In cases like this, all of us retrieve all of the columns within the android sqlite database for the contact with the desired ID.
  • Method deleteContact makes use of SqLiteDatabase’s delete approach to delete any contact from the android sqlite database.

Full Source Code

Output Screen of the Application

Android Tutorial For Beginners

Android Tutorial For Beginners SQLite Database

Android SQLite Database

Android SQLite Database Example

Android SQLite Database Tutorial

Finally we have learnt how to use SQLite and Built application using SQLite database in android through this Android SQLite Database Tutorial Example of Android Tutorial For Beginners Series.

Take a Look at this Advanced Tutorial on Android SQLite Database using Custom Cursor Adapter ListView

Contact List View

99 comments

  1. Great tutorial on Android and SQLite on the web.

    • @VimalRick
      Thanks for the tutorial, it really helps. But there are things that i don’t understand why do you need to use Async to save the countries if i understand the code correctly.

      And please sir send me the project. Thanks in advance

  2. Good Work …Keep it up!

  3. can u send me view_country.xml file

    • Hai Swapnil, I have also updated it in my post. And tell me whether you can download the code or not. If you can download the code, then you can find it inside the res/layout folder.

      view_country.xml
      ——————-
      < ?xml version="1.0" encoding="utf-8"?>

      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:stretchColumns="1"
      android:layout_margin="5dp">
      android:text="@string/name_lbl">
      style="@style/StyleText">
      android:text="@string/cap_lbl">
      style="@style/StyleText">
      android:text="@string/code_lbl">
      style="@style/StyleText">
  4. great tutorial but the example requires htc open sense sdk library .
    please make it universal

    • Thank you for your comment Vivek, I have updated the Code now.
      Please do download the updated project file.
      If any issues you can inform me.
      Keep visiting my blog :)

      • hi vimal i just download your project .in that oly 3 edittext feild is thr,if i add 4th one it take it.when add 5th it seems error .it say no string refrence database connector but i add string thr .please help me vimal by anand. if u found mail to anandkiot@gmail.com.ex.i need to add 6 edittext in that .if u can means help me . i am in helpless position

      • Hi. It can only be used in android 4.1 (API 16), how can I use this to android 2.2?

        • right click the project folder
          select properties–>select Android from the left portion of the window.
          Now you will see a list of available platform.
          Select your desire platform ex:android 2.2 and click apply and ok.

          Now you will see android2.2 jar inside your project folder below gen folder.

          • Thank you. But I have another problem, when I run your code, only a black blank screen appears. I tried to change the theme but nothing happened. Sorry, I’m still new with android programming and I don’t know the things to debug.

          • Sorry man,
            You need to press menu button. “Menu” button can be found in right side of your emulator.
            Or simply press F2 from your keyboard.
            Then “Add Country” Menu will be shown. From there you can proceed.

  5. you using 3 edit text but i need to use 6 . i can create string in databaseconnector class and create database table in that class .but it seems error. i need to u r help

  6. Very useful. Finding good tutorial of data binding with list view is difficult.

  7. hey hi , can u please send me the link from where i can download this project ,for some reason , i cannot find the download link ,it would be a great thanks in advance

  8. please ,can you have some idea about to open a project..

  9. Thanks for tutorial….

    conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list, null, from, to);
    SimpleCursorAdapter is deprecated, what is the alternative?

  10. Thanks! I fuckin’ love you!!!

  11. hai VimalRick, i am beginner of Android Applications development, So i developed one application useing Sqlite database for android app and i created a App file Like(Example.apk). And i install Android Tab App it’s runing fine then when i useing databse it’s not working, where i did mistake let me know plz…. it’s throwing Exception like (Application unfortunately stopped )

  12. Hi I was just wondering how to add more than one table in the database using DBOpenhelper.
    I’m actually writing an app with same kind of your sample app ,but with 3 more options.I want to navigate the page according to the user choice.But I find it really hard and the menu doesn’t seem working when I add more than one item in the menu .Can you please help me with this.

  13. @VimalRick

    At first I want thanks for such a nice tutorial with clear picture showing interaction between android and Sqlite database, It helped me a lot.

    But How can display the Country_List using Spinner drop down and respected textViews should be updated depending upon the country selected……

    Thanks you in advance…..

  14. I didn’t got your mail yet waiting for your response……Thanks

  15. Thanks I got your mail …….

    I want to know more about How to fetch particular values of record from SQL databse stored on server and update that values in SQLite database of android?

  16. VimalRick
    i am gone need your help with my project

  17. i found exact that what i need thanks for this great example and keep it up

  18. code iws not download is show advertise and say download iLivid what is that? please sendme code on my email farhankhan0987@hotmail.com

  19. i need ur help vimalRick i edit ur code and add imageview field but is not save iamge in database i modify ur code to add button which browse and take image from gellry and upload in database what is wrong in my code ? i posy my question also on stack overflow no one answer me please help me what do i do??

    http://stackoverflow.com/questions/13879011/please-tell-me-how-do-i-add-image-view-field-ins-qllite-database

    this is my code url which i post on stackover flow plz tel me how do i add image field in ur code? s o its browse and load image and save and retrieve from database give me ur email address so i can mail u my project

  20. i sent u my code plz check it

  21. great tutorial…..please tell me how to store image …along with it like country flag

    • OK, I have already prepared a Tutorial on that. But it will took some more days to post, as I am developing some other students college projects. Any way I have sent you the code to your mail. :)

      Like my Fanbook page. And add me to your google Circle.

      I can chat with you, and will help you further.

  22. hi vimal
    i couldnt understand how row_id taken when clicking the listview
    i understand how u pass the row_id from Country_List to View_country
    but how you get that row_id synchronous with databse id and listview id
    could u help me please
    Thanks a lot for your help and Magnificent Tutorial

    • OnItemClickListener viewConListener = new OnItemClickListener()
      {
      public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3)
      {
      Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
      viewCon.putExtra(ROW_ID, arg3);
      startActivity(viewCon);
      }
      };

      public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3)

      Below you can see the more clear form of the above method.

      public void onItemClick (AdapterView< ?> parent, View view, int position, long id)

      parent ==> The AdapterView where the click happened.

      view ==> The view within the AdapterView that was clicked

      position==> The position of the view in the adapter.

      id ==> The row id of the item that was clicked.

      So here, you know, we want to pass the row position of the clicked item in the listview.
      I assigned a id to a String called ROW_ID. You can see at the beginning of this class, I have created this String variable.
      and pass to the next activity.

  23. thank for email…..while saving country without loading image giving an error

  24. well i used Boolean to overcome that…help me search function i am not able get search function work

  25. Please can u post an example on SQL Lite Database using Foreign Keys in Android.. Thank You In Advance.. :)

  26. How to display more information from table ? not only Country name in this Country list ?

    • and how to read information not only from TextBoxes but also from spinners and time/date pickers ?

      • and how to display a Country with the same key world ? for example insead of displaying all countries it will display countries with the same world ? , key_world = United and it will display :
        United Arab Emirates
        United Kingdom
        United States of America etc etc

  27. Hi,

    Please send me the full script for SQLiteOpenHelper class. I’m having trouble in naming the database = dbOpenHelper.getWritableDatabase();
    It says that I have to create another class for database.

  28. I cant download.. Its lock

  29. I find it’s great, dear.

    Please, send your code to me

    annv1990@gmail.com

  30. I have a some doubt about this example, so please send me your mail id.

  31. This is so very nice tutorial. You know what dude! I’m using it for my thesis project, You are a life saver. This Codes and Idea’s are so useful. Can I request? Can you post a 2-3 tables with relationship? Our thesis compose with 3 tables. Can you set an example? It is my honor to grant my request. More power to you dude. :)

  32. Sir,
    I am very beginner in android I use Eclipse Galileo version. I have run some basic application in android now i want run database application using SQLite. I have try to run your provided Android SQLite Database Example code but it cant run why I dont know following are the 36 error occur during run so sir please help me how I can run this program because using this database program. I understand & implement my 8th semester android project so sir please help me.

  33. Sir,
    I am very beginner in android I use Eclipse Galileo version. I have run some basic application in android now i want run database application using SQLite. I have try to download & run your provided Android SQLite Database Example code but it cant run why I dont know following are the error occur during run so sir please help me how I can run this program because using this database program. I understand & implement my 8th semester android project so sir please help me.

    The errors are

    Description Resource Path Location Type
    The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project WorldCountriesBooks Unknown Java Problem
    The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files ViewCountry.java /WorldCountriesBooks/src/com/example/worldcountriesbooks line 1 Java Problem
    Unable to resolve target ‘android-16′ WorldCountriesBooks Unknown Android Target Problem

  34. Hi vimal,

    Thanks for such nice example. When i try to download the source code, it is showing some add. could you send me the code to this id mpadmapriya89@gmail.com.

  35. Very nice work. Please send me the project. :)

  36. hi vimal,

    i am trying to download source code but i cant. it always shows advertisement whenever i clicked on.
    would you please send me the full source code as soon as possible. Please!
    my email id is : abhiporval@gmail.com

  37. Please ! sent to me your project.
    My email: minhlanhat@gmail.com

  38. hi vimal
    i just send u a note via my wifes fb site regarding one thing about your database sample
    i like to add an image into the listview for each item – could u please reply with an idea how it will be done like a flag for the 3 samples (germany, india and malaysia).
    i changed the xml file and some code cause to compare the listview countrynames with a given word – but i stucked now for a couple of weeks. my e-mail adress is info@cargoonhand.com

    hope u have a few minutes to i have a eye on my problem

  39. Hey dude, thanks for the post. unable to get your source code, can u email it to pars_root@hotmail.co.uk

    thanks in advance!

  40. Hello sir,

    i get error in ViewCountry.java. in line where i use Async. The error in The type new AsyncTask(){} must implement the inherited abstract method AsyncTask.doInBackground(Object…). So plz help me in resolve this error

    Thank you
    Vikram Raj

  41. sir i am unable to download database code of country….plz send me.dat codes
    on my email id…himanshukr403@gmail.come

  42. how to know the speed of distant vehicle using android mobile?????????????

  43. Hi vimal,

    I want the entire project coding,could u send me that coding to my mail id:anwar.res@gmail.com

  44. Good tutorial. But however I found a little issue(it might not be an issue for others). When I press a delete button on the list item. It gives another activity as it started the same activity through intent in the delete contact method. Suppose if I press delete button on three items of the listview, it back stacks 3 activities. Can you please suggest how to avoid this?

  45. Hello sir,
    in my project there are three classes
    Fist class is DatabaseHelper class
    Second Class is UserImage class (user image id (PK) ,user image name)
    Thrid Class is User class ( user id(PK) ,user name , user image id (FK)
    There is a relationship between second and third class
    When I called them in DatabaseHelper Class , two choices (Create field or create constant) are shown on DatabaseHelper page . I couldn’t this part please help me my mail address is deryaaltinoklar@gmail.com

  46. hi vimal. this is awesome tutorial. i am a newbie in android and m working currently in a project using database. please can you send me the source code. it will of great help. this is great stuff. like it. my mail id is iyerkrtk@gmail.com please send me at earliest.

    thanks and regards..

  47. Hi vimal,

    hi vimal.
    this is cool tutorial. i am a new in android and m working currently in a project using database. please can you send me the source code. it will of great help. this is great stuff. mail id:mangalpsingh@yahoo.com.plz as soon as possible

  48. Hello, sir!
    i cannot download the code
    could you please send me a code?
    I put like and add the google also!
    My email is
    raulhurj@gmail.com

    Thanks in advance!!

  49. Thanks for the tutorial, it really helps.

    Can send me the project code?
    Email: luvclssam@yahoo.com

    Thanks in advance

  50. great tutorial!!!!!!!!!!, but im stuck at SQLiteDatabase.jave.. can u email me full coding? zazsvs_ok2@yahoo.com

  1. Pingback: how to inseert selected image in sqllite database video

  2. Pingback: How to insert selected image in a SqlLite database ? : Android Community - For Application Development

  3. Pingback: Need some help going through code

  4. Pingback: changing font colour in ListView, database, android : Android Community - For Application Development

Leave a Reply

Scroll To Top

Foolow Me on Google Plus

VimalTuts on Twitter
62 people follow VimalTuts
Lukus_Q7jatarmlmohammedsureshkurupinderdeeprojeMageshKeravon30