Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

Smart

Application
Development
+
SQLiteDB
● Contract
● SQLiteDBHelper
● Cursor

2
+ SQLite
■ SQLite DB - Data organized as tables

■ Support for CRUD Operations using SQL


Queries
+

WeatherDBHelper

Weather Contract Content Provider


DB Helper
WeatherEntry
URI Matcher
LocationEntry SQLite
DB

Data Contract Content Provider


SQLite Database
+ Typical Methodology
■ Step 1: Define a Contract

■ Step 2: Create the DB

■ Step 3: CRUD Queries

■ Retrieve

■ Update

■ Add

■ Remove
+
What is a Contract?
Why do we need to create one?
Defines what DB design looks like! Contract is what two sides agree on!
+ Contract Class
■ A contract class

■ container for constants that define names for URIs,


tables, and columns.

■ The contract class allows you to use the same constants


across all the other classes in the same package.

■ This lets you change a column name in one place and have
it propagate throughout your code.
+ Organizing a Contract Class
■ A good way to organize a contract class is to put definitions that
are global to your whole database in the root level of the class.

■ Then create an inner class for each table that enumerates


its columns.
+

WeatherDBHelper

Weather Contract Content Provider


DB Helper
WeatherEntry
URI Matcher
LocationEntry SQLite
DB

Data Contract Content Provider


SQLite Database
+
User Interface
June 24 Cloudy 24 13
UI Element

COLUMN_DATE COLUMN_DESC COLUMN_MAX COLUMN_MIN

JUNE 24 CLOUDY 24 13

JUNE 25 SUNNY 26 12
+ ContactsContracts-ContactColumns
■ Display_Name

■ Has_Phone_Number

■ Photo_ID

■ Photo_File_ID

■ Photo_URI

■ Contact_Last_Updated_TimeStamp
+ Sample Contract
■ package com.fall2019.guestlistdemo;

import android.provider.BaseColumns;

public class WaitListContract {


public static final class WaitlistEntry implements BaseColumns {
public static final String TABLE_NAME = "waitlist";
public static final String COLUMN_GUEST_NAME = "guestName";
public static final String COLUMN_PARTY_SIZE = "partySize";
public static final String COLUMN_TIMESTAMP = "timestamp";
}
}
+ Sample Contract (Another Example)

■ Read More:
https://developer.android.com/training/basics/data- storage/dat
abases.html
+

WeatherDBHelper

Weather Contract Content Provider


DB Helper
WeatherEntry
URI Matcher
LocationEntry SQLite
DB

Data Contract Content Provider


SQLite Database
+ Create a Database Using a SQL Helper
■ Implement methods that create and maintain the database and tables.

■ final String SQL_CREATE_WAITLIST_TABLE = "CREATE TABLE " +


WaitListContract.WaitlistEntry.TABLE_NAME + " (" +
WaitListContract.WaitlistEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
WaitlistEntry.COLUMN_GUEST_NAME + " TEXT NOT NULL, " +
WaitlistEntry.COLUMN_PARTY_SIZE + " INTEGER NOT NULL, " +
WaitlistEntry.COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
"); ";
+ Example)
Create a Database Using a SQL Helper (Another
■ Implement methods that create and maintain the database
and
tables.
+ SQLiteOpenHelper
■ A helper class to manage database creation and version management
■ Use this class to obtain references to your database
■ the system performs the potentially long-running operations of
creating and updating the database only when needed and not
during app startup
■ onCreate(SQLiteDatabase db)Called when the database is created
for the first time.
■ Call
■ getWritableDatabase()
■ getReadableDatabase()

https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
+ Implementing a DB Helper
■ public class WaitlistDbHelper extends SQLiteOpenHelper {
// The database name

private static final String DATABASE_NAME = "waitlist.db";


// If you change the database schema, you must increment the database version
private static final int DATABASE_VERSION = 1;
// Constructor
public WaitlistDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
+ Implementing a DB Helper (Continues
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

// Create a table to hold waitlist data


sqLiteDatabase.execSQL(SQL_CREATE_WAITLIST_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// For now simply drop the table and create a new one. This means if you change the
// DATABASE_VERSION the table will be dropped.
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WaitlistEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}

}
+ Implementing a DB Helper (Another Example)
■ Demo: WaitListApp

23
+What should the Contract
Look Like?
+ DB Schema
+ Contract
public class WaitlistContract {

public static final class WaitlistEntry implements BaseColumns {


public static final String TABLE_NAME = "waitlist";
public static final String COLUMN_GUEST_NAME = "guestName";
public static final String COLUMN_PARTY_SIZE = "partySize";
public static final String COLUMN_TIMESTAMP = "timestamp";
}

By implementing the BaseColumns interface, your inner class can inherit a


primary key field called _ID that some Android classes such as cursor
adaptors will expect it to have. It's not required, but this can help your
database work harmoniously with the Android framework.
+
Creating a DB
The role of a DB Helper
+ Creating a DBHelper
public class WaitlistDbHelper extends SQLiteOpenHelper {

// The database name


private static final String DATABASE_NAME = "waitlist.db";

// If you change the database schema, you must increment the database version
private static final int DATABASE_VERSION = 1;

// Constructor
public WaitlistDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
The onCreate method is only called if there is no database.

+ onCreate!
public void onCreate(SQLiteDatabase sqLiteDatabase) {

// Create a table to hold waitlist data


final String SQL_CREATE_WAITLIST_TABLE = "CREATE TABLE " + WaitlistEntry.TABLE_NAME + " ("
+
WaitlistEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
WaitlistEntry.COLUMN_GUEST_NAME + " TEXT NOT NULL, " +
WaitlistEntry.COLUMN_PARTY_SIZE + " INTEGER NOT NULL, " +
WaitlistEntry.COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
"); ";

sqLiteDatabase.execSQL(SQL_CREATE_WAITLIST_TABLE);
}

In the end foreign key can be added like: +


“FOREIGN Key (“ WaitlistEntry.COLUMN_LOC_KEY + “) REFEREENCES “ +
LocationEntry.TABLE_NAME+ “ ( “ + LocationEntry._ID+ (“). “ +
…..
+ onUpgrade!
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// For now simply drop the table and create a new one. This means if you change the
// DATABASE_VERSION the table will be dropped.
// In a production app, this method might be modified to ALTER the table
// instead of dropping it, so that existing data is not deleted.

sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WaitlistEntry.TABLE_NAME);


onCreate(sqLiteDatabase);
}
+ Reading/Writing/Updating
Database
+ Reading/Writing/Updating Database
■ Get reference to writable database

■ Create ContentValues of what you want to insert

https://developer.android.com/reference/android/content/ContentValues
+ Reading/Writing/Updating Database
■ ContentValues cv = new ContentValues();

cv.put(WaitlistContract.WaitlistEntry.COLUMN_GUEST_NAME,
name);

cv.put(WaitlistContract.WaitlistEntry.COLUMN_PARTY_SIZE,
partySize);
+ Add a new Guest!
/**
* Adds a new guest to the mDb including the party count and the current timestamp
*
* @param name Guest's name
* @param partySize Number in party
* @return id of new record added
*/
private long addNewGuest(String name, int partySize) {
ContentValues cv = new ContentValues();
cv.put(WaitlistContract.WaitlistEntry.COLUMN_GUEST_NAME, name);
cv.put(WaitlistContract.WaitlistEntry.COLUMN_PARTY_SIZE, partySize);
return mDb.insert(WaitlistContract.WaitlistEntry.TABLE_NAME, null, cv);
}

https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
+ Insert
+ Reading/Writing/Updating Database
■ Get reference to writable database

■ Create ContentValues of what you want to insert

■ Insert ContentValues and get a row ID back

■ Query the database and receive a Cursor back

https://developer.android.com/reference/android/content/ContentValues
+ The Cursor
+ Reading Information from a Database
+

https://developer.android.com/reference/android/database/sqlite/SQLiteQueryBu ilder
+
+
+ Cursor movement
+ What will this method
return?
private Cursor guesswhatthisdoes() {
return
mDb.query( WaitlistContract.WaitlistEntry.TA
BLE_NAME, null,
null,
null,

null,

null,
WaitlistC
ontr
act.
Wait
listE
ntry.
COL
UM
N_T
IME
STA
MP
+ Get All Guests!
private Cursor getAllGuests() {
return
mDb.query( WaitlistContract.WaitlistEntry.TA
BLE_NAME, null,
null,
null,

null,

null,
WaitlistC
ontr
act.
Wait
listE
ntry.
COL
UM
N_T
IME
STA
MP
+ Select Query
■ Cursor ncursor= (Cursor) mDb.query(
WaitListContract.WaitlistEntry.TABLE_NAME,
new String[]{WaitListContract.WaitlistEntry.COLUMN_GUEST_NAME},
WaitListContract.WaitlistEntry._ID + "=" + guest_id,
null,

null,

null,
Wait
List
Con
tract
■ + {
public void show_guest(View view)

int guest_id= Integer.parseInt ( guestId.getText().toString() );


String name;
Cursor ncursor= (Cursor)
mDb.query( WaitListContract.WaitlistEntry.TA
BLE_NAME,
new String[]{WaitListContract.WaitlistEntry.COLUMN_GUEST_NAME},
WaitListContract.WaitlistEntry._ID + "=" + guest_id,
null,
null,
null,
WaitListC
ontr
act.
Wait
listE
ntry.
COL
UM
N_T
IME
STA
MP
);
+ Delete a guest!
// COMPLETED (1) Create a new function called removeGuest that takes l ong id as input and returns a
boolean
/**
* Removes the record with the specified id
*
* @param id the DB id to be removed
* @return True: if removed successfully, False: if failed
*/
private boolean removeGuest(long id) {
// COMPLETED (2) Inside, call mDb.delete to pass in the TABLE_NAME and the condition that
WaitlistEntry._ID equals id
return mDb.delete(WaitlistContract.WaitlistEntry.TABLE_NAME,
WaitlistContract.WaitlistEntry._ID + "=" + id, null) > 0;
}
+ Update
■ Updating the table combines the content values syntax
of
insert() with the where syntax of delete().
+ Persisting Database Connection
■ Since getWritableDatabase() and getReadableDatabase() are
expensive to call when the database is closed, you should
leave your database connection open for as long as you
possibly need to access it. Typically, it is optimal to close the
database in the onDestroy() of the calling Activity.
Quiz
+ Where is the
DB file stored?
+ Where the file is stored?
■ Just like files that you save on the device's internal storage
, Android stores your database in private disk space that's
associated application.

■ Your data is secure, because by default this area is not


accessible to other applications.
Tool for Managing SQLite
DBs
+ `

http://sqlitebrowser.org

You might also like