1. Data Storage
• Your data storage options are the following:
• Shared Preferences
• Store private primitive data in key-value pairs.
• Internal Storage
• Store private data on the device memory.
• External Storage
• Store public data on the shared external storage.
• SQLite Databases
• Store structured data in a private database.
• Network Connection
• Store data on the web with your own network server.
2. SQLite Database
• SQLite is a Structure query base database, open source, light weight, no
network access and standalone database.
• Whenever an application needs to store large amount of data then using
sqlite is more preferable than other repository system
like SharedPreferences or saving data in files.
• Android has built in SQLite database implementation.
• It is available locally over the device(mobile & tablet) and contain data in
text format. So, it doesn’t required any administration or setup procedure
of the database.
• The database created is saved in a directory:
data/data/APP_Name/databases/DATABASE_NAME.
3. SQLite Database
• For creating, updating and other operations you need to
use SQLiteOpenHelper class.
• SQLiteOpenHelper is a helper class to manage database creation and
version management.
• It provides two methods
• onCreate(SQLiteDatabase db),
• onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion).
4. SQLite Database
• The SQLiteOpenHelper is responsible for opening database if exist,
creating database if it does not exists and upgrading if required.
• The SQLiteOpenHelper only require the DATABASE_NAME to create
database.
• After extending SQLiteOpenHelper you will need to implement
its methods onCreate(), onUpgrade() and constructor.
5. SQLite Database
• onCreate(SQLiteDatabase sqLiteDatabase)
• is called only once throughout the application lifecycle.
• It will be called whenever there is a first call to
getReadableDatabase() or getWritableDatabase() function
available in super SQLiteOpenHelper class.
• Syntax:
public void onCreate(SQLiteDatabase sqLiteDatabase)
6. • onUpgrade(SQLiteDatabase db,int oldVersion, int
newVersion)
• is only called whenever there is a update in existing
version.
• so to update a version we have to increment the value of
version variable passed in the superclass constructor.
• Syntax:
onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion)
• In onUpgrade (), we can write queries to perform whatever
action is required. In most example you will see that
existing table(s) are being dropped. But it’s not mandatory
to do so and it all depends upon your requirements.
7. • execSQL(String sql, Object[] bindArgs)
• This method not only insert data , but also used to update or modify already existing
data in database using bind arguments
• Execute SQL query not SELECT query
• Execute a single SQL statement that is NOT a SELECT or any other SQL statement that
returns data.
• It has no means to return any data (Such as the number of affected rows)
8. Cursor
• public Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy)
• Query the given table, returning a Cursor over the result set.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
9. Cont..
• table
• The table name to compile the query against.
• columns
• A list of which columns to return. Passing null will return all columns, which is
discouraged to prevent reading data from storage that isn't going to be used.
• selection
• A filter declaring which rows to return, formatted as an SQL WHERE clause
(excluding the WHERE itself). Passing null will return all rows for the given
table.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
10. Cont..
• selectionArgs
• You may include selection, which will be replaced by the values from selectionArgs,
in order that they appear in the selection. The values will be bound as Strings.
• groupBy
• A filter declaring how to group rows, formatted as an SQL GROUP BY clause
(excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
• having
• A filter declare which row groups to include in the cursor, if row grouping is being
used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null
will cause all row groups to be included, and is required when row grouping is not
being used.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
11. Cont..
• orderBy
• How to order the rows, formatted as an SQL ORDER BY clause (excluding the
ORDER BY itself). Passing null will use the default sort order, which may be
unordered.
• limit
• Limits the number of rows returned by the query, formatted as LIMIT clause.
Passing null denotes no LIMIT clause.
• Returns
• A Cursor object, which is positioned before the first entry.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
12. Example
• SELECT column_name,column_name FROM table_name
WHERE column_name operator value;
• SELECT column_name, column_name FROM table_name ORDER
BY column_name ASC|DESC;
• Cursor c = db.query(TABLE, null, null, null, null, null, KEY_SNAME+”DESC”);
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
13. Content Value
• This class is used to store a set of values that the ContentResolver can
process.
• ContentValues()
• Creates an empty set of values using the default initial size
• public void put (String key, String value)
• Adds a value to the set.
• key
• the name of the value to put
• value
• the data for the value to put
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
14. SimpleCursorAdapter
• An easy adapter to map columns from a cursor to TextViews or
ImageViews defined in an XML file.
• You can specify which columns you want, which views you want to
display the columns, and the XML file that defines the appearance of
these views.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
15. Cont..
• Constructors:
• public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)
• public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)
• context
• The context where the ListView associated with this SimpleListItemFactory is running
• layout
• resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in
"to“
• c
• The database cursor. Can be null if the cursor is not available yet.
• from
• A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet.
• to
• The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values
of the first N columns in the from parameter. Can be null if the cursor is not available yet.
• flags
• Flags used to determine the behavior of the adapter.
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
16. Datatypes in SQLiteDatabase
• NULL
• The value is a NULL value.
• BLOB
• The value is a blob of data, stored exactly as it was input.
• INTEGER
• The value is a signed integer, stored in 0, 1, 2, 3, 4, 6, or 8 bytes
depending on the magnitude of the value.
• REAL
• The value is a floating point value, stored as an 8-byte IEEE floating
point number.
• TEXT
• The value is a text string, stored using the database encoding (UTF-
8, UTF-16BE or UTF-16LE).
CO4: Use Android APIs for managing data as well as
communication APIs for SMS, telephony and location.
17. CRUD operations
• Create, Read, Update & Delete
• While using SQLite there could be two different ways to perform
different operations like create, read, update and delete.
1. writing raw queries and
2. using parameterized functions
18. Creating a database
• Using SQLiteOpenHelper class with two methods
• onCreate(SQLiteDatabase db) and
• onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
• Syntax:
public class DBHelper extends SQLiteOpenHelper
{ @Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int
oldVersion, int newVersion)
{
}
}
19. Creating database
public class DBHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "abhiandroid.db";
public static final int version = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String dbQuery = "CREATE TABLE tblstudent (id INTEGER PRIMARY KEY
AUTOINCREMENT, name TEXT, description TEXT)";
sqLiteDatabase.execSQL(dbQuery);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int
newVersion)
{ }
}
20. • Insert, Read, Delete & Update Operation In SQLite:
• To perform insert, read, delete, update operation there are two
different ways:
• Write parameterized queries (Recommended)
• Write raw queries
• Parameterized Queries: using inbuilt functions to insert, read,
delete or update data. These operation related functions are
provided in SQLiteDatabase class.
• Raw Queries: These are simple sql queries similar to MySql.
• In this case user will have to write query as text and
• passed the query string in rawQuery(String sql,String [] selectionArgs) or
execSQL(String sql,Object [] bindArgs) method to perform operations.
• While using raw queries we never come to know the result of
operation, however with parameterized queries function a value is
returned for success or failure of operation.
21. Insert operation
• Example of raw query to insert data:
String query = "INSERT INTO tblstudent values( ‘Maya’, ‘Student’)”;
SQLiteDatabase db = getWritableDatabase();
db.execSQL(query);
db.close();
22. Insert operation
• Using parameterized query, call insert() function
available in SQLiteDatabase class.
• The insert() function has three parameters like
• Syntax:
db.insert(String tableName, String nullColumnHack,
ContentValues values);
Where,
• tableName is name of table in which data to be inserted.
• nullColumnHack may be passed null, it require table
column value in case we don’t put column name in
ContentValues object.
• ContentValues is a key-pair based object to store
name/values pairs.
• Its put() method enables you to insert keys with values of
different data types.
23. Insert operation
• Example of parameterize query for Insert
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", “Maya”);
contentValues.put("description", “Student”);
db.insert(“tblstudent", null, contentValues);
db.close();
24. Update operation
• update() is used to update data.
• Syntax:
public int update(String tableName,ContentValues contentValues,String
whereClause,String[] whereArgs)
• Here whereClause is tell the database where to update data in table, it’s recommended
to pass ?s (questions) along with column name in whereClause String.
• Similarly whereArgs array will contain values for those columns whose against ?s has
been put in whereClause.
• Update function will return number of rows affected if success, 0 otherwise.
26. Delete operation
• delete() function is available in SQLiteDatabase class
• Syntax:
public int delete(String tableName,String whereClause,String [] whereArgs)
Here whereClause is optional, passing null will delete all rows in table.
• delete function will return number of affected row if whereClause passed
otherwise will return 0.