41 YAMBA Database
41 YAMBA Database
The Database
Android uses database to store useful
information that needs to be kept even when
the app is killed or the device is shut down
Locally storing the data also makes it
accessible more quickly and have it even when
the network is unavailable
About SQLite
An open source database
Very stable
Reasons why SQLite is a great fit for Android
DbHelper
To access the database, we first need a helper
Provides a connection to the database
SQLiteOpenHelper
Returns an instance of SQLiteDatabase
Database Scheme
Description of whats in a database
Yamba Database
Created_at
Txt
User
ID
Each row in a database will contain the data
for one tweek
Schema Creation
Schema has to be created when the
application starts
So it will be done in the onCreate() method of
DBHelper
We will also need an onUpgrade() method
that we can call to alter the schema
Major Operations
Insert()
Query()
Update()
Delete()
Cursors
A query returns a set of rows, with a pointer
called cursor
We can retrieve results one at a time from the
cursor
An empty cursor means that you have
retrieved all the rows
SQL Exception
Anything done with SQL could lead to an SQL
exception
For example, database could be running out of
space or somehow corrupted
Its good practice to handle all SQLExceptions
by surrounding database calls in try/catch
blocks
Putting try/catch in eclipse
Update UpdaterService
We need to update the UpdaterService
Its the class that connects to Twitter and get
the latest timeline
However, currently it posts everything to
LogCat
But now it will be updated to insert the
timeline into the database
Verify that the Database Exist
If the database file was created successfully, it
will be located in
/data/data/com.marakana.yamba/databases/ti
meline.db
Database Constraints
You will see many SQLExceptions in the
LogCat, when your service runs for the second
time
It happens because of the duplicate IDs
We could check with the database that there
are no duplicates before insertion, however it
is more efficient to try to insert duplicates, fail
at it, and ignore the failure