Mobile and Ubiquitous Computing: Android Programming (part 4)

Similar documents
Spring Lecture 5 Lecturer: Omid Jafarinezhad

SharedPreferences Internal Storage External Storage SQLite databases

MOBILE APPLICATIONS PROGRAMMING

Android: Data Storage

The Basis of Data. Steven R. Bagley

Eng. Jaffer M. El-Agha Android Programing Discussion Islamic University of Gaza. Data persistence

Mobile Application Development Android

Mobile Application Development Android

CS371m - Mobile Computing. Persistence

CS378 -Mobile Computing. Persistence

07. Data Storage

Mobile Application Development Android

Data storage and exchange in Android

SAVING SIMPLE APPLICATION DATA

CSCU9YH: Development with Android

Distributed Systems 2011 Assignment 1

Mediensystemen mit Android

Automatically persisted among application sessions

Mobile Application Development MyRent Settings

Lecture 7: Data Persistence : shared preferences. Lecturer : Ali Kadhim Al-Bermani Mobile Fundamentals and Programming

Android Programming - Jelly Bean

SQLite. 5COSC005W MOBILE APPLICATION DEVELOPMENT Lecture 6: Working with Databases. What is a Database Server. Advantages of SQLite

Single Application Persistent Data Storage. CS 282 Principles of Operating Systems II Systems Programming for Android

Database Development In Android Applications

Distributed Systems Assignment 1

SharedPreference. <map> <int name="access_count" value="3" /> </map>

Answers to Exercises

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Software Practice 3 Today s lecture Today s Task

Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

Software Engineering Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 27, 2017

Lab 5 Periodic Task Scheduling

Services. service: A background task used by an app.

Starting Another Activity Preferences

How-to s and presentations. Be prepared to demo them in class. ons

Developing Android Applications Introduction to Software Engineering Fall Updated 1st November 2015

Computer Science Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 26, 2017

Android File & Storage

Required Core Java for Android application development

Distributed Systems Assignment 1

Communicating with a Server

32. And this is an example on how to retrieve the messages received through NFC.

ANDROID SYLLABUS. Advanced Android

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

COMP4521 EMBEDDED SYSTEMS SOFTWARE

An Android Studio SQLite Database Tutorial

CS378 -Mobile Computing. Services and Broadcast Receivers

Android" Application Development SAMS. Sams Teach Yourself. Shane Conder. Lauren Darcey. Second Edition

Basic UI elements: Defining Activity UI in the code. Marco Ronchetti Università degli Studi di Trento

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Mobile Programming Lecture 10. ContentProviders

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

Mobile Application Programing: Android. Data Persistence

CS 403X Mobile and Ubiquitous Computing Lecture 5: Web Services, Broadcast Receivers, Tracking Location, SQLite Databases Emmanuel Agu

Android Application Model I

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Introduction to Android

Mobile Programming Lecture 7. Dialogs, Menus, and SharedPreferences

The Broadcast Class Registration Broadcast Processing

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Upon completion of the second part of the lab the students will have:

SQLite Database. References. Overview. Structured Databases

Android Application Development Course 28 Contact Hours

OFFLINE MODE OF ANDROID

Android Essentials with Java

Android Specifics. Jonathan Diehl (Informatik 10) Hendrik Thüs (Informatik 9)

Multiple Activities. Many apps have multiple activities

10/27/17. Network Connec1on. Outline. Connect to the Internet. Connect to the Internet. Perform Network Operations. Perform Network Operations

CMSC436: Fall 2013 Week 3 Lab

EMBEDDED SYSTEMS PROGRAMMING Android Services

CORE JAVA& ANDROID SYLLABUS

Android Application Development

UI Fragment.

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Java Training Center - Android Application Development

Syllabus- Java + Android. Java Fundamentals

MOBILE APPLICATION DEVELOPMENT LECTURE 10 SERVICES IMRAN IHSAN ASSISTANT PROFESSOR

Android. Operating System and Architecture. Android. Screens. Main features

Software Engineering Large Practical: Accessing remote data and XML parsing. Stephen Gilmore School of Informatics October 8, 2017

Android/Java Lightning Tutorial JULY 30, 2018

AND-401 Android Certification. The exam is excluded, but we cover and support you in full if you want to sit for the international exam.

MC Android Programming

Android Connectivity & Google APIs

Writing Efficient Drive Apps for Android. Claudio Cherubino / Alain Vongsouvanh Google Drive Developer Relations

CS 528 Mobile and Ubiquitous Computing Lecture 4a: Fragments, Camera Emmanuel Agu

Lecture 2 Android SDK

Android App Development

An Overview of the Android Programming

PROFILE MANAGER ANDROID APPLICATION. A Project. Presented to the faculty of the Department of Computer Science

Overview of Frameworks: Part 3

CS 4518 Mobile and Ubiquitous Computing Lecture 6: Databases, Camera, Face Detection Emmanuel Agu

Software Engineering Large Practical: Preferences, storage, and testing

Hydrogen Car Mobile Display

CS 4330/5390: Mobile Application Development Exam 1

External Services. CSE 5236: Mobile Application Development Course Coordinator: Dr. Rajiv Ramnath Instructor: Adam C. Champion

Topics Covered in the Android Apps Development Training

Android Fundamentals - Part 1

Understanding Application

Transcription:

Mobile and Ubiquitous Computing: Android Programming (part 4) Master studies, Winter 2015/2016 Dr Veljko Pejović Veljko.Pejovic@fri.uni-lj.si Examples from: Mobile and Ubiquitous Computing Jo Vermeulen, University of Birmingham, UK

Data Storage SharedPreferences Internal storage External storage SQLite database

SharedPreference Preserve a small amount of primitive type (int, float, String, Boolean) data on a device Data are saved as key-value pairs Should be read/written by your app only Stored for as long as the app is installed on a device Common use: User preferences username, customisations, such as preferred WiFi AP, preferred theme, etc. Variables for conditional app execution When the app is launched for the first time set launched to True; next time, check if launched was set or not http://developer.android.com/reference/android/content/sharedpreferences.html

Accessing SharedPreferences Reading SharedPreferences settings = getapplicationcontext().getsharedpreferences( preferences, MODE_PRIVATE); boolean waslaunched = settings.getboolean( launched, false); Need to know the type of data: getboolean() getstring() getall() returns a Map of key-value pairs Always use MODE_PRIVATE

Accessing SharedPreferences Writing SharedPreferences settings = getapplicationcontext().getsharedpreferences( preferences, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putboolean( launched, true); editor.commit(); Different put methods for different data types Don t forget to commit!

PreferenceFragment A special Fragment that connects XML preference hierarchy with SharedPreferences <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android > <PreferenceCategory android:title="@string/inline_preferences"> <CheckBoxPreference android:key="checkbox_preference android:title="@string/title_checkbox_preference /> <EditTextPreference android:key="edittext_preference" android:title="@string/title_edittext_preference /> </PreferenceCategory> <PreferenceScreen/> public class PrefsFragment extends PreferenceFragment { @Override public void oncreate(bundle savedinstancestate{ super.oncreate(savedinstancestate); addpreferencesfromresource(r.xml.preferences); } } http://developer.android.com/reference/android/preference/preferencefragment.html

File Storage Android uses the common Java File API Files saved as internal or external files INTERNAL Always available. Files saved here are accessible by only your app by default. When the user uninstalls your app, the system removes all your app's files from internal storage. EXTERNAL Not always available a user can mount the external storage as USB storage World-readable, so files saved here may be read outside of your control. When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getexternalfilesdir().

Internal Files Find where to save files getfilesdir() an internal directory for your app getcachedir() an internal directory for your app's temporary cache files If the system begins running low on storage, it may delete these cache files Read/write methods FileOutputStream openfileoutput (String name, int mode) opens file for writing (creates it if needed) FileInputStream openfileinput (String name) opens a file for reading

External Files Check if the storage is mounted public boolean isexternalstoragewritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } Write to private external storage: getexternalfilesdir() Write to public external storage: getexternalstoragepublicdirectory()

External Files If written to public external storage your files remain on the device even after your app is uninstalled Use Environment class constants for storing files in appropriate directories File file = new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), albumname);

SQLite A relational database implementation for embedded systems A library added to an app, rather than a standalone client-served DB engine The whole database is kept in a single file, and a write operation gets an exclusive lock over the file (no concurrent writing) SQL-92 language standard implemented (mostly) Supports ACID transactions (Atomic, Consistent, Isolated and Durable)

SQLite Use Android s SQLite database for structured data, especially if SQL queries can be used for improved data presentation Key classes: SQLiteOpenHelper To create, open, modify the tables in the database SQLiteDatabase To query the database

SQLiteOpenHelper Subclass SQLiteOpenHelper for your database Define your schema - formal declaration of how the database is organized, and the SQL statements that you use to create your database Call super() from the subclass constructor to initialize the underlying database Execute database creation in oncreate() oncreate() of the helper is called when a component tries to access a not-yet-existing database SQLiteOpenHelper abstracts the costly DB creation operations, and does not run them when not needed

SQLiteOpenHelper Access the database via SQLiteOpenHelper: getreadabledatabase() getwritabledatabase() These operations may take some time, thus, run them on a background thread using AsyncTask or IntentService

SQLiteOpenHelper Example Use _id for the primary key

SQLiteOpenHelper Example Use in Activity:

SQLiteDatabase Insert into database by calling insert() with ContentValues key-value pairs Query the database with query() and rawquery()

SQLiteDatabase ListViews populated with Adapters connected to the database are often the most convenient way of displaying DB content

Examining DB Content Databases stored in /data/data/<package name>/databases/ Can examine database with sqlite3 # adb -s emulator-5554 shell # sqlite3 /data/data/ si.uni_lj.fri.lrss.databaseexample/databases/ contacts_db

Examining DB Content

Background Processing

Concurrency in Android Java Threads The most general method Service Runs work in the background, however, by default on the same thread as the UI IntentService Background work on a separate thread, to contact the UI use local broadcast AsyncTask Background work on a separate thread, but with a tight integration with the UI

IntentService Suitable for long running one-off tasks when we don t want to affect the UI responsiveness IntentService survives Activity lifecycle changes No need to cancel the service when Activity is rebuilt Called using explicit Intent Starts on demand handles each Intent in turn; stops itself when it runs out of work

IntentService Define in AndroidManifest.XML Extend the class in your Java code

Invoking IntentService Create an explicit Intent for your IntentService Use startservice() to start the IntentService Add additional data if needed with the extra field

Handling Results (1) ResultReceiver in your Activity Subclass ResultReceiver, implement onreceiveresult Pass ResultReceiver through Intent

Handling Results (1) ResultReceiver IntentService sends results to ResultReceiver in a Bundle with send() method Example Display location address h"p://developer.android.com/training/loca4on/display- address.html

Handling Results (2) Broadcast A different approach Subclass BroadcastReceiver in your Activity Broadcast from IntentService

AsyncTask For short, more interactive tasks Runs on a separate worker thread, but keeps a link with the main UI thread via: onpreexecute onprogressupdate onpostexecute Define what we want to do in the background in: doinbackground Start with YourTask().execute() AsyncTask <?,?,?>? param types for input, progress, output

h"ps://github.com/googlesamples/android- play- loca4on/tree/master/ac4vityrecogni4on AsyncTask Example Just before the task starts This is done in the background, and the status is communicated via publishprogress()

AsyncTask Example Connects with the UI thread Immediately after the task is finished