Tuesday, January 11, 2011

Using Database SQLite : Andorid

Hi There...

Hope the last post of mine was quite useful for anyone who wanna go ahead and implement his/ her Notification..

Today we'll discuss about saving and retrieving data in and from database.
As Android has provided us with SQLite database. In this section of post we will understand the usage of the same.

WHAT IS SQLITE (QUOTE FROM WIKIPEDIA)
SQLite uses a dynamically- and weakly-typed SQL syntax that does not guarantee the domain integrity, which gives rise to criticism. SQLite is a multitasking database concerning reads. Writes can be done only one-at-a-time. It is a popular choice for local/client storage on Web browsers. It has many bindings to programming languages. Before a new version is released, extensive regression tests are performed, in an attempt to increase the quality of the product. It is arguably the most widely used database engine, as it is used today by several widespread browsers, operating systems, embedded systems among others

WHEN TO USE
This defines your understanding on the architecture of Android, also it showcases your expertise and understanding of tools that you use in different cases.
SQLite database is used in typical scenarios when you need to save multiple data in tabular format. Please note it is not a good practice to save Images in SQLite database.
Just for info we have multiple saving options when we tak about Andorid
1. Shared Preferences
2. Local Storage
3. External Storage
4. SQLite Database

Hence, you should identify your target well before going ahead and saving your data.

IMPLEMENTATION:
/**
* Copyright [2011] [Abhinava Srivastava]
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package abhi.blog.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SQlConnector {

/**
* NAME of database
*/
private static final String NAME = "abhinavasblog";

/**
* TABLE NAME
*/
private static final String TABLE_NAME = "blog";

// To hold Context reference
private Context mContext = null;

/**
* To hold SQliteDatabase handler reference All operations of SQL will be
* performed over this
*/
private SQLiteDatabase databaseHandler = null;

/**
* Private Constructor to create only single instance of the class
*
* @param cntx
*/
private SQlConnector() {
}

private void openDB(Context cntx) {
// make check for no null value
if (cntx != null && mContext == null) {
mContext = cntx;
}

/**
* openOrCreateDatabase method has been provided by Context class.
* Taking 3 Params 1. Name of database you wanna create 2. Mode in which
* you want to open the database 3. Cursor factory is is Used to allow
* returning sub-classes of Cursor when calling query. for now we pass
* null as we are going to handle it here itself.
*/
databaseHandler = mContext.openOrCreateDatabase(NAME,
SQLiteDatabase.OPEN_READWRITE, null);

/**
* SQLiteDatabase has multiple options by which you can perform various
* operations in Android.
*/
databaseHandler.execSQL("create if not exists " + TABLE_NAME
+ " (names text);");
}

/**
* @param dataToInsert
* @return index of inserted data
*/
public long insertData(String dataToInsert, Context cntx) {
// open DB
openDB(cntx);

/**
* Creating data pair which need sto be inserted in the table
*/
ContentValues values = new ContentValues();
values.put("names", dataToInsert);

/**
* Insert function is provided by SQLiteDatabase with following
* parameter 1. Table Name 2. Calumn Hack - SQLiteDatabase do not allow
* null values but incase you want to fit in null 3. ContentValues - Key
* value pair which needs to be inserted in the DB
*/
long rowId = databaseHandler.insert(TABLE_NAME, null, values);

// close DB
closeDB();
return rowId;
}

/**
* @param id
*/
public void readAllFromDatabase(Context cntx) {
// open DB
openDB(cntx);

/**
* Query database for all values Cursor is responsible for traversing
* the view which is returned
*/
Cursor cursor = databaseHandler.query(TABLE_NAME, null, null, null,
null, null, null);

if (cursor != null) {
// reset cursor to top position of the obtained view of result set
cursor.moveToFirst();

while (!cursor.isAfterLast()) {
Log.i("Saved Data", cursor.getString(cursor
.getColumnIndex("names")));
}
}

// Close the cursor
cursor.close();
// close DB
closeDB();
}

/**
* Closing Database
*/
private void closeDB() {
if (databaseHandler != null) {
databaseHandler.close();
databaseHandler = null;
}
}

}


No comments: