You are on page 1of 27

Minds-on: Android

Session 3

Paulo Baltarejo Sousa

Instituto Superior de Engenharia do


Porto

2016
Outline

Shared Preferences

SQLite Database

Android Adapter

Practice

Assignment

1 / 27
Shared Preferences

2 / 27
What are SharedPreferences?
• A SharedPreferences object points to a file containing
key,value pairs and provides simple methods to read and write
them.
• Each SharedPreferences file is managed by the framework and can
be private or shared.
• They are accessible from anywhere within the app to either put
data into the file or take data out of the file.
• For primitive data types: booleans, floats, ints, longs, and strings.
• They can be removed or cleared from:
Settings -> Applications ->
Manage applications -> (choose
your app) -> Clear data or
Uninstall
3 / 27
Where SharedPreferences should be used?
• Typically for small collection of data.
• In all situations where apps needs to save data about the
application state so that users progress is not lost.
• Example:
◦ In a game for saving user’s name, high score, and state of the game
when they logged off.
◦ Then the next time they log in, their score and game level would be
retrieved from the preference file and they would continue the game
from where they ended it when they logged off.

4 / 27
Get a Handle to a SharedPreferences
• You can create a new shared preference file or access an existing
one by calling one of two methods:
◦ getSharedPreferences: Use this if you need multiple shared
preference files identified by name
◦ getPreferences: Use this from an Activity if you need to use only
one shared preference file for the activity. Because this retrieves a
default shared preference file that belongs to the activity, you don’t
need to supply a name.

5 / 27
Get Shared Preferences
• If you need multiple files
Context context = getActivity () ;
S h a r e d P re fer enc es sharedPref = context . g e t S h a r e d P r e f e r e n c e s ( " MyPrefs " , Context .
MODE_PRIVATE ) ;

◦ The first parameter is the key and the second parameter is the
MODE.
• MODE APPEND: This will append the new preferences with the already
existing preferences
• MODE PRIVATE: By setting this mode , the file can only be accessed
using calling application
• ...: some modes allow others apps to read or to write the preferences.

• If you need just one shared preference file for your activity
S h a r e d P re fer enc es sharedPref = getActivity () . getPreferences ( Context . MODE_PRIVATE
);

6 / 27
Write to Shared Preferences
• Create a SharedPreferences.Editor by calling edit on your
SharedPreferences.
• Then call commit to save the changes.

/* ****** Create S h a r e d P r e f e r e n c e s ****** */


S h a r e d Pr efer enc es sharedPref = context . g e t S h a r e d P r e f e r e n c e s ( " MyPrefs " , Context .
MODE_PRIVATE ) ;
S h a r e d Pr efer enc es . Editor editor = sharedPref . edit () ;

/* * * * * * * * * * * * * * * * Storing data as KEY / VALUE pair * * * * * * * * * * * * * * * * * * */

editor . putBoolean ( " key_name1 " , true ) ; // Saving boolean - true / false
editor . putInt ( " key_name2 " , " int value " ) ; // Saving integer
editor . putFloat ( " key_name3 " , " float value " ) ; // Saving float
editor . putLong ( " key_name4 " , " long value " ) ; // Saving long
editor . putString ( " key_name5 " , " string value " ) ; // Saving string

// Save the changes in S h a r e d P r e f e r e n c e s


editor . commit () ; // commit changes

7 / 27
Read from Shared Preferences
• To retrieve values from a shared preferences file, call methods such
as getInt and getString, providing the key for the value you
want, and optionally a default value to return if the key is not
present.
• Checking if a particular preference exists (is set) or not using the
contains method on the SharedPreferences
/* ****** Create S h a r e d P r e f e r e n c e s ****** */
S h a r e d Pr efer enc es sharedPref = context . g e t S h a r e d P r e f e r e n c e s ( " MyPrefs " , Context .
MODE_PRIVATE ) ;
/* * * * * * * * * * * * * * * * Get S h a r e d P r e f e r e n c e s data * * * * * * * * * * * * * * * * * * */
// If value for key not exist then return second param value - In this case null
sharedPref . getBoolean ( " key_name1 " , null ) ; // getting boolean
sharedPref . getInt ( " key_name2 " , null ) ; // getting Integer
sharedPref . getFloat ( " key_name3 " , null ) ; // getting Float
sharedPref . getLong ( " key_name4 " , null ) ; // getting Long
sharedPref . getString ( " key_name5 " , null ) ; // getting String
/* * * * * * * * * * * * * * * * Checking S h a r e d P r e f e r e n c e s data * * * * * * * * * * * * * * * * * * */
boolean exists = sharedPref . contains ( " username " ) ;

8 / 27
Deleting keys and data
/* ****** Create S h a r e d P r e f e r e n c e s ****** */
S h a r e d Pr efer enc es sharedPref = context . g e t S h a r e d P r e f e r e n c e s ( " MyPrefs " , Context .
MODE_PRIVATE ) ;
S h a r e d Pr efer enc es . Editor editor = sharedPref . edit () ;

/* * * * * * * * * * * * Deleting Key value from S h a r e d P r e f e r e n c e s * * * * * * * * * * * * * * * * */

editor . remove ( " key_name3 " ) ; // will delete key k e y _ n a m e 3


editor . remove ( " key_name4 " ) ; // will delete key k e y _ n a m e 4

// Save the changes in S h a r e d P r e f e r e n c e s


editor . commit () ; // commit changes

/* * * * * * * * * * * * Clear all data from S h a r e d P r e f e r e n c e s * * * * * * * * * * * * * * * * */

editor . clear () ;
editor . commit () ; // commit changes

9 / 27
Commit changes
• In order to commit changes can be used two methods:
◦ apply
• This saves your data into memory immediately and saves the data to
disk on a separate thread. So there is no chance of blocking the main
thread (your app won’t hang).
• It is the preferred technique but has only been available since
Gingerbread (API 9, Android 2.3).
◦ commit
• Calling this will save the data to the file however, the process is carried
out in the thread that called it, stopping everything else until the save is
complete. It returns true on successful completion, false on failure.
• Use commit if you need confirmation of the success of saving your data
or if you are developing for pre-Gingerbread devices.
• It has been available since API 1

10 / 27
SQLite Database

11 / 27
What is SQLite Database?
• It is an open-source light weight relational database.
• It is used to store data in structured format.
◦ tables ”rows and columns”, indexes, and so on.
• It comes embedded within Android operating system.
• It is used by Android applications to store data in private database.
• Android provides a standard API to interact with SQLite database
from your Android application.
◦ Using the standard API you can create a database and tables and
perform CRUD ”create, read, update, delete” opertaions.
◦ Database created by an application will be accessible by name to any
class of that application, but not outside the application.
◦ Database files for an application can be found under
/data/data/[app-package]/databases/[db-name]
◦ To make your database data accessible to other applications use
Content Provider.
12 / 27
Android SQLite API (I)
• android.database.sqlite Package
◦ Contains the SQLite database management classes that an application
would use to manage its own private database.
• android.database.sqlite.SQLiteOpenHelper Class(abstract)
◦ A helper class to manage database creation and version management.
• It takes care of opening the database if it exists, creating it if it does
not, and upgrading it as necessary.
• android.database.sqlite.SQLiteDatabase Class
◦ Exposes methods to manage a SQLite database.
◦ SQLiteDatabase has methods to create, delete, execute SQL
commands, and others.
• android.content.ContentValues Class
◦ This class is used to store a set of key,value key=”table column”
value=”table record”
◦ Content Values are used to insert new rows into tables.
• Each ContentValues object represents a single table row as a map of
column names to values.
13 / 27
Android SQLite API (II)
• android.database.Cursor Class (interface)
◦ Database queries return Cursor objects that work like a pointer to
the result set.
• Cursors provide a methods that allow you to control your position (row)
in the result set returned by database queries.
• This interface provides random read-write access to the result set
returned by a database query.
◦ Some methods provided by Cursor:
• getCount: to get the number of records ”rows” returned in result set.
• moveToFirst & moveToNext: to move cursor to first or next row.
• isAfterLast: to check if you reach the end of the query result.
• getString(columnIndex): to get the value at current cursor position
from column number ”columnIndex” as String.
• close: to close the cursor.

14 / 27
DBAdapter
• A common practice is to create a class which interacts with the
SQLite database and also with the activities of the app.
• This class is called DBAdapter
◦ It contains all the necessary code for creating the tables and the
assigned fields.
◦ All of the operations regarding for inserting, updating, and deleting
records are in the DBAdapter.

15 / 27
Android Adapter

16 / 27
Adapters (I)
• Android’s Adapter is described in the API documentation, as ”a
bridge between an AdapterView and the underlying data for that
View”.
◦ An AdapterView is a group of View components in Android that
include the ListView, Spinner, and GridView.

17 / 27
Adapters (II)
• For showing a vertical list of scrollable items it must be used a
ListView which has data populated using an Adapter.
◦ The simplest adapter to use is called an ArrayAdapter because the
adapter converts an ArrayList of objects into View items loaded
into the ListView container.
...
ListView lv ;
ArrayList < String > list ;
ArrayAdapter < String > adapter ;
@Override
protected void onCreate ( Bundle sa ve d In s ta nc e St a te ) {
super . onCreate ( s a ve dI n st a nc eS t at e ) ;
setContentView ( R . layout . activity_main ) ;
lv = ( ListView ) findViewById ( R . id . listView ) ;
list = new ArrayList < String >() ;
String [] students = getResources () . getStringArray ( R . array . students ) ;
Collections . addAll ( list , students ) ;
adapter = new ArrayAdapter < String >( this , android . R . layout . simple_list_item_1
, list ) ;
lv . setAdapter ( adapter ) ;
...
18 / 27
Custom Adapter
• In order to display a series of items into a list using a custom
representation of the items:
◦ Create a custom XML layout for each row.
◦ Create a custom Adapter class, which could be a subclass of
BaseAdapter class.

19 / 27
Practice

20 / 27
Shared Preferences

21 / 27
SQLite & ListView Adapter

22 / 27
Assignment

23 / 27
Assignment (I)

• Update Database based app


with following functionalities:
◦ Add
◦ Delete
◦ Edit
◦ Search

24 / 27
Assignment (II)
• Add and Search, implemented as an Option Menu.

25 / 27
Assignment (III)
• Delete and Edit, implemented as a Context Menu.

26 / 27

You might also like