android
COIT20270 Application Development for Mobile Platforms Week 5: Displaying Pictures and Menus, Data Persistence
Dr. R. Balsys, CQU, 2016.
Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016
Week 5 – Displaying Pictures and Menus
Objectives, to :
use image views to display pictures
Use menu’s with views
Examine some additional views
2
CQU - COIT20270 Application Development for Mobile Platforms
Using Image Views to Display Pictures
You display images with ImageView, Gallery, ImageSwitcher and GridView views
An ImageView is used to display an individual image
The Gallery view displays images as a center-locked horizontally scrolling list of images
The ImageSwitcher view is used when you wish to apply animation or transitions when moving from one image to another
The GridView shows images as a two dimensional array of rows and columns of images
3
CQU - COIT20270 Application Development for Mobile Platforms
Using Menu’s With Views
There are two main types of menus in Android
Options menu – activated using the keyboard Menu button and it displays menus for the current activity
Context menu – displays information about the current view in an activity when the user taps and holds on the view
The way menu’s are created and handled in Android 6 and greater has changed and is different to that given in the text
4
CQU - COIT20270 Application Development for Mobile Platforms
4
The Menu XML file
An XML defining the menu items is added as an XML file to the projects res/menu folder
The menu items should be contained within
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
All menu items are defined within <item> </item> tags
As a minimum the item need the following options
android:id - identifier of the item
android:orderInCategory – the position of the item in the menu, higher goes first
android:title – the text of the menu item
5
CQU - COIT20270 Application Development for Mobile Platforms
5
The Menu Inflater
The onCreateOptionsMenu() is called when the Menu is drawn
Call getMenuInflater().inflate(R.menu.menu_main, menu);
and then return true;
You should replace menu_main with the name of the xml file you created your menu resource in
6
CQU - COIT20270 Application Development for Mobile Platforms
6
The onOptionsItemSelected method
The onCreateOptionsMenu() is called when the Menu is drawn
Call getMenuInflater().inflate(R.menu.menu_main, menu);
and then return true;
You should replace menu_main with the name of the xml file you created your menu resource in
7
CQU - COIT20270 Application Development for Mobile Platforms
7
Context Menu
To associate a context menu with a view you call the setOnCreateContextMenuListener() on the view
The item to associate the context menu with uses the setOnCreateContextMenuListener() to listen for any tap and holds on the view
You override the onCreateContextMenu() method and call your CreateMenu() method within it
8
CQU - COIT20270 Application Development for Mobile Platforms
Get student to Google epistemological
8
Data Persistence
Objectives, to :
Save and load data with user preferences
Persist data to files
Create and use databases
9
CQU - COIT20270 Application Development for Mobile Platforms
Saving and Loading User Preferences
To save data objects you can
Write the objects to a file
Save the object to a database
Use a SharedPreferences object
To use a SharedPreferences object you save a name/value pair to SharedPreferences and this is then saved into an XML file for you
10
CQU - COIT20270 Application Development for Mobile Platforms
Accessing Preferences in an Activity
You 1st need to create a myapppreferences.xml file to use for saving your data
Within this xml file you need to create key:value pairs for the data you wish to save
Create an activity that extends the PreferenceActivity class and call the addPreferencesFromResource() method to load the xml file containing the preferences
11
CQU - COIT20270 Application Development for Mobile Platforms
Retrieving and Modifying Preference Values
To make use of preferences you use the SharedPreferences class
The getSharedPreferences() method is used to get an instance of the SharedPreferences class using the name of the XML preferences file
You then create a SharedPreferences.Editor() object and use a putString() method to change the value of a string preference
To save the change to the XML file you use the commit() method
12
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the files working and discuss how they work
12
Changing the Default Name of a Preferences File
Using the PreferenceManager class you can call a getPreferenceManager() method and then set the instance of this to use a new name by calling the setSharedPreferenceName() and passing in the new name
13
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
13
Persisting Data to Files
To store data to files use the java.io package
You can write data to the devices internal store by
Writing text to a file using the FileOutputStream class and the openFileOutput() method with MODE_WORLD_READABLE (public read access), MODE_PRIVATE (private access), MODE_APPEND or MODE_WORLD_WRITEABLE (public write access)
To convert a character stream to a byte stream create a OutputStreamWriter instance using OutputStreamWriter() and then use the write() method to write to the file. Remember to flush() and close() the file
14
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
14
…Persisting Data to Files
You can read data from the devices internal store by
using the FileInputStream class and the openFileInput() passing the file name as an input parameter. Then use the instance of the FileInputStream to create a new InputStreamReader()
The input file is read in blocks of READ_BLOCK_SIZE bytes into a character array buffer you create. The read() method is used for this. read() returns -1 when the end of file is reached
15
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
15
Saving to External (SD card) Storage
Use the getExternalStorageDirectory() method to get a File object that points to your SD card’s path
To write to the SD card you then create a new directory using the previously found path using mkdirs()
You can then use the previously discussed FileOutputStream() method to write objects to the file
16
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
16
…Saving to External (SD card) Storage
To load data from the SD card use the path and filename approach used to write to the file and use a FileInputStream object instance along with an InputStream instance to read from the file
In order to write to a file you need to set the WRITE_EXTERNAL_STORAGE permission in your Android.Manifest file
17
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
17
Choosing a Storage Option
If you have data that can be represented using name:value pairs then use the SharedPreferences approach to store your data
If your data is not in easily put into name:value pairs and is not going to be shared with other apps then use internal storage to save your data
If your data is to be shared with other apps or users then use the SD card storage option
18
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
18
Using Static Resources
You can add files to your projects res/raw folder. These files are then usable in your app
Use the getResources() method to return a Resources object to get access to the file in res/raw
The resource ID is used to identify the required resource. It is the name of the file in res/raw without its extension
19
CQU - COIT20270 Application Development for Mobile Platforms
Creating and Using Databases
Using a relational database to store tables of data is efficient as database queries can be used to retrieve the data
Android uses the SQLite database system to provide access to a database, only to the app that created it
The created database is stored in the /data/data/<package_name>/databases folder
20
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the files working and discuss how they work
20
Creating a DBAdapter Helper Class
It is a good idea to create a helper class to create, open, close and use a SQLite database
A database has a name, tables and columns
You need to create constants to name the fields of your database
The DATABASE_CREATE constant contains the SQL statements for creating the table of the database
Within your DBAdapter class create a DatabaseHelper class that extends SQLiteOpenHelper
21
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
21
…Creating a DBAdapter Helper Class
Override the onCreate() method to create the new database
Override the onUpgrade() method for use when the database is upgraded
You then define methods to use for opening, closing and adding, deleting or updating rows in the table
Android uses the Cursor class to return values from queries
ContentValues object is used to store name:value pairs using its put() method
22
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
22
CRUD Operations on the Database
As an example we will look at adding contacts to the contacts database
Use the DBAdapter class to create a new instance of the DBAdapter class
To retrieve contacts in the contacts table use the getAllContacts() method. This returns a Cursor object.
You can use the moveToFirst() and moveToNext() methods to examine each contact in turn. The contact details are found by calling DisplayContact() on the cursor object
23
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
23
…CRUD Operations on the Database
To retrieve a single contact use its ID and call the getContact() method to get the details which is returned in a Cursor object
To update a contact call the updateContact() method passing the ID as the 1st parameter
To delete a contact use the deleteContact() method with the contact ID as the parameter
To upgrade a new database to a new one change the DATABASE_VERSION field in the DBAdapter class to a higher value than the old one. This deletes the old table, ready for the new table to be created from an existing one or otherwise
24
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
24
Pre-creating a Database
Often the database is pre-created at design time and used at run-time
Tools are used to create the initial database, such as that at sourceforge.net/projects/sqlitebrowser. This tool allows you to visually create the fields for the database and populate the fields with values
The database is copied into the assets folder of your project. When the application is created you copy the database in the assets folder into the /data/data/<project_name>/databases folder if it does not already exist. You can then use it as before
25
CQU - COIT20270 Application Development for Mobile Platforms
Demonstrate the file working and discuss how it works
25