Pemograman Aplikasi Perangkat Bergerak
Pemograman Aplikasi Perangkat Bergerak
PERANGKAT BERGERAK
(LANJUT)
“
SQLite Database
K Candra Brata
andra.course@gmail.com
Mobille App Lab 2017-2018
SQLite Concept
Definition
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.
} finally {
cursor.close();
}
Implementing SQLite
Table Example
table_mahasiswa
_id nama nim
1 "alpha" "1234"
2 "beta" "5678"
3 "omega" "9999"
Basic Steps
// MahasiswaModel nama
static String NAMA = "nama";
// MahasiswaModel nim
static String NIM = "nim";
}
}
2. Subclass
SQLiteOpenHelper
…
}
2. Declare constants
for Database
@Override
public void onCreate(SQLiteDatabase db)
// Create the tables
db.execSQL(CREATE_TABLE_MAHASISWA);
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()
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
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 {
@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
}
public class MahasiswaModel {
}
4. Table Helper
Class (DML)
In SQLiteDatabase API, we can call method
query(), insert(), update(), delete() to manipulate our data.
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
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)
} while (!cursor.isAfterLast());
}
cursor.close();
return arrayList;
}
4. update()
}
4. delete()
● In MainActivity onCreate()
● In MainActivity onCreate()
mahasiswaHelper = new MahasiswaHelper(this);
● Call method of SQLiteOpenHelper
mahasiswaHelper.open();
mahasiswaHelper.getAllData();
mahasiswaHelper.close();
SQLite Transaction
Query Transaction
database.beginTransaction();
try {
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.
http://j.gs/18164083/papbl