App Development for Smart Devices. Lec #4: Files, Saving State, and Preferences



Similar documents
Programming with Android: Data management. Dipartimento di Scienze dell Informazione Università di Bologna

getsharedpreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.

Persistent Data Storage. Akhilesh Tyagi

Programming Mobile Applications with Android

Android Persistency: Files

App Development for Smart Devices. Lec #4: Services and Broadcast Receivers Try It Out

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

Chapter 2 Getting Started

Android Services. Android. Victor Matos

TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION

AdFalcon Android SDK Developer's Guide. AdFalcon Mobile Ad Network Product of Noqoush Mobile Media Group

Now that we have the Android SDK, Eclipse and Phones all ready to go we can jump into actual Android development.

Programming Android applications: an incomplete introduction. J. Serrat Software Design December 2013

06 Team Project: Android Development Crash Course; Project Introduction

Introduction to Android SDK Jordi Linares

App Development for Smart Devices. Lec #2: Android Tools, Building Applications, and Activities

How to develop your own app

CSE476 Mobile Application Development. Yard. Doç. Dr. Tacha Serif Department of Computer Engineering Yeditepe University

Android Development. Marc Mc Loughlin

File System. /boot /system /recovery /data /cache /misc. /sdcard /sd-ext. Also Below are the for SD Card Fie System Partitions.

Mono for Android Activity Lifecycle Activity Lifecycle Concepts and Overview

Frameworks & Android. Programmeertechnieken, Tim Cocx

ELET4133: Embedded Systems. Topic 15 Sensors

Android Fundamentals 1

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

Mobile App Sensor Documentation (English Version)

Android Development Exercises Version Hands On Exercises for. Android Development. v

Mobile Application Development

Admin. Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources. Recap: TinyOS. Recap: J2ME Framework

Android Basics. Xin Yang

Introduction to Android. CSG250 Wireless Networks Fall, 2008

Getting Started: Creating a Simple App

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Login with Amazon Getting Started Guide for Android. Version 2.0

Beginner s Android Development Tutorial!

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

TomTom PRO 82xx PRO.connect developer guide

Android Environment SDK

Creating a List UI with Android. Michele Schimd

Tutorial #1. Android Application Development Advanced Hello World App

IOIO for Android Beginners Guide Introduction

Mobile Security - Tutorial 1. Beginning Advanced Android Development Brian Ricks Fall 2014

directory to "d:\myproject\android". Hereafter, I shall denote the android installed directory as

Developing Android Apps: Part 1

Android Environment SDK

Android Programming. Android App. Høgskolen i Telemark Telemark University College. Cuong Nguyen,

Getting Started with Android Programming (5 days) with Android 4.3 Jelly Bean

WRITING DATA TO A BINARY FILE

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

Using Extensions or Cordova Plugins in your RhoMobile Application Darryn

Advantages. manage port forwarding, set breakpoints, and view thread and process information directly

Android For Java Developers. Marko Gargenta Marakana

Android Studio Application Development

Android Application Development

Android Development. 吳 俊 興 國 立 高 雄 大 學 資 訊 工 程 學 系

Android on Intel Course App Development - Advanced

Objective. Android Sensors. Sensor Manager Sensor Types Examples. Page 2

Spring Design ScreenShare Service SDK Instructions

Developing for MSI Android Devices

Android app development course

HTTPS hg clone plugin library SSH hg clone plugin library

Android Framework. How to use and extend it

Lecture 1 Introduction to Android

CS 111 Classes I 1. Software Organization View to this point:

Introduction to NaviGenie SDK Client API for Android

Android Application Model

An Android-based Instant Message Application

Operating System Support for Inter-Application Monitoring in Android

Presenting Android Development in the CS Curriculum

Sending and Receiving Data via Bluetooth with an Android Device

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS170 Lab 11 Abstract Data Types & Objects

ANDROID APPLICATION FOR FILE STORAGE AND RETRIEVAL OVER SECURED AND DISTRIBUTED FILE SERVERS SOWMYA KUKKADAPU B.E., OSMANIA UNIVERSITY, 2010 A REPORT

Android Bootcamp. Elaborado (com adaptações) a partir dos tutoriais:

Introduction to Android Programming (CS5248 Fall 2015)

APPFORUM2014. Helping the developer community build next-generation, multi-platform apps. SCHAUMBURG, ILLINOIS SEPTEMBER 8-10

4. The Android System

Developing an Android App. CSC207 Fall 2014

Orders.java. ArrayList of Drinks as they are ordered. Functions to calculate statistics on Drinks

Advanced Java Client API

Università Degli Studi di Parma. Distributed Systems Group. Android Development. Lecture 2 Android Platform. Marco Picone

Advertiser Campaign SDK Your How-to Guide

GETTING STARTED WITH ANDROID DEVELOPMENT FOR EMBEDDED SYSTEMS

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Creating a 2D Game Engine for Android OS. Introduction

J a v a Quiz (Unit 3, Test 0 Practice)

Transcription:

App Development for Smart Devices CS 495/595 - Fall 2011 Lec #4: Files, Saving State, and Preferences Tamer Nadeem Dept. of Computer Science Some slides adapted from Stephen Intille

Objective Data Storage Shared Preferences Data Files Two design papers Case Studies (1-6) Presenter: Tony Chiou Case Studies (7-13) Presenter: Ashok Kumar Page 2 Fall 2011 CS 495/595 - App Development for Smart Devices

Saving data Your options (most complex apps use all) Shared Preferences Bundles Local files Local database (SQLite) Remote database Saving data obviously essential Page 3 Fall 2011 CS 495/595 - App Development for Smart Devices

Saving UI state Activity should save its user interface state each time it moves to the background Required due to OS killing processes Even if you think your app will be in the foreground all the time, you need to do this, because of... Phone calls Other apps The nature of mobile use Page 4 Fall 2011 CS 495/595 - App Development for Smart Devices

Saving other info Application preferences UI selections Data entry Page 5 Fall 2011 CS 495/595 - App Development for Smart Devices

Shared Preferences Page 6 Spring 2011 CS 752/852 - Wireless and Mobile Networking

Shared Preferences Simple, lightweight key/value pair (or name/value pair NVP) mechanism Support primitive types: Boolean, string, float, long and integer Shared among application components running in the same application context //Getting Context example public class MyActivity extends Activity { public void method() { Context actcontext = this; // since Activity extends Context Context appcontext = getapplicationcontext(); Context vwcontext = ((Button)findViewById(R.id.btn_id)).getContext(); } } Page 7 Fall 2011 CS 495/595 - App Development for Smart Devices

Using Shared Preferences Shared across an application s components, but are not available to other applications Caveat: they can be made available to multiple processes within same application, but be careful Stored as XML in the protected application directory on main memory (usually /data/data/<package name>/shared_prefs/<sp Name>.xml) Page 8 Fall 2011 CS 495/595 - App Development for Smart Devices

DDMS-File Explorer (Window > Open Perspective > Other... > DDMS) http://developer.android.com/guide/developing/debugging/ddms.html Page 9 Fall 2011 CS 495/595 - App Development for Smart Devices

Creating and Sharing Prefs public static String MY_PREFS = "MY_PREFS"; int mode = Activity.MODE_PRIVATE; SharedPreferences mysharedpreferences = getsharedpreferences(my_prefs, mode); SharedPreferences.Editor editor = mysharedpreferences.edit(); // Store new primitive types in the shared preferences object. editor.putboolean("istrue", true); editor.putfloat("lastfloat", 1f); editor.putint("wholenumber", 2); editor.putlong("anumber", 3l); editor.putstring("textentryvalue", "Not Empty"); // Commit the changes. editor.commit(); Page 10 Fall 2011 CS 495/595 - App Development for Smart Devices

Retrieving public static String MY_PREFS = "MY_PREFS"; public void loadpreferences() { // Get the stored preferences int mode = Activity.MODE_PRIVATE; SharedPreferences mysharedpreferences = getsharedpreferences(my_prefs, mode); } // Retrieve the saved values. boolean istrue = mysharedpreferences.getboolean("istrue", false); float lastfloat = mysharedpreferences.getfloat("lastfloat", 0f); int wholenumber = mysharedpreferences.getint("wholenumber", 1); long anumber = mysharedpreferences.getlong("anumber", 0); String stringpreference = mysharedpreferences.getstring("textentryvalue", ""); Page 11 Fall 2011 CS 495/595 - App Development for Smart Devices

Preference Activity System-style preference screens Familiar Can merge settings from other apps (e.g., system settings such as location) 3 parts Preference Screen Layout (XML) Extension of PreferenceActivity onsharedpreferencechangelistener Page 12 Fall 2011 CS 495/595 - App Development for Smart Devices

Preference Activity XML <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="my Preference Category"/> <CheckBoxPreference android:key="pref_check_box" android:title="check Box Preference" android:summary="check Box Preference Description" android:defaultvalue="true" /> </PreferenceCategory> </PreferenceScreen> Page 13 Fall 2011 CS 495/595 - App Development for Smart Devices

Preference Activity Options CheckBoxPreference EditTextPreference ListPreference RingtonePreference Page 14 Fall 2011 CS 495/595 - App Development for Smart Devices

Preference Activity Public class MyPreferenceActivity extends PreferenceActivity { @Override Public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); addpreferencesfromresource(r.xml.preferences); } } In manifest... <activity android:name=.mypreferenceactivity android:label= My Preferences > To start... Intent I = new Intent(this, MyPreferenceActivity.class); startactivityforresult(i, SHOW_PREFERENCES); Page 15 Fall 2011 CS 495/595 - App Development for Smart Devices

Using prefs from Pref. Activity Recorded shared prefs are stored in Application Context. Therefore, available to any component: Activities Services BroadcastReceiver Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // then Retrieve values using get<type> method Page 16 Fall 2011 CS 495/595 - App Development for Smart Devices

SP change listeners Run some code whenever a Shared Preference value is added, removed, modified Useful for Activities or Services that use SP framework to set application preferences Page 17 Fall 2011 CS 495/595 - App Development for Smart Devices

SP change listeners public class MyActivity extends Activity implements OnSharedPreferenceChangeListener { @Override public void oncreate(bundle SavedInstanceState) { // Register this OnSharedPreferenceChangeListener Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.registeronsharedpreferencechangelistener(this); } } public void onsharedpreferencechanged(sharedpreferences prefs, String key) { // TODO Check the shared preference and key parameters // and change UI or behavior as appropriate. } Page 18 Fall 2011 CS 495/595 - App Development for Smart Devices

Activity Local Preferences Only be used within the activity and can not be used by other components of the application. //Storing Local Preferences SharedPreferences preferences = getpreference(mode_private); SharedPreferences.Editor editor = preferences.edit(); editor.putint("storedint", storedpreference); // value to store editor.commit(); //Retrieving Local Preferences SharedPreferences preferences = getpreferences(mode_private); int storedpreference = preferences.getint("storedint", 0); // use the values Page 19 Fall 2011 CS 495/595 - App Development for Smart Devices

Bundles Page 20 Spring 2011 CS 752/852 - Wireless and Mobile Networking

Bundles Activities offer onsaveinstancestate handler Works like SharedPreferences Bundle parameter represents key/value map of primitive types that can be used save the Activity s instance values Bundle made available as a parameter passed in to the oncreate and onrestoreinstance method handlers Bundle stores info needed to recreate UI state Page 21 Fall 2011 CS 495/595 - App Development for Smart Devices

Saving Bundle @Override public void onsaveinstancestate(bundle savedinstancestate) { // Save UI state changes to the savedinstancestate. // This bundle will be passed to oncreate if the process is // killed and restarted. savedinstancestate.putboolean("myboolean", true); savedinstancestate.putdouble("mydouble", 1.9); savedinstancestate.putint("myint", 1); savedinstancestate.putstring("mystring", "Welcome back to Android"); // etc. } super.onsaveinstancestate(savedinstancestate); Page 22 Fall 2011 CS 495/595 - App Development for Smart Devices

Restoring Bundle @Override public void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); } // Restore UI state from the savedinstancestate. // This bundle has also been passed to oncreate. boolean myboolean = savedinstancestate.getboolean("myboolean"); double mydouble = savedinstancestate.getdouble("mydouble"); int myint = savedinstancestate.getint("myint"); String mystring = savedinstancestate.getstring("mystring"); Page 23 Fall 2011 CS 495/595 - App Development for Smart Devices

Data Files Page 24 Spring 2011 CS 752/852 - Wireless and Mobile Networking

Saving/loading files Biggest decision: location Local vs Remote Internal vs External Code is standard Java String FILE_NAME = "tempfile.tmp"; // Create a new output file stream that s private to this application. FileOutputStream fos = openfileoutput(file_name, Context.MODE_PRIVATE); // Create a new file input stream. FileInputStream fis = openfileinput(file_name); Page 25 Fall 2011 CS 495/595 - App Development for Smart Devices

Saving/loading files Can only write in current application folder (/data/data/<package_name>/files/<filename>) or external storage (e.g., /mnt/sdcard/<filename>) Exception thrown otherwise For external, must be careful about availability of storage card Behavior when docked Cards get wiped Page 26 Fall 2011 CS 495/595 - App Development for Smart Devices

Static files as resources Only good option for small files that NEVER change Otherwise, grab on the fly from net Put in res/raw folder Resources myresources = getresources(); InputStream myfile = myresources.openrawresource(r.raw.myfilename); Page 27 Fall 2011 CS 495/595 - App Development for Smart Devices

Handling SD Card Writing Permission (AndroidManifest.xml) <uses-permission android:name="android.permission.write_external_storage"> </uses-permission> Page 28 Fall 2011 CS 495/595 - App Development for Smart Devices

Check SD card! private static final String ERR_SD_MISSING_MSG = ERRSD cannot see your SD card. Please reinstall it and do not remove it."; private static final String ERR_SD_UNREADABLE_MSG = "CITY cannot read your SD (memory) card. This is probably because your phone is plugged into your computer. Please unplug it and try again."; public static String getsdcard() throws ERRSDException { if (Environment.getExternalStorageState().equals( Environment.MEDIA_REMOVED)) throw new ERRSDException(ERR_SD_MISSING_MSG); else if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) throw new ERRSDException(ERR_SD_UNREADABLE_MSG); File sdcard = Environment.getExternalStorageDirectory(); // /mnt/sdcard if (!sdcard.exists()) throw new ERRSDException(ERR_SD_MISSING_MSG); if (!sdcard.canread()) //for writing sdcard.canwrite() throw new ERRSDException(ERR_SD_UNREADABLE_MSG); } return sdcard.tostring(); Page 29 Fall 2011 CS 495/595 - App Development for Smart Devices

Other data storage options Later in the course: Local database (SQLite) If you need to perform queries on data Content Providers to share data External database Grab info on demand (or overnight) If you can rely on sporadic Internet connectivity Page 30 Fall 2011 CS 495/595 - App Development for Smart Devices

Questions? Page 31 Spring 2011 CS 752/852 - Wireless and Mobile Networking

TO DO Check your paper assignment on the class webpage 8-10 slides 15-20 minutes presentations Implement Sudoku in Ch. 4 (highly recommended) Project teams (team s name, team s member) due date: Friday Sep 16 th, 11:59pm Page 32 Fall 2011 CS 495/595 - App Development for Smart Devices