Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

SQLite Tutorial


SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.

It is embedded in android bydefault. So, there is no need to perform any database setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is displayed in the logcat. For displaying data on the spinner or listview, move to the next page.

SQLiteOpenHelper class provides the functionality to use the SQLite database.


SQLiteOpenHelper class

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) creates an object for creating, opening and managing the database.
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) creates an object for creating, opening and managing the database. It specifies the error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is created for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) called when database needs to be upgraded.
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) called when database needs to be downgraded.

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String nullColumnHack, ContentValues values) inserts a record on the database. The table specifies the table name, nullColumnHack doesn’t allow completely null values. If second argument is null, android will store null values if values are empty. The third argument specifies the values to be stored.
int update(String table, ContentValues values, String whereClause, String[] whereArgs) updates a row.
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) returns a cursor over the resultset.

Example of android SQLite database

Let’s see the simple example of android sqlite database.

File: Contact.java
  1. package com.example.sqlite;
  2. public class Contact {
  3.    int _id;
  4.     String _name;
  5.     String _phone_number;
  6.      public Contact(){   }
  7.     public Contact(int id, String name, String _phone_number){
  8.         this._id = id;
  9.         this._name = name;
  10.         this._phone_number = _phone_number;
  11.     }
  12.     public Contact(String name, String _phone_number){
  13.         this._name = name;
  14.         this._phone_number = _phone_number;
  15.     }
  16.     public int getID(){
  17.         return this._id;
  18.     }
  19.     public void setID(int id){
  20.         this._id = id;
  21.     }
  22.     public String getName(){
  23.         return this._name;
  24.     }
  25.     public void setName(String name){
  26.         this._name = name;
  27.     }
  28.     public String getPhoneNumber(){
  29.         return this._phone_number;
  30.     }
  31.     public void setPhoneNumber(String phone_number){
  32.         this._phone_number = phone_number;
  33.     }
  34. }
File: DatabaseHandler.java

Now, let’s create the database handler class that extends SQLiteOpenHelper class and provides the implementation of its methods.

  1. package com.example.sqlite;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentValues;
  5. import android.content.Context;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.database.sqlite.SQLiteOpenHelper;
  9. public class DatabaseHandler extends SQLiteOpenHelper {
  10.    private static final int DATABASE_VERSION = 1;
  11.    private static final String DATABASE_NAME = “contactsManager”;
  12.     private static final String TABLE_CONTACTS = “contacts”;
  13.      private static final String KEY_ID = “id”;
  14.     private static final String KEY_NAME = “name”;
  15.     private static final String KEY_PH_NO = “phone_number”;
  16.     public DatabaseHandler(Context context) {
  17.         super(context, DATABASE_NAME, null, DATABASE_VERSION);
  18.         //3rd argument to be passed is CursorFactory instance
  19.     }
  20.     // Creating Tables
  21.     @Override
  22.     public void onCreate(SQLiteDatabase db) {
  23.         String CREATE_CONTACTS_TABLE = “CREATE TABLE “ + TABLE_CONTACTS + “(“
  24.                 + KEY_ID + ” INTEGER PRIMARY KEY,” + KEY_NAME + ” TEXT,”
  25.                 + KEY_PH_NO + ” TEXT” + “)”;
  26.         db.execSQL(CREATE_CONTACTS_TABLE);
  27.     }
  28.     // Upgrading database
  29.     @Override
  30.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  31.         // Drop older table if existed
  32.         db.execSQL(“DROP TABLE IF EXISTS “ + TABLE_CONTACTS);
  33.         // Create tables again
  34.         onCreate(db);
  35.     }
  36.      // code to add the new contact
  37.      void addContact(Contact contact) {
  38.         SQLiteDatabase db = this.getWritableDatabase();
  39.         ContentValues values = new ContentValues();
  40.         values.put(KEY_NAME, contact.getName()); // Contact Name
  41.         values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
  42.         // Inserting Row
  43.         db.insert(TABLE_CONTACTS, null, values);
  44.         //2nd argument is String containing nullColumnHack
  45.         db.close(); // Closing database connection
  46.     }
  47.     // code to get the single contact
  48.     Contact getContact(int id) {
  49.         SQLiteDatabase db = this.getReadableDatabase();
  50.         Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
  51.                 KEY_NAME, KEY_PH_NO }, KEY_ID + “=?”,
  52.                 new String[] { String.valueOf(id) }, nullnullnullnull);
  53.         if (cursor != null)
  54.             cursor.moveToFirst();
  55.         Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
  56.                 cursor.getString(1), cursor.getString(2));
  57.         // return contact
  58.         return contact;
  59.     }
  60.     // code to get all contacts in a list view
  61.     public List<Contact> getAllContacts() {
  62.         List<Contact> contactList = new ArrayList<Contact>();
  63.         // Select All Query
  64.         String selectQuery = “SELECT  * FROM “ + TABLE_CONTACTS;
  65.         SQLiteDatabase db = this.getWritableDatabase();
  66.         Cursor cursor = db.rawQuery(selectQuery, null);
  67.         // looping through all rows and adding to list
  68.         if (cursor.moveToFirst()) {
  69.             do {
  70.                 Contact contact = new Contact();
  71.                 contact.setID(Integer.parseInt(cursor.getString(0)));
  72.                 contact.setName(cursor.getString(1));
  73.                 contact.setPhoneNumber(cursor.getString(2));
  74.                 // Adding contact to list
  75.                 contactList.add(contact);
  76.             } while (cursor.moveToNext());
  77.         }
  78.         // return contact list
  79.         return contactList;
  80.     }
  81.     // code to update the single contact
  82.     public int updateContact(Contact contact) {
  83.         SQLiteDatabase db = this.getWritableDatabase();
  84.         ContentValues values = new ContentValues();
  85.         values.put(KEY_NAME, contact.getName());
  86.         values.put(KEY_PH_NO, contact.getPhoneNumber());
  87.         // updating row
  88.         return db.update(TABLE_CONTACTS, values, KEY_ID + ” = ?”,
  89.                 new String[] { String.valueOf(contact.getID()) });
  90.     }
  91.     // Deleting single contact
  92.     public void deleteContact(Contact contact) {
  93.         SQLiteDatabase db = this.getWritableDatabase();
  94.         db.delete(TABLE_CONTACTS, KEY_ID + ” = ?”,
  95.                 new String[] { String.valueOf(contact.getID()) });
  96.         db.close();
  97.     }
  98.     // Getting contacts Count
  99.     public int getContactsCount() {
  100.         String countQuery = “SELECT  * FROM “ + TABLE_CONTACTS;
  101.         SQLiteDatabase db = this.getReadableDatabase();
  102.         Cursor cursor = db.rawQuery(countQuery, null);
  103.         cursor.close();
  104.         // return count
  105.         return cursor.getCount();
  106.     }
  107. }
File: MainActivity.java
  1. package com.example.sqlite;
  2. import java.util.List;
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.util.Log;
  6. import android.view.Menu;
  7. public class MainActivity extends Activity {
  8.     @Override
  9.     protected void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         setContentView(R.layout.activity_main);
  12.         DatabaseHandler db = new DatabaseHandler(this);
  13.          // Inserting Contacts
  14.         Log.d(“Insert: ““Inserting ..”);
  15.         db.addContact(new Contact(“Ravi”“9100000000”));
  16.         db.addContact(new Contact(“Srinivas”“9199999999”));
  17.         db.addContact(new Contact(“Tommy”“9522222222”));
  18.         db.addContact(new Contact(“Karthik”“9533333333”));
  19.         // Reading all contacts
  20.         Log.d(“Reading: ““Reading all contacts..”);
  21.         List<Contact> contacts = db.getAllContacts();
  22.         for (Contact cn : contacts) {
  23.          String log = “Id: “+cn.getID()+” ,Name: “ + cn.getName() + ” ,Phone: “ +
  24.             cn.getPhoneNumber();
  25.         // Writing Contacts to log
  26.         Log.d(“Name: “, log);
  27.     }
  28.     }
  29.     @Override
  30.     public boolean onCreateOptionsMenu(Menu menu) {
  31.         // Inflate the menu; this adds items to the action bar if it is present.
  32.         getMenuInflater().inflate(R.menu.activity_main, menu);
  33.         return true;
  34.     }
  35. }

download this sqlite example

Output:

Open Logcat and see the output. It is the basic example of android sqlite without any GUI.

For GUI application with android SQLite, visit next page.


Output:

sqlitesimpleoutput1

Comments

comments