Thursday, 23 April 2015

Android Sqlite

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

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:

android simple sqlite example output 1

Android Sqlite Example

In this example, we are adding a label on button click and displaying all the added labels on the spinner. As you have seen in the previous example, SQLiteOpenHelper class need to be extended for performing operations on the sqlite.
We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper class in the DatabaseHandler class that provides additional methods to insert and display the labels or data.

Android Sqlite Spinner Example

Let's see the simple code to add and display the string content on spinner using sqlite database.

activity_main.xml

File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.      <!-- Label -->  
  8.     <TextView  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="Add New Label"  
  12.         android:padding="8dip" />  
  13.   
  14.     <!-- Input Text -->  
  15.     <EditText android:id="@+id/input_label"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_marginLeft="8dip"  
  19.         android:layout_marginRight="8dip"/>  
  20.   
  21.     <Spinner  
  22.         android:id="@+id/spinner"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_alignParentLeft="true"  
  26.         android:layout_below="@+id/btn_add"  
  27.         android:layout_marginTop="23dp" />  
  28.   
  29.     <Button  
  30.         android:id="@+id/btn_add"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_below="@+id/input_label"  
  34.         android:layout_centerHorizontal="true"  
  35.         android:text="Add Item" />  
  36.      
  37. </RelativeLayout>  

Activity class

File: MainActivity.java
  1. package com.example.sqlitespinner;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import java.util.List;  
  7. import android.content.Context;  
  8. import android.view.View;  
  9. import android.view.inputmethod.InputMethodManager;  
  10. import android.widget.AdapterView;  
  11. import android.widget.AdapterView.OnItemSelectedListener;  
  12. import android.widget.ArrayAdapter;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.Spinner;  
  16. import android.widget.Toast;  
  17.   
  18. public class MainActivity extends Activity implements OnItemSelectedListener{  
  19.     Spinner spinner;  
  20.     Button btnAdd;  
  21.     EditText inputLabel;  
  22.    
  23.     @Override  
  24.     public void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.activity_main);  
  27.    
  28.         spinner = (Spinner) findViewById(R.id.spinner);  
  29.         btnAdd = (Button) findViewById(R.id.btn_add);  
  30.         inputLabel = (EditText) findViewById(R.id.input_label);  
  31.    
  32.         spinner.setOnItemSelectedListener(this);  
  33.    
  34.         // Loading spinner data from database  
  35.         loadSpinnerData();  
  36.    
  37.         btnAdd.setOnClickListener(new View.OnClickListener() {  
  38.    
  39.             @Override  
  40.             public void onClick(View arg0) {  
  41.                 String label = inputLabel.getText().toString();  
  42.    
  43.                 if (label.trim().length() > 0) {  
  44.                     DatabaseHandler db = new DatabaseHandler(getApplicationContext());  
  45.                     db.insertLabel(label);  
  46.    
  47.                     // making input filed text to blank  
  48.                     inputLabel.setText("");  
  49.    
  50.                     // Hiding the keyboard  
  51.                     InputMethodManager imm = (InputMethodManager)   
  52.                           getSystemService(Context.INPUT_METHOD_SERVICE);  
  53.                     imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);  
  54.    
  55.                     // loading spinner with newly added data  
  56.                     loadSpinnerData();  
  57.                 } else {  
  58.                     Toast.makeText(getApplicationContext(), "Please enter label name",  
  59.                             Toast.LENGTH_SHORT).show();  
  60.                 }  
  61.    
  62.             }  
  63.         });  
  64.     }  
  65.    
  66.     /** 
  67.      * Function to load the spinner data from SQLite database 
  68.      * */  
  69.     private void loadSpinnerData() {  
  70.         DatabaseHandler db = new DatabaseHandler(getApplicationContext());  
  71.         List<String> labels = db.getAllLabels();  
  72.    
  73.         // Creating adapter for spinner  
  74.         ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, labels);  
  75.    
  76.         // Drop down layout style - list view with radio button  
  77.         dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
  78.    
  79.         // attaching data adapter to spinner  
  80.         spinner.setAdapter(dataAdapter);  
  81.     }  
  82.    
  83.     @Override  
  84.     public void onItemSelected(AdapterView<?> parent, View view, int position,  
  85.             long id) {  
  86.         // On selecting a spinner item  
  87.         String label = parent.getItemAtPosition(position).toString();  
  88.    
  89.         // Showing selected spinner item  
  90.         Toast.makeText(parent.getContext(), "You selected: " + label,  
  91.                 Toast.LENGTH_LONG).show();  
  92.    
  93.     }  
  94.    
  95.     @Override  
  96.     public void onNothingSelected(AdapterView<?> arg0) {  
  97.         // TODO Auto-generated method stub  
  98.    
  99.     }  
  100.     @Override  
  101.     public boolean onCreateOptionsMenu(Menu menu) {  
  102.         // Inflate the menu; this adds items to the action bar if it is present.  
  103.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  104.         return true;  
  105.     }  
  106.   
  107. }  

DatabaseHandler class

File: DatabaseHandler.java
  1. package com.example.sqlitespinner2;  
  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.   
  10. public class DatabaseHandler extends SQLiteOpenHelper {  
  11.     private static final int DATABASE_VERSION = 1;  
  12.     private static final String DATABASE_NAME = "spinnerExample";  
  13.     private static final String TABLE_NAME = "labels";  
  14.     private static final String COLUMN_ID = "id";  
  15.     private static final String COLUMN_NAME = "name";  
  16.    
  17.     public DatabaseHandler(Context context) {  
  18.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  19.     }  
  20.    
  21.     // Creating Tables  
  22.     @Override  
  23.     public void onCreate(SQLiteDatabase db) {  
  24.         // Category table create query  
  25.         String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("  
  26.                 + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";  
  27.         db.execSQL(CREATE_ITEM_TABLE);  
  28.     }  
  29.    
  30.     // Upgrading database  
  31.     @Override  
  32.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  33.         // Drop older table if existed  
  34.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);  
  35.    
  36.         // Create tables again  
  37.         onCreate(db);  
  38.     }  
  39.    
  40.     /** 
  41.      * Inserting new lable into lables table 
  42.      * */  
  43.     public void insertLabel(String label){  
  44.         SQLiteDatabase db = this.getWritableDatabase();  
  45.    
  46.         ContentValues values = new ContentValues();  
  47.         values.put(COLUMN_NAME, label);//column name, column value  
  48.    
  49.         // Inserting Row  
  50.         db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues  
  51.         db.close(); // Closing database connection  
  52.     }  
  53.    
  54.     /** 
  55.      * Getting all labels 
  56.      * returns list of labels 
  57.      * */  
  58.     public List<String> getAllLabels(){  
  59.         List<String> list = new ArrayList<String>();  
  60.    
  61.         // Select All Query  
  62.         String selectQuery = "SELECT  * FROM " + TABLE_NAME;  
  63.    
  64.         SQLiteDatabase db = this.getReadableDatabase();  
  65.         Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments  
  66.    
  67.         // looping through all rows and adding to list  
  68.         if (cursor.moveToFirst()) {  
  69.             do {  
  70.                 list.add(cursor.getString(1));//adding 2nd column data  
  71.             } while (cursor.moveToNext());  
  72.         }  
  73.         // closing connection  
  74.         cursor.close();  
  75.         db.close();  
  76.    
  77.         // returning lables  
  78.         return list;  
  79.     }  
  80. }  


Output:

android sqlite example output 1 android sqlite example output 2 android sqlite example output 3

No comments:

Post a Comment