0% found this document useful (0 votes)
71 views47 pages

13 DataStorage

This document summarizes different data storage options in Android including Shared Preferences, internal files, SQLite database, and Room database. It provides details on implementing Shared Preferences to store key-value pairs and describes how to read and write to internal and external files. The document also explains basic SQLite operations like queries, updating and deleting rows, and using cursors to access query results. It provides examples of common SQLite queries and using the SQLiteOpenHelper class to manage databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views47 pages

13 DataStorage

This document summarizes different data storage options in Android including Shared Preferences, internal files, SQLite database, and Room database. It provides details on implementing Shared Preferences to store key-value pairs and describes how to read and write to internal and external files. The document also explains basic SQLite operations like queries, updating and deleting rows, and using cursors to access query results. It provides examples of common SQLite queries and using the SQLiteOpenHelper class to manage databases.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Data Storage

Contents
● Shared Preferences
● Internal/External Files
● Sqlite
● Room database
Shared Preferences
- Shared Preferences allows activities and applications to keep
preferences, in the form of key-value pairs
- Android stores Shared Preferences settings as XML file in
shared_prefs folder under DATA/data/{application package} directory
- To get access to the preferences, we have APIs:
- getPreferences() : used from within your Activity, to access activity-
specific preferences
- getSharedPreferences() : used from within your Activity (or other
application Context), to access application-level preferences
Shared Preferences
- Implement:
- getSharedPreferences (String PREFS_NAME, int mode)

PREFS_NAME is the name of the file.

mode is the operating mode.


Shared Preferences
- Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",
Context.MODE_PRIVATE);
Editor editor = pref.edit();

- Storing Data
Shared Preferences
- Retrieving Data

- Clearing or Deleting Data:


- remove(“key_name”) is used to delete that particular value.
- clear() is used to remove all data
File Storage
● External storage -- Public directories
● Internal storage -- Private directories for just your app

Apps can browse the directory structure


Structure and operations similar to Linux and java.io
File Storage
● Internal storage is best when
○ you want to be sure that neither the user nor other apps can access your
files
● External storage is best for files that
○ don't require access restrictions
○ you want to share with other apps
○ you allow the user to access with a computer
File Storage
● Internal Storage
○ Always available
○ Uses device's filesystem
○ Only your app can access files, unless explicitly set to be readable or
writable
○ On app uninstall, system removes all app's files from internal storage
File Storage
● External storage
○ Not always available, can be removed
○ Uses device's file system or physically external storage like SD card
○ World-readable, so any app can read

○ On uninstall, system does not remove files private to app


Using Internal Storage
● An activity has methods you can call to read/write files:
○ getFilesDir() - returns internal directory for your app
○ getCacheDir() - returns a "temp" directory for scrap files
○ getResources().openRawResource(R.raw.id) - read an input file from
res/raw/
○ openFileInput("name", mode) - opens a file for reading
○ openFileOutput("name", mode) - opens a file for writing
Using Internal Storage – Example 1
Using Internal Storage – Example 2
Using External Storage
● Must explicitly request permission
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />

● Methods to read/write external storage:


○ getExternalFilesDir("name") - returns "private" external directory for
your app with the given name
○ Environment.getExternalStoragePublicDirectory(name) - returns public
directory for common files like photos, music, etc.
External Storage – Example
External Storage - Checking if storage is available
Assignment
● In LoginActivity, using SharedPreference to handle:
○ If user has not login app, show LoginActivity
○ If user logined app, show HomeActivity
Sqlite database
● Store data in tables of rows and columns (spreadsheet…)
● Field = intersection of a row and column
● Fields contain data, references to other fields, or references to other
tables
● Rows are identified by unique IDs
● Column names are unique per table
Sqlite database
● Table

WORD_LIST_TABLE
_id word definition
1 "alpha" "first letter"
2 "beta" "second letter"
3 "alpha" "particle"
SQL basic operations
● Insert rows
● Delete rows
● Update values in rows
● Retrieve rows that meet given criteria
SQL Query
● SELECT word, description
FROM WORD_LIST_TABLE
WHERE word="alpha"
Generic
● SELECT columns
FROM table
WHERE column="value"

21
SELECT columns FROM table

● SELECT columns
○ Select the columns to return
○ Use * to return all columns

● FROM table—specify the table from which to get results

22
WHERE column="value"

● WHERE—keyword for conditions that have to be met

● column="value"—the condition that has to be met


○ common operators: =, LIKE, <, >

23
AND, ORDER BY, LIMIT

SELECT _id FROM WORD_LIST_TABLE WHERE word="alpha" AND


definition LIKE "%art%" ORDER BY word DESC LIMIT 1

● AND, OR—connect multiple conditions with logic operators


● ORDER BY—omit for default order, or ASC for ascending, DESC for
descending
● LIMIT—get a limited number of results

24
Sample queries

1 SELECT * FROM Get the whole table


WORD_LIST_TABLE

2 SELECT word, definition Returns


FROM [["alpha", "particle"]]
WORD_LIST_TABLE
WHERE _id > 2

25
More sample queries

3 SELECT _id FROM Return id of word alpha with


WORD_LIST_TABLE substring "art" in definition
WHERE word="alpha" AND [["3"]]
definition LIKE "%art%"
4 SELECT * FROM Sort in reverse and get first item.
WORD_LIST_TABLE Sorting is by the first column (_id)
ORDER BY word DESC [["3","alpha","particle"]]
LIMIT 1

26
Last sample query

5 SELECT * FROM Returns 1 item starting at position 2.


WORD_LIST_TABLE Position counting starts at 1 (not zero!).
LIMIT 2,1 Returns
[["2","beta","second letter"]]

27
rawQuery()

String query = "SELECT * FROM WORD_LIST_TABLE";


rawQuery(query, null);

query = "SELECT word, definition FROM WORD_LIST_TABLE


WHERE _id> ? ";

String[] selectionArgs = new String[]{"2"}


rawQuery(query, selectionArgs);

28
query()

SELECT * FROM String table = "WORD_LIST_TABLE"


WORD_LIST_TABLE String[] columns = new String[]{"*"};
WHERE word="alpha" String selection = "word = ?"
ORDER BY word ASC String[] selectionArgs = new String[]{"alpha"};
LIMIT 2,1; String groupBy = null;
String having = null;
Returns: String orderBy = "word ASC"
String limit = "2,1"
[["alpha", "particle"]]
query(table, columns, selection, selectionArgs, groupBy,
having, orderBy, limit);

29
Cursors
Queries always return a Cursor object
Cursor is an object interface that provides random read-write access to
the result set returned by a database query
⇒ Think of it as a pointer to table rows

30
Using sqlite
● SQLiteDatabase db = openOrCreateDatabase( "name", MODE_PRIVATE,
null); db.execSQL("SQL query");
● Methods:
○ – db.beginTransaction(), db.endTransaction()
○ – db.delete("table", "whereClause" , args)
○ – db.deleteDatabase(file)
○ – db.insert("table", null, values)
○ – db.query(...)
○ – db.rawQuery("SQL query", args)
○ – db.replace("table", null, values)
○ – db.update("table", values, "whereClause", args)
Using sqlite
● ContentValues can be optionally used as a level of abstraction for statements like
INSERT, UPDATE, REPLACE

ContentValues cvalues = new ContentValues();


cvalues.put("columnName1", value1);
cvalues.put("columnName2", value2);
...
db.insert("tableName", null, cvalues);
db.execSQL("INSERT INTO tableName (" + columnName1 + ", "
+ columnName2 + ") VALUES (" + value1 + ", " + value2 + ")");
Using sqlite
● SQLiteOpenHelper class provides the functionality to use the
SQLite database
Constructor Description
SQLiteOpenHelper(Context context, String creates an object for creating,
name, SQLiteDatabase.CursorFactory factory, opening and managing the
int version) database.
SQLiteOpenHelper(Context context, String creates an object for creating,
name, SQLiteDatabase.CursorFactory factory, opening and managing the
int version, DatabaseErrorHandler database. It specifies the error
errorHandler) handler.
Using sqlite
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is created for the first
time.

public abstract void onUpgrade(SQLiteDatabase called when database needs to be upgraded.


db, int oldVersion, int newVersion)

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase db, int called when database needs to be downgraded.
oldVersion, int newVersion)
Using sqlite
Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String nullColumnHack, ContentValues values) inserts a record on the database. The table specifies the table name,
nullColumnHack doesn't allow completely null values. If second argument is
null, android will store null values if values are empty. The third argument
specifies the values to be stored.

int update(String table, ContentValues values, String whereClause, updates a row.


String[] whereArgs)

Cursor query(String table, String[] columns, String selection, String[] returns a cursor over the resultset.
selectionArgs, String groupBy, String having, String orderBy)
Room database
● Room is a robust SQL object
mapping library

● Generates SQLite Android code


Room database
● Room works with DAO and
Entities LiveData
LiveData
RoomDatabase
Entity
● Entities define the database
schema SQLite DAO

● DAO provides methods to access


database
Using Room database
● Add library
● Create Entity
● Create DAO
● Create Database
Using Room database
● Add library

// Room components
    implementation "androidx.room:room-runtime:$rootProject.roomVersion"
    annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion"
    androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
Using Room database
● Create Entity
Using Room database
● Create DAO
Using Room database
● Create database
○ Create public abstract class extending RoomDatabase

○ Annotate as @Database

○ Declare entities for database schema


and set version number

@Database(entities = {Word.class}, version = 1)


public abstract class WordRoomDatabase extends RoomDatabase
Using Room database
Entity
@Database(entities = {Word.class}, version = 1)
defines
public abstract class WordRoomDatabase DB schema
extends RoomDatabase { DAO for
database
public abstract WordDao wordDao();
Create
private static WordRoomDatabase INSTANCE; database as
singleton
// ... create instance here instance
}
Using Room database
● Use Database builder
○ Use Room's database builder to create the database
○ Create DB as singleton instance

private static WordRoomDatabase INSTANCE;


INSTANCE = Room.databaseBuilder(...)
.build();
Room database creation example
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (WordRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.build();
}}}
return INSTANCE;
Classwork
● Create a database in sqlite, named “goods.db”
● Create a table, named “product”
Id ProductName Product Description ProductPrice
1 Laptop Abc… 20.000.000
2 Smartphone Xyz… 15.000.00
3 Headphone Kzz… 1000.000
● Load data into the recyclerview (slot 10)
● Create Insert/Update/Delete function for Product screen
References
● https://developer.android.com/codelabs/android-room-with-a-vie
w#0
● https://google-developer-training.github.io/android-developer-fun
damentals-course-concepts-v2/

You might also like