SQLite DATABASE
SQLite DATABASE
SQLite DATABASE
SQLITE DATABASES
3. SQLITE Databases
Topics Covered
Overview of Storage in Android
Why sqlite
Sqlite classes
Storage class and data types
Database
• Create database
• Insert data into database
• Update and Delete data
Retrieve information
Get reference to database
Get data from the database(cursor)
Return records
Storage in Android
There are different ways to store data in android.
App-specific storage
Shared storage
Preferences
Databases
App specific storage: Store files that are meant for your app's use only,
either in dedicated directories within an internal storage volume or
different dedicated directories within external storage.
Use the directories within internal storage to save sensitive information
that other apps shouldn't access.
The directories include both a dedicated location for storing persisting files
and another location for storing cache data.
N.B you shouldn't use this storage to save anything that the user expects
to persist independently of your app
Cont’d
Shared storage: Store files that the app intends to share with other apps, including
media, documents, and other files.
The data can be accessible and saved even if the user uninstalls the app.
Android provides APIs for storing and accessing the following types of shareable
data:
Media Content: The system provides standard public directories for these kinds of
files, so the user has a common location for all their photos, another common
location for all their music and audio files. Our App can access this content using
MediaStore API.
Document and other files: The system has a special directory for containing other file
types, such as PDF documents and books that use the EPUB format. Your app can
access these files using the platform's Storage Access Framework.
Datasets: On Android 11 (API level 30) and higher, the system caches large datasets
that multiple apps might use. These datasets can support use cases like machine
learning and media playback.
Cont’d
Preferences: Store private, primitive data in key-value pairs. As the name
suggests, the primary purpose is to store user-specified configuration
details, such as user specific settings, keeping the user logged into the
application.
You build a settings screen for your app using the Preferences API. This
allows you to add individual preferences, and record a value for each
preference. These values are recorded in a shared preferences file for your
app. Data is lost
• on uninstalling the application
• on clearing the application data (through Settings)
Databases: we can Store structured data in a private database.
Overview (Sqlite)
Android uses SQLite databases to persist data.
Cursors
are what contain the result set of a query made against a database
in Android. It’s like a ResultSet in JDBC.
We’re going to use these objects to create SQLite database your app
can use to persist data
SQLite Helper
It’s an Android convention to call your primary key columns _id. Android
code expects there to be an _id column on your data. Ignoring this
convention will make it harder to get the data out of your database and
into your user interface.
The onCreate()method
db.delete("DRINK",
"NAME = ?",
new String[] {"Latte"});
Version control
The onCreate() method will make sure that all new users get the new
column.
The onUpgrade() method will make sure that all existing users get it too.
upgrade on the database can be taken due to
Change the database records. We may want to add more records
when you upgrade the database, or update or delete the records that
are already there.
Change the database structure. We may also want to add columns to
existing tables, rename tables, or remove tables completely.
E.g [update the structure of DB]
Class …. extends SQLiteOpenHelper{
private static final String DB_NAME = “Caffe"; // the name of our database
private static final int DB_VERSION = 2; // the version of the database
….(Context context){ ---------- Constructor
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
updateMyDatabase(db, 0, DB_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
Cont’d
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam", R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
}
Retrieve data
We will retrieve the information in the database by following these
procedures:
Get a reference to the database.
Create a cursor to read data from the database.
Return all the records from a table
Get a reference to the database
SQLiteOpenHelper databaseHelper = new DatabaseHelper(this);
You then call SQLite helper’s getReadableDatabase() or
getWritableDatabase() to get a reference to the database.
getReadableDatabase() is used if you need read-only access to the
database.
getWritableDatabase() method is used if you need to perform any
updates
SQLiteOpenHelper Helper = new DatabaseHelper(this);
try {
SQLiteDatabase db = Helper.getReadableDatabase();
//Code to read data from the database
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this,
"Database unavailable",
Toast.LENGTH_SHORT);
toast.show();
}
Cont’d
Create a cursor to read data from the database
A cursor lets you read from and write to the database. You specify what data
you want access to, and the cursor brings back the relevant records from the
database. You can then navigate through the records supplied by the
cursor.
You create a cursor using the SQLiteDatabase query() method:
Android uses the query() method to construct an SQL SELECT statement.
Next we see how to Update the column when check box is selected
ContentValues drinkValues = new ContentValues();
drinkValues.put("FAVORITE", favorite.isChecked());
//Get a reference to the database and update the FAVORITE column
SQLiteOpenHelper starbuzzDatabaseHelper = new
StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
db.update("DRINK",
drinkValues,
"_id = ?",
new String[] {Integer.toString(drinkId)});
db.close();
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable",
Toast.LENGTH_SHORT);
toast.show();
}
Exercise
Display the list view in main activity as favorite Drinks
When the item is clicked start detail Activity
What you observe when you go back to the main activity after you
uncheck the drink value?
Change cursor()
Cursors don’t automatically keep track of whether the underlying
data in the database has changed
Cursors retrieve data when the cursor gets created. So, we create
the cursor on the oncreate() method when the user navigate to
another activity it is stopped so the oncreate() method will not
recreated.
We have to change the cursor with changeCursor()
Define the cursor
Get reference to the cursor adapter: use getAdapter() method
Change the cursor using changeCursor() method.
@Override
public void onRestart() {
super.onRestart();
Cursor newCursor = db.query("DRINK",
new String[] { "_id", "NAME"},
"FAVORITE = 1",
null, null, null, null);
ListView listFavorites = (ListView) findViewById(R.id.list_favorites);
CursorAdapter adapter = (CursorAdapter) listFavorites.getAdapter();
adapter.changeCursor(newCursor);
Youroldcursor = newCursor;
}
AsyncTask
Database are very powerful, but they can be slow.
The Database needs to go searching for the database file, if it is not
available it needs to create it.
It needs to run all of the SQL commands {Creating tables, insert data
as well as retrieving data’s from db}
As a database gets bigger and bigger, the time to perform the
database operations will also increase.
We can increase our app responsiveness by using threads.
Since Lollipop, there are three kinds of threads you need to think
about:
Cont’d
The main event thread
This is the real workhorse in Android. It listens for intents, it receives
touch messages from the screen, and it calls all of the methods
inside your activities.
The render thread
You don’t normally interact with this thread, but it reads a list of
requests for screen updates and then calls the device’s low-level
graphics hardware to repaint the screen and make your app look
pretty.
Any other threads that you create
In order to increase the performance, move your database code
off the main event thread and run it in a custom thread in the
background.
In the Drink Activity Code
Choose the type of thread you think each should run on.
In the main thread or In the background thread
1) int drinkId = (Integer) 2)
getIntent().getExtras().get(EXTRA_DRINKID); SQLiteOpenHelper
CheckBox favorite = (CheckBox) starbuzzDatabaseHelper = new
findViewById(R.id.favorite); StarbuzzDatabaseHelper(this);
ContentValues drinkValues = new SQLiteDatabase db =
ContentValues(); starbuzzDatabaseHelper.getWriteableDat
drinkValues.put("FAVORITE", abase();
favorite.isChecked()); db.update("DRINK",...);
3)
Toast toast = Toast.makeText(...);
toast.show();
Async Task performs asynchronous
tasks
AsyncTask lets you perform operations in the background
After AsyncTask performs its task, then it allows you to update views
in the main event thread.
We will not publish the progress of our task. So the AsyncTask class
will have the form <Integer, Void, Boolean>
The onPostExecute() method
The onPostExecute() method is called after the background task has
finished.
It is called in main event thread, so it has access to views in the user
interface.
The result of the task can be presented in this method.
private class UpdateDrinkTask extends AsyncTask<Integer, Void,
Boolean> {
...
protected void onPostExecute(Boolean success) {
if (!success) {
Toast toast = Toast.makeText(DrinkActivity.this,
"Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
}
}
Execute the AsyncTask
You run the AsyncTask by calling the AsyncTask execute() method
and passing it any parameters required by the doInBackground()
method.