PENGEMBANGAN APLIKASI
PERANGKAT BERGERAK
(LANJUT)
“
SQLite Database
K Candra Brata
andra.course@gmail.com
Mobille App Lab 2017-2018
SQLite Concept
Definition
Android menyediakan salah satu mekanisme penyimpanan
data berulang yang dapat tersimpan secara terstruktur dan
berelasi dengan menggunakan SQLite.
SQLite hanya mendukung beberapa tipe data seperti
text, int, real. Jadi apabila ingin menyimpan data yang
tidak didukung oleh SQLite maka harus dilakukan
proses konversi tipe data yang sesuai dengan tipe
data yang didukung sebelum melakukan penyimpanan
data.
Using SQLite
database
Versatile and straightforward to implement
Structured data that you need to store persistently
Access, search, and change data frequently
Primary storage for user or app data
Cache and make available data fetched from the
cloud.
Data can be represented as rows and columns.
SQLite software
library
Implements SQL database engine that is
self-contained (requires no other components)
serverless (requires no server backend)
zero-configuration (does not need to be configured
for your application)
transactional (changes within a single transaction in
SQLite either occur completely or not at all)
SQLite
Transaction
A transaction is a sequence of operations performed as
a single logical unit of work.
A logical unit of work must have four properties
Atomicity
Consistency
Isolation
Durability
SQLite Transaction
(ACID)
Atomicity—All or no modifications are performed
Consistency—When transaction has completed, all data
is in a consistent state
Isolation—Modifications made by concurrent transactions
must be isolated from the modifications made by any
other concurrent transactions
Durability—After a transaction has completed, its effects
are permanently in place in the system
SQLite Table Operation
Table Example
table_mahasiswa
_id nama nim
1 "alpha" "1234"
2 "beta" "5678"
3 "omega" "9999"
Components of
SQLite database
SQLiteOpenHelper
SQLite database represented as an SQLiteDatabase
object.
All interactions with database through
SQLiteOpenHelper
Executes your requests
Manages your database
Separates data and interaction from app
Keeps complex apps manageable
Cursors
Data type commonly used for results of queries.
Pointer into a row of structured data ...
… think of it as an array of rows
Cursor class provides methods for moving cursor and
getting data .
SQLiteDatabase always presents results as Cursor
Cursor common
operations
getCount()—number of rows in cursor
getColumnNames()—string array with column names
getPosition()—current position of cursor
getString(int column), getInt(int column), ...
moveToFirst(), moveToNext(), ...
close() releases all resources and invalidates cursor
Cursors
Processing
Cursors
// Store results of query in a cursor
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
// Do something with data
} finally {
cursor.close();
}
Implementing SQLite
Table Example
table_mahasiswa
_id nama nim
1 "alpha" "1234"
2 "beta" "5678"
3 "omega" "9999"
Basic Steps
1.Create Database Contract
2.Subclass SQLiteOpenHelper
a.Create constants variable for tables
b.onCreate()—create SQLiteDatabase with tables
c. onUpgrade(), and optional methods
3.Create data model
4.Create Helper Class to Implement query(), insert(),
delete(), update(), count() in each Table.
5.In MainActivity, create instance of SQLiteOpenHelper
6.Call methods of SQLiteOpenHelper to work with
database
1. Database
Contract
Declare variable table name and column
Implement BaseColumns to automatically create “_id” column.
public class DatabaseContract {
static String TABLE_MAHASISWA = "table_mahasiswa";
static final class MahasiswaColumns implements BaseColumns
{
// MahasiswaModel nama
static String NAMA = "nama";
// MahasiswaModel nim
static String NIM = "nim";
}
}
2. Subclass
SQLiteOpenHelper
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Construct DatabaseHelper");
}
…
}
2. Declare constants
for Database
// It's a good idea to always define a log tag like this.
private static final String TAG =
DatabaseHelper.class.getSimpleName();
// has to be 1 first time or app will crash
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = “dbmahasiswa";
2. Define query for
creating database
You need a query to create the database (DDL)
Customarily defined as a string constant
public static String CREATE_TABLE_MAHASISWA = "create
table "+TABLE_MAHASISWA+
" ("+_ID+" integer primary key autoincrement, " +
NAMA+" text not null, " +
NIM+" text not null);";
2. onCreate()
@Override
public void onCreate(SQLiteDatabase db)
// Create the tables
db.execSQL(CREATE_TABLE_MAHASISWA);
// Add initial data (optional)
In the onCreate method, add code to create a database and the table (The helper class does not
create another database, if one already exists.)
2. onUpgrade()
onUpgrade( ) will be called if there are different DB
Version number or data migration.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_MAHASISWA);
onCreate(db);
}
}
Drop table tidak dianjurkan ketika proses migrasi terjadi dikarenakan data user akan hilang,.
SAVE DATA !!!
2. Optional
Methods
onDowngrade( )—default rejects downgrade
onConfigure( )—called before onCreate(). Only call
methods that configure the parameters of the database
connection
onOpen( )
2. DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "dbmahasiswa";
private static final int DATABASE_VERSION = 1;
public static String CREATE_TABLE_MAHASISWA = "create table "+TABLE_MAHASISWA+
" ("+_ID+" integer primary key autoincrement, " +
NAMA+" text not null, " +
NIM+" text not null);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_MAHASISWA);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*
Drop table tidak dianjurkan ketika proses migrasi terjadi dikarenakan data user akan
hilang,
*/
db.execSQL("DROP TABLE IF EXISTS "+TABLE_MAHASISWA);
onCreate(db);
}
}
3. Data Model
Class with getters and setters
One "item" of data (for database, one record or one row)
Make it Parcelable (optional).
public class MahasiswaModel {
private int id;
private String name;
private String nim;
...
}
public class MahasiswaModel {
3. Mahasiswa private int id;
private String name;
Model private String nim;
public MahasiswaModel(String name, String nim) {
this.name = name;
this.nim = nim;
}
public MahasiswaModel(int id, String name, String nim) {
this.id = id;
this.name = name;
this.nim = nim;
}
public String getNim() {
return nim;
}
public void setNim(String nim) {
this.nim = nim;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
4. Table Helper
Class (DML)
In SQLiteDatabase API, we can call method
query(), insert(), update(), delete() to manipulate our data.
To open connection to DB and invoke these methods,
instance SQLiteDatabase object from
getWritableDatabase() inside DatabaseHelper.
// Gets the data repository in write mode
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Use database convenience methods for insert, delete, and
update
4. insert()
long insert(String table, String nullColumnHack,
ContentValues values)
● First argument is the table name.
● Second argument is a String nullColumnHack.
○ Workaround that allows you to insert empty rows
○ Use null as default
● Third argument must be a ContentValues with values for the row
● Returns the id of the newly inserted item
4. insert()
ContentValues
● An instance of ContentValues
○ Represents one table row
○ Stores data as key-value pairs
○ Key is the name of the column
○ Value is the value for the field
● Used to pass row data between methods
4. insert() example
public long insert(MahasiswaModel mahasiswaModel){
ContentValues initialValues = new ContentValues();
initialValues.put(NAMA, mahasiswaModel.getName());
initialValues.put(NIM, mahasiswaModel.getNim());
return database.insert(TABLE_MAHASISWA, null, initialValues);
}
4. executing
queries
SQLiteDatabase.rawQuery()
Use when data is under your control and supplied only
by your app
SQLiteDatabase.query()
Use for all other queries
4. rawQuery()
rawQuery(String sql, String[] selectionArgs)
First parameter is SQLite query string
Second parameter contains the arguments
Only use if your data is supplied by app and under
your full control.
4. rawQuery()
String queryString = "SELECT * FROM " + TABLE_MAHASISWA +
" ORDER BY " + NAMA + " ASC " +
"LIMIT " + position;
cursor = database.rawQuery(queryString, null);
4. query()
query() can take and return any data type that UI
needs
Only support queries that your app needs
query (String table,
String[] columns, String selection,
String[] selectionArgs, String groupBy,
String having, String orderBy,String limit);
4. query() example
public ArrayList<MahasiswaModel> getAllData(){
Cursor cursor =
database.query(TABLE_MAHASISWA,null,null,null,null,null,_ID+ " DESC",null);
cursor.moveToFirst();
ArrayList<MahasiswaModel> arrayList = new ArrayList<>();
MahasiswaModel mahasiswaModel;
if (cursor.getCount()>0) {
do {
mahasiswaModel = new MahasiswaModel();
mahasiswaModel.setId(cursor.getInt(cursor.getColumnIndexOrThrow(_ID)));
mahasiswaModel.setName(cursor.getString(cursor.getColumnIndexOrThrow(NAMA)));
mahasiswaModel.setNim(cursor.getString(cursor.getColumnIndexOrThrow(NIM)));
arrayList.add(mahasiswaModel);
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
cursor.close();
return arrayList;
}
4. update()
int update(String table, ContentValues values,
String whereClause, String[] whereArgs)
First argument is table name
Second argument must be ContentValues with new values for the row
Third argument is WHERE clause
Fourth argument are the arguments to the WHERE clause
4. update()
Example
public int update(MahasiswaModel mahasiswaModel){
ContentValues args = new ContentValues();
args.put(NAMA, mahasiswaModel.getName());
args.put(NIM, mahasiswaModel.getNim());
return database.update(TABLE_MAHASISWA, args, _ID + "= '" + mahasiswaModel.getId() + "'", null);
}
4. delete()
int delete (String table, String whereClause, String[] whereArgs)
First argument is table name
Second argument is WHERE clause
Third argument are arguments to WHERE clause
4. delete() example
public int delete(int id){
return database.delete(TABLE_MAHASISWA, _ID + " = '"+id+"'", null);
}
5. Instantiate
OpenHelper
● In MainActivity onCreate()
mahasiswaHelper = new MahasiswaHelper(this);
6. Work with database
OpenHelper
● In MainActivity onCreate()
mahasiswaHelper = new MahasiswaHelper(this);
● Call method of SQLiteOpenHelper
mahasiswaHelper.open();
mahasiswaHelper.getAllData();
mahasiswaHelper.close();
SQLite Transaction
Query Transaction
Use transactions when performing multiple operations that all need to
complete to keep database consistent.
Use to batch multiple independent operations to improve
performance.
Example : insert multiple data in one time execution.
Transaction
common structure
database.beginTransaction();
try {
... // your process
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
Code Lab
Implementation
Tugas 1
Buat Apliaksi Native android dengan
memanfaatkan SQLite sebagai media
penyimpanan.
Minimal 2 Table
Tiap Table min 3 kolom.
Skenario Aplikasi bebas.
Proses CRUD harus bisa di semua table.
Harus ada Feature Search.
Thanks!
JOIN !!
http://j.gs/18164083/papbl