Introduction
In the previous articles, we discussed saving the data locally, meaning in the local storage of the phone. We also learned about data saving in the SD card or externally.
Saving data when developing an application requires connecting it to the database. In this case, the database is highly optimized for handheld devices. Saving the data to a database is good for structured data such as contact information. All the classes related and used for development is given in the package “android.database.sqlite”.
First of all, we need to configure the schema and must implement the schema, such that it is one of the principles of SQL databases. It is very helpful for declaring the contract classes that explicitly specify the layout of the schema in a systematic and self-documenting manner.
Let us have a look at how to create the table and rows in an SQLite database.
Defining a schema and contract
- public final class FeedReaderContract {
- // To prevent someone from accidentally instantiating the contract class,
- // give it an empty constructor.
- public FeedReaderContract() {}
- /* Inner class that defines the table contents */
- public static abstract class FeedEntry implements BaseColumns {
- public static final String TABLE_NAME = "entry";
- public static final String COLUMN_NAME_ENTRY_ID = "entryid";
- public static final String COLUMN_NAME_TITLE = "title";
- public static final String COLUMN_NAME_SUBTITLE = "subtitle";
- ...
- }
- }
The preceding written code is just a basic illustration. Now let us see the code with the SQL helper. Once you have defined how your database looks, you should implement methods that create and maintain the database and tables. Here are some typical statements that create and delete a table:
- private static final String TEXT_TYPE = " TEXT";
- private static final String COMMA_SEP = ",";
- private static final String SQL_CREATE_ENTRIES =
- "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
- FeedEntry._ID + " INTEGER PRIMARY KEY," +
- FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
- FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
- ... // Any other options for the CREATE command
- " )";
- private static final String SQL_DELETE_ENTRIES =
- "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
Just like files and other data any user save on the device locally, it means the device's internal storage. Each and every data entered or saved in the disk is completley secure because the other application can't access those resources. To use the sqliteOpenHelper create a subclass that overrides the onCreate(), onUpgrade() and onOpen() callback methods. For example the implementation of sqliteOpenHelper that uses some of the commands shown below.
- public class FeedReaderDbHelper extends SQLiteOpenHelper {
- // If you change the database schema, you must increment the database version.
- public static final int DATABASE_VERSION = 1;
- public static final String DATABASE_NAME = "FeedReader.db";
- public FeedReaderDbHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
- public void onCreate(SQLiteDatabase db) {
- db.execSQL(SQL_CREATE_ENTRIES);
- }
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // This database is only a cache for online data, so its upgrade policy is
- // to simply to discard the data and start over
- db.execSQL(SQL_DELETE_ENTRIES);
- onCreate(db);
- }
- public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- onUpgrade(db, oldVersion, newVersion);
- }
- }
To access your database, instantiate your subclass of SQLiteOpenHelper:
- FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
Now we have seen various commands in that previously written code. It is now time to put the information into the database.
Put Information into a Database
- // Gets the data repository in write mode
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- // Create a new map of values, where column names are the keys
- ContentValues values = new ContentValues();
- values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
- values.put(FeedEntry.COLUMN_NAME_TITLE, title);
- values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
- // Insert the new row, returning the primary key value of the new row
- long newRowId;
- newRowId = db.insert(
- FeedEntry.TABLE_NAME,
- FeedEntry.COLUMN_NAME_NULLABLE,
- values);
The first argument for insert() is simply the table name. The second one provides the name of a column the methods combines the elements of insert().
Reading the information from the database
- SQLiteDatabase db = mDbHelper.getReadableDatabase();
- // Define a projection that specifies which columns from the database
- // you will actually use after this query.
- String[] projection = {
- FeedEntry._ID,
- FeedEntry.COLUMN_NAME_TITLE,
- FeedEntry.COLUMN_NAME_UPDATED,
- ...
- };
- // How you want the results sorted in the resulting Cursor
- String sortOrder =
- FeedEntry.COLUMN_NAME_UPDATED + " DESC";
- Cursor c = db.query(
- FeedEntry.TABLE_NAME, // The table to query
- projection, // The columns to return
- selection, // The columns for the WHERE clause
- selectionArgs, // The values for the WHERE clause
- null, // don't group the rows
- null, // don't filter by row groups
- sortOrder // The sort order
- );
For each row, you can read a column's value by calling one of the Cursor get methods, such as getString() or getLong(). For each of the get methods, you must the index position of the column you desire that you can get by calling getColumnIndex() or getColumnIndexOrThrow(). Let us take an example:
- cursor.moveToFirst();
- long itemId = cursor.getLong(
- cursor.getColumnIndexOrThrow(FeedEntry._ID)
- );
Delete Information From the Database
- // Define 'where' part of query.
- String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
- // Specify arguments in placeholder order.
- String[] selectionArgs = { String.valueOf(rowId) };
- // Issue SQL statement.
- db.delete(table_name, selection, selectionArgs);
Update a Database
- SQLiteDatabase db = mDbHelper.getReadableDatabase();
- // New value for one column
- ContentValues values = new ContentValues();
- values.put(FeedEntry.COLUMN_NAME_TITLE, title);
- // Which row to update, based on the ID
- String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
- String[] selectionArgs = { String.valueOf(rowId) };
- int count = db.update(
- FeedReaderDbHelper.FeedEntry.TABLE_NAME,
- values,
- selection,
- selectionArgs);
Backup the Data on cloud
Package included in the Backup process
- Perform backup of arbitrary data to remote storage.
- Easily perform backup of SharedPreferences and files.
- Restore the data saved to remote storage.

Neeraj KumarPosted Jul 30, 2015, 4:26 PM
Nice
Sibeesh VenuPosted Feb 25, 2015, 5:15 AM
Good one.