Download Word - FIS Incorporated

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Android Programming Notes
Document description...................................................................................................... 1
Example Code Implementations ...................................................................................... 1
Event Bus........................................................................................................................ 1
Fragment Method Calls Relating to Adding/Removing Fragments................................... 1
Order of Activity and Fragment Calls ............................................................................... 2
Menu items not showing in action bar ............................................................................. 3
Supporting different screen sizes .................................................................................... 4
Android Verisons ............................................................................................................. 7
Different ways to get data directories .............................................................................. 7
Colors ............................................................................................................................. 8
Android Asset Studio ....................................................................................................... 8
Buttons (With gradients) .................................................................................................. 8
Creating new ActionBar styles ......................................................................................... 8
Organization of Styles and Themes................................................................................. 9
Styles........................................................................................................................... 9
Themes ..................................................................................................................... 10
Themes based on Platform ........................................................................................ 11
Activity/Fragment lifecycle ............................................................................................. 11
Android Source Code .................................................................................................... 11
Actionbar Icon sizes ...................................................................................................... 11
Icon Sizes ..................................................................................................................... 12
Acronyms ...................................................................................................................... 12
Android Tools ................................................................................................................ 12
ADB – Android Debug Bridge ........................................................................................ 13
Commonly Used Packages for Android ......................................................................... 13
Logging Support ............................................................................................................ 13
Android Program Language Terminology ...................................................................... 14
Anatomy of an Activity ................................................................................................... 14
The Intent of the Intent .................................................................................................. 15
Using Intents with an Activity ......................................................................................... 15
Intents with Menus and Drilldowns ................................................................................ 16
Broadcasting and Receiving Intents .............................................................................. 16
Services ........................................................................................................................ 16
Resource Files and Suggested Names ......................................................................... 16
Views ............................................................................................................................ 19
Attributes ....................................................................................................................... 22
Styles ............................................................................................................................ 22
Themes ......................................................................................................................... 23
Other code snippets ...................................................................................................... 23
File Locations ................................................................................................................ 28
Launching ADB in command window ............................................................................ 28
Menus ........................................................................................................................... 29
SQLite ........................................................................................................................... 30
SQLite Commands .................................................................................................... 31
SQLite SQL Examples ............................................................................................... 31
SQLite/Android/JDBC methods.................................................................................. 32
Sample Code to Use Database in Application............................................................ 34
Contacts Database .................................................................................................... 38
General ContentProvider Setup .................................................................................... 39
The Emulator and DDMS .............................................................................................. 40
Toggling Emulator Orientation between Portrait and Landscape................................ 40
Android Programming Notes
Emulator files ............................................................................................................. 40
Defining SD Card ....................................................................................................... 40
Non-Writeable SD Card in emulator ........................................................................... 40
Putting images on emulator SD Card ......................................................................... 40
Push/Pull Files to Emulator ........................................................................................ 41
Seeing SDCard contents in emulator ......................................................................... 41
Getting Google Maps to work in emulator. ................................................................. 41
Android folders .............................................................................................................. 41
Sending a broadcast via adb ......................................................................................... 42
Memory Analyzer .......................................................................................................... 42
Exerciser Monkey .......................................................................................................... 42
Monkeyrunner ............................................................................................................... 43
Using Google API’s in app............................................................................................. 43
Uploading App to GooglePlay Store .............................................................................. 43
FaceBook API install ..................................................................................................... 43
Converting an Activity to a Activity/Fragment ................................................................ 45
Android Programming Notes
Document description
This document contains various items I felt worth noting as I went through Android
books, websites, programming exercises and developing my own Android code. There
are no claims to accuracy but just what I thought was true and important at the time I
made the notes.
Example Code Implementations
Project
ActivityTracker
ActivityTracker
Class
SQLiteCursorLoader
ActivityPager
Contains code for
AsynTaskLoader<Cursor>
ViewPager
SQLiteCursorLoader
LoaderCallbacks<Cursor>
ActivityTracker
TrackerDatabaseHelper
SQLiteOpenHelper
ActivityTracker
TrackerDatabase
SQL Table definitions and SQL
ActivityTracker
ActivityLoggerFragment
Broadcast receiver
ActivityTracker
GPSLocationManager
Broadcast receiver for location
updates
Broadcast location update record
LanguageLesson LanguageSettings
Shared preferences
LanguageLesson LanguageApplication
Subclassed Application to get
daoMaster and daoSession
LanguageLesson LanguageMaintenanceService IntentService
LanguageLesson LanguagePhraseLoader
HandlerThread
LanguageLesson LanguagePhrasePlayer
HandlerThread
MediaPlayer
LanguageLesson MediaPlayerFragment
MediaPlayer
LanguageLesson YouTubeLessonFragment
YouTubePlayerSupportFragment
LanguageLesson MasterActiviyt
Create/display search option based
on Android version
LanguageLesson SearchResultFragment
Text Search within app database
Event Bus
See http://square.github.io/otto/
Fragment Method Calls Relating to Adding/Removing Fragments
Add fragment
onAttach
onCreate
onCreateView
onStart
onResume
D:\582694522.doc
Remove fragment
onPause
onStop
onDestroyView
onDestroy
onDetach
Attach fragment
onCreateView
onStart
onResume
1
Detach fragment
onPause
onStop
onDestroyView
Android Programming Notes
Android persists the Fragment layout and associated back stack when an Activity is restarted
due to a configuration change
Order of Activity and Fragment Calls
See http://www.silverbaytech.com/2014/03/24/android-fragment-lifecycle-in-detail/
The following provides a general overview, some subtleties may not be noted.
When an Activity and Fragment are being created ‘at the same time’
Activity
Activity constructor
onCreate()
and before setContentView() completes
Fragment
Fragment constructor
OnAttach (Activity) associate the fragment with
the activity (the activity may not be fully
initialized)
onCreate(Bundle) Init the fragment
onCreateView(LayoutInflater, ViewGroup,
Bundle) return view associated with fragment
setContentView() completes along with
remaining part of onCreate()
onStart() and within it super.onStart()
onActivityCreated(Bundle) trigger to coincide
with activity onCreate method
onViewStateRestored()
onStart() trigger to coincide with activity’s
onStart method
onStart() super.onStart() returns
onRestoreInstanceState() on orientation
change
onResume()
onResume() triggered to coincide with activity’s
onResume() method
onPause() and super.onPause()
onPause() triggered to coincide with activity’s
onPause() method or when fragment operation
is modifying it
onPause() super.onPause() completes
onSaveInstanceState() and
super.onSaveInstanceState() on orientation
change
onSaveInstanceState()
onSaveInstanceState()
super.onSaveInstanceState() completes
onStop() and super.onStop()
onStop() triggered to coincide with activity’s
onStop() method or when fragment operation is
modifying it
D:\582694522.doc
2
Android Programming Notes
onStop() super.onStop() completes
onDestroy() and super.onDestroy()
onDestroyView() release any resources
associated with its view
onDestroy() release any final resources
onDetach() last change to process prior to
being detached from activity
onDestroy() super.onDestroy() completes
Adding a Fragment to, and removing from an Activity
Activity
Fragment
Fragment constructor
Fragment added to activity via
FragmentTransaction, FragmentTransaction is
then committed
Asynchronous calls to
OnAttach (Activity) associate the fragment with
the activity
onCreate(Bundle) Init the fragment
onCreateView(LayoutInflater, ViewGroup,
Bundle) return view associated with fragment
onStart()
onResume
Fragment removed from Activity via a
Fragment transaction, FragmentTransaction is
then committed
Asynchronous calls to
onPause()
onStop()
onDestroyView() release any resources
associated with its view
onDestroy() release any final resources
onDetach() last change to process prior to
being detached from activity
Add existing fragment back to Activity
Calls on device rotation (added to first table)
Menu items not showing in action bar
You need additional namespace and also use the namespace on showAsAction parm. In
the example below the namespace is:
xmlns:app="http://schemas.android.com/apk/res-auto"
and the make sure you use app:showAsAction
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
D:\582694522.doc
3
Android Programming Notes
android:id="@+id/select_teacher_class_lesson"
android:title="@string/select_class_lesson"
app:showAsAction="ifRoom|withText">
</item>
</menu>
Supporting different screen sizes
http://developer.android.com/guide/practices/screens_support.html#NewQualifiers
http://developer.android.com/guide/topics/resources/providingresources.html#AlternativeResources
Qualifiers for both layouts and drawables (Android version up to but not including 3.2)
Size
small
Small screens
normal
Baseline (default)
large
Large
xlarge
Extra large (generally used for 7in
tables running Android 3.0 or 3.1)
Density
ldpi
mdpi
hdpi
xhdpi
nodpi
tvdpi
~120dpi
~160dpi (baseline)
~240dpi
~320dpi
For all densities, system does not
scale resources (drawables) tagged
with this qualifier
Somewhere between mdpi and hpdi, ~
213dpi.
Orientation land
port
Landscape orientation
Portrait orientation
Aspect
ration
Resources for screens with
significantly taller or wider aspect
ration (when in either portrait or
landscape orientation) than baseline
Resources for screens that have
aspect ration similar to baseline screen
configuration
long
notlong
Folder
layout
layout-small
layout-normal
D:\582694522.doc
Approx. screen size
(at least)
Default – used if no
layout defined in
other folders
426dp x 320dp
470dp x 320dp
4
Android Programming Notes
layout-large
layout-xlarge
640dp x 480dp
960dp x 720dp
3.2 and later (above formats deprecated)
Name
Min screen size
wXXXdp
Minimum available width in dp units where width >= XXX dp.
The corresponding system width changes when the orientation
changes (Can be used in place of using screen size and
orientation qualifiers together)
hXXXdp
Available height where height in dp units >= XXX dp. The
corresponding system width changes when the orientation
changes (Can be used in place of using screen size and
orientation qualifiers together). But since apps can use scrolling
this is generally not used.
swXXXdp
Smallest width where height or width(whichever is smaller) >=
XXX dp. The system value does not change on orientation
change.
Generally for a 7in tablet you would have layouts in res/layoutsw600dp/…
10 in tablet layouts would be in something like res/layoutsw720dp/…
So depending on the version of Android you may create layouts similar to
Version
<3.2
Screen Size
Layout
For 1.6 or above. There are also additional API’s for 3.2 and above
Screen size by diagonal – Android groups them by small, medium, large, extra large
Screen density – Android groups them by low, medium, high, extra high
Orientation – landscape vs portrait. Different manufactures may use different defaults
Resolution – total pixels on screen. But apps should only be concerned with screen size
and density
Density-independent pixel (dp or dip) – A virtual pixel and is equivalent to one physical
pixel on a 160 dpi screen. The conversion of dp units to screen pixels is : px = dp * (dpi /
160). Note:dpi is dots per inch On 240dpi screen, 1dp equals 1.5 physical pixels.
Always us dp when defining the apps UI.
The baseline configuration that is a normal size and mdpi (medium) density.
D:\582694522.doc
5
Android Programming Notes
In general (rule of thumb only)

xlarge screens are at least 960dp x 720dp

large screens are at least 640dp x 480dp

normal screens are at least 470dp x 320dp

small screens are at least 426dp x 320dp
Layouts and drawables (up to but not including 3.2)
res/layout/my_layout.xml
("default")
res/layout-small/my_layout.xml
res/layout-large/my_layout.xml
res/layout-xlarge/my_layout.xml
size
res/layout-xlarge-land/my_layout.xml
landscape orientation
// layout for normal screen size
res/drawable-mdpi/my_icon.png
res/drawable-hdpi/my_icon.png
res/drawable-xhdpi/my_icon.png
// bitmap for medium density
// bitmap for high density
// bitmap for extra high density
// layout for small screen size
// layout for large screen size
// layout for extra large screen
// layout for extra large in
For tablets running 3.2 or higher
The new technique is based on the amount of space your layout needs (such as 600dp
of width), rather than trying to make your layout fit the generalized size groups (such
as large or xlarge).
Technically a 7 in screen is in the same group as a 5 in screen (both in the ‘large’ group)
but the 7in screen has significantly more space. So specify your layout resources based
on the width and/or height that's actually available for your application's layout, specified
in dp units.
Beginning with Android 3.2 (API level 13), the above size groups are deprecated and
you should instead use the sw<N>dp configuration qualifier to define the smallest
available width required by your layout resources. For example, if your multi-pane
tablet layout requires at least 600dp of screen width, you should place it in layoutsw600dp/.
D:\582694522.doc
6
Android Programming Notes
See the link for the complete list of configuration qualifiers for the various screen
orientations and sizes
Android Verisons
https://source.android.com/source/build-numbers.html
Code nme
Version
API level
(no code name)
1.0
API level 1
(no code name)
1.1
API level 2
Cupcake
1.5
API level 3, NDK 1
Donut
1.6
API level 4, NDK 2
Eclair
2.0
API level 5
Eclair
2.0.1
API level 6
Eclair
2.1
API level 7, NDK 3
Froyo
2.2.x
API level 8, NDK 4
Gingerbread
2.3 - 2.3.2
API level 9, NDK 5
Gingerbread
2.3.3 - 2.3.7
API level 10
Honeycomb
3.0
API level 11
Honeycomb
3.1
API level 12, NDK 6
Honeycomb
3.2.x
API level 13
Ice Cream Sandwich
4.0.1 - 4.0.2
API level 14, NDK 7
Ice Cream Sandwich
4.0.3 - 4.0.4
API level 15, NDK 8
Jelly Bean
4.1.x
API level 16
Jelly Bean
4.2.x
API level 17
Jelly Bean
4.3.x
API level 18
KitKat
4.4 - 4.4.3
API level 19
Different ways to get data directories
http://stackoverflow.com/questions/21216943/how-to-access-getfilesdir-as-anenvironment-variable
Environment.getDataDirectory()
returns the part of the data directory common to all
apps. For example, the /data/data.
D:\582694522.doc
7
Android Programming Notes
Environment.
getExternalStorageDirectory();
refers to whatever the device manufacturer
considered to be "external storage"
(Context). getFilesDir()
Returns the internal data directory related to the
apps package name
/data/data/com.fisincorporated.language
tutorial/files
getExternalFilesDir(null)
Returns external data directory related
to the apps package name
/storage/sdcard/Android/data/com.fisinc
orporated.languagetutorial/files
(Context)
/storage/sdcard/Android/data/com.fisinc
orporated.languagetutorial/files/Music
(Context)
getExternalFilesDir(Environmen
t.DIRECTORY_MUSIC)
Colors
A good place to get color values, e.g. #4d90fe, or to see what color a value is
http://www.w3schools.com/tags/ref_colorpicker.asp
See also
http://www.w3schools.com/tags/ref_colornames.asp
For 8 digit numbers #AARRGGBB, the AA is alpha or transparency FF is solid, 00 is
transparent
Android Asset Studio
A website to help create icons, themes, colored buttons, spinners, etc.
http://romannurik.github.io/AndroidAssetStudio/
Buttons (With gradients)
http://angrytools.com/
http://www.mindfreakerstuff.com/2012/09/50-useful-android-custom-button-style-set-1/
Creating new ActionBar styles
See http://jgilfelt.github.io/android-actionbarstylegenerator/ (also linked from
Android asset studio) to create action bar styles. This includes tabs, menu items,
spinners selected/non selected.
D:\582694522.doc
8
Android Programming Notes
You can change the theme (light, dark, light_dark) and past from &actionbarstyle to see
what the various base themes look like with the selected colors
Used for LanguageLesson
StyleName: LanguageLessonStyle1 (green menu)
http://jgilfelt.github.io/androidactionbarstylegenerator/#name=LanguageLessonStyle1&compat=appcompat&theme=li
ght_dark&actionbarstyle=solid&texture=0&hairline=0&neutralPressed=1&backColor=00f
%2C100&secondaryColor=33b5e5%2C100&tabColor=000%2C100&tertiaryColor=9c0%
2C100&accentColor=cbe533%2C100&cabBackColor=33b5e5%2C100&cabHighlightCol
or=33B5E5%2C100
StyleName: LanguageLessonStyle1 (blue menu)
http://jgilfelt.github.io/androidactionbarstylegenerator/#name=LanguageLessonStyle1&compat=appcompat&theme=li
ght_dark&actionbarstyle=solid&texture=0&hairline=0&neutralPressed=1&backColor=00f
%2C100&secondaryColor=33b5e5%2C100&tabColor=000%2C100&tertiaryColor=33b5
e5%2C100&accentColor=7bcfee%2C100&cabBackColor=33b5e5%2C100&cabHighlight
Color=33B5E5%2C100
StyleName: ActivityTrackerGreen1
http://jgilfelt.github.io/androidactionbarstylegenerator/#name=ActivityTrackerGreen1&compat=appcompat&theme=lig
ht&actionbarstyle=solid&texture=0&hairline=0&neutralPressed=1&backColor=76b200%
2C100&secondaryColor=9cd000%2C100&tabColor=000%2C100&tertiaryColor=9cd000
%2C100&accentColor=aae301%2C100&cabBackColor=9cd000%2C100&cabHighlightC
olor=9cd000%2C100
Organization of Styles and Themes
See http://developer.android.com/guide/topics/ui/themes.html
Styles
1. Styles are tagged with the <style> tag and should be stored in the /res/values directory
2. Styles are given a name, can inherit from a parent style, and are composed of items
whose attributes define the style (perhaps overriding parent style attributes)
<?xml … >
<resources>
<style name = “mandatory_text_field_style”
parent="@android:style/TextAppearance.Medium">>
<item name=”android:textColor>#00FF00></item>
<item name=”android:textSize”>14pt</item>
<item name=”android:textStyle”>bold</item>
</style>
D:\582694522.doc
9
Android Programming Notes
</style name=”….”>
….
</style>
3. Style inheritance from styles that you create do not need the parent attribute but can
be done via prefixing the style name with the parent name followed by a period.
<style name="mandatory_text_field_style.red_font">
<item name="android:textColor">#FF0000</item>
</style>
Inheritance can be done to multiple levels parent.child.subchild.sub_subchild
This only works for styles you define, not for styles inherited from android: (the
parent attribute must be used).
4. The item name values can be defined in other resource files such as colors.xml and
dimens.xml
…
<item name=”android:textColor”>@color/optional_text_color</item>
<item name=”android:textSize”>@dimen/optional_text</item>
5. Styles can be applied to views via the style attribute
<TextView
android:id=”@+id/TextView01”
style=”@style/mandatory_text_field_style”
…
6. Look at the corresponding View class reference (e.g. TextView, Spinner, etc.) to see the
list a attributes that can apply to each style. For a complete list of attributes look at
R.attr
7. Styles are applied to specific layout controls such as TextView, Button, etc.
8. Programmatically you supply the resource if when you call the controls contructor, eg.
R.style.mandatory_text_field_style
9. A style applied to a ViewGroup only applies to that ViewGroup. The style DOES NOT
cascade down to elements of that ViewGroup. To apply a style to all the child elements
of a viewgroup the style must be applied as a Theme at the activity or application level
via the Android Manifest file.
Themes
1. Themes are like styles but are applied to all elements of a given activity rather than one
view at a time.
2. Themes use the <style> tag and should be stored in the /res/values directory.
D:\582694522.doc
10
Android Programming Notes
3. The theme is assigned by adding the android:theme attribute to the <activity> or
<application> element in the Android manifest.
Themes based on Platform
1. Additional themes are available with newer platforms. To use different themes available
on different versions assign the appropriate style in the res/values-vxx directory. For
example
res/values/styles.xml
<style name="LightThemeSelector" parent="android:Theme.Light">
...
</style>
res/values-v11/styles
<style name="LightThemeSelector" parent="android:Theme.Holo.Light">
...
</style>
Activity/Fragment lifecycle
Code and output from the activity and fragment methods as they go through a lifecycle
including an orientation change.
http://stackoverflow.com/questions/14595946/activity-and-fragment-lifecycles-andorientation-changes
Android Source Code
http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/androi
d/
Actionbar Icon sizes
For actionbar icons (from http://stackoverflow.com/questions/15248207/actionbar-logosize)
32 dp = 32 px (MDPI)
32 dp * 1.5 = 48 px (HDPI)
32 dp * 2 = 64 px (XHDPI)
32 dp * 3 = 96 px (XXHDPI)
32 dp * 4 = 128 px (XXXHDPI)
If a drawable is only provided in XHDPI, Android scales it down, which is a little less
performant than providing the images in the proper sizes. I guess, this was just accepted by
the developers of the I/O app.
A free online site to resize images - http://resizepic.com/resize.php
D:\582694522.doc
11
Android Programming Notes
Icon Sizes
From http://stackoverflow.com/questions/12768128/android-launcher-icon-size
LDPI should be 36 x 36.
MDPI should be 48 x 48.
HDPI should be 72 x 72.
XHDPI should be 96 x 96.
XXHDPI should be 144 x 144.
XXXHDPI should be 192 x 192.
Sizes above in proportion to MDPI
LDPI is MDPI x 0.75.
HDPI is MDPI x 1.5.
XHDPI is MDPI x 2.
XXHDPI is MDPI x 3.
XXXHDPI is MDPI x 4.
Android app icon -512 x 512 pixels
Online icon converter - Using Chrome try http://android-ui-utils.googlecode.com/hg/assetstudio/dist/index.html
Acronyms
SMS
EMS
MMS
WAP
OHA
BREW
NDK
ADT
AVD
DDMS
ADB
Short message service (text messages)
Enhanced message service
Multimedia messaging service (photos, video, text)
Wireless Application Protocol (Stripped down version of http)
Open Handset Alliance
Binary runtime environment for Wireless
Native development kit
Android development tools
Android virtual device
Dalvik debug monitor service)
Android debug bridge
Android Tools
Android SDK and AVD
manager
Android Emulator
DDMS
ADB
Android Hierarchy
Viewer
D:\582694522.doc
Manages versions of SDK and AVD’s
AVD – Android virtual device
PC based android device emulator
Dalvik Debug Monitor
Android Debug Bridge
Visual tool that illustrates layout component relationships
12
Android Programming Notes
ADB – Android Debug Bridge
To debug on a actual mobile phone device you need a USB connector to the phone and a USB
driver to handle the communication. I found that coming up with the needed USB driver via the
Android to Dell web site links was rather confusing and if the driver was available I couldn’t find
it.
After much searching I found the PdaNet USB driver (http://www.junefabrics.com/android/) did
the trick with no muss, no fuss
Commonly Used Packages for Android
android.*
dalvik.*
java.*
javax.*
junit.*
org.apache.http.*
org.json
Org.w3c.dom
Org.xml.sax.*
Oorg.xmlpull.*
Android stuff of course
Dalvik vm support classes
Java core stuff of course
Java extension stuff for encryption support, parsers, sql, etc.
Java unit testing
Http
Javascript Object Notation(JSON)
W3C java bindings for DOM (for XML, HTML)
SAX support for XML
High performance XML parsing
Logging Support
Add import to your code
import android.util.Log;
and use methods
Methods
Log.e()
Log.w()
Log.i()
Log.d()
Log.v()
Type of logging
Errors
Warnings
Informational msgs
Debug msgs
Verbose messages
Sample code
Private static final String LOG_INFO = “IAmHere”;
Log.i(LOG_INFO, “Values of x:” + x);
Go to DDMS/Logcat tab (at bottom?) and look for the message. Click the + symbol on right of
Logcat tab to add a filter on “IAMHere” to just see those messages.
D:\582694522.doc
13
Android Programming Notes
Android Program Language Terminology
Context
All application-specific functionality can be accessed through the
Context
An application is a series of tasks and each task is implemented as
an Activity
An intent can be considered a message to the system to do
something, e.g. to switch from one ‘page’ to another (one Activity
to a different Activity, and Activity to request a Service to be
started, etc.) It is a request to the system to do something. That
something is handled by the Android OS in an asynchronous
messaging manner.
A service is a task that doesn’t not require user interaction (no user
GUI screen). A service can be something that does email checking,
playing a sound track, etc
Activity
Intent
Service
Anatomy of an Activity
public class MyActivity extends Activity{
// onCreate is called when Activity is first started
// bundle is null if newly started Activity
// or is this activity is being restarted it contains state information
// from it’s last execution
protected void onCreate(Bundle savedInstanceState){
//remember to call superclass if this is really some subclass
// super.onCreate(savedInstanceState);
}
// called after onCreate when activity ready to be started by Android OS
Protected vod onStart(){…}
// when activity brought back to foreground after onStop() was called
Protected void onRestart(){…}
// onResume called if Activity reaches top of activity stack
// and becomes foreground activity. Called either after onStart() or after an
// onPause() call occurred
// Most appropriate spot to retrieve any instances (e.g. audio, video and
// animation) to resources that this activity needs to run
public void onResume(){ …}
// onPause called when another Activity moves to the top of the activity stack
// Stop any audio, video etc started on onResume()
// Deactivate any Cursor objects
// do clean up and release any resources activity doesn’t need while in
D:\582694522.doc
14
Android Programming Notes
// background
// Save any uncommitted data in case Activity des not resume
// This should be done quickly as new Activity does not start until
// onPause() completes
// If activity killed after onPause(), onStop() and onDestroy might not
// be called.
// The more resources released in onPause() the less likely the Activity to be
// killed in background
protected void onPause(){
// save state info in Bundle.
onSaveInstanceState();
…}
// may be called after onPause() or after onStart() if activity sent to background
protected onStop(){…}
// onDestroy() is called when:
// activity completed its lifecyle OR
// resources low and Android needs to free them up
Protected void onDestroy(){
// isFinishing() returns false if activity has been killed by Android OS
If (isFinishing() ){ ….}
}
The Intent of the Intent
An Intent is the object that tells the Android OS to match a request with an Activity or Service,
and perhaps for broadcast to the system at large.
Using Intents with an Activity
// start MyActivity (that is defined elsewhere in the package
// no data is passed with the request
startActivity(new Intent(getApplicationContext(), MyActivity.class);
// dial a number
// (assumes application has authority defined to dial)
Uri telenumber = Uri.parse(7744378162);
Intent dial = new Intent(Intent.ACTION_DIAL, telenumber);
// add name value pair where name should include a package prefix
dial.putExtra(com.fisincorporated.android.COMPANY_NAME,
“FIS Incorporated”);
dial.putExtra(com.fisincorporated.android.COMPANY_GRADE, “A+”);
D:\582694522.doc
15
Android Programming Notes
startActivity(dial)
Commonly used intents can be found at::
http://developer.android.com/guide/appendix/g-app-intents.html
http://www.openintents.org/en/intentstable
Intents with Menus and Drilldowns
Main Menu – Each item on a menu corresponds to an Activity. A suitable Intent is created to
start the appropriate Activity when the item is selected
Drill Down – Each menu item might start the same Activity, but the data passed based on the
menu item is different.
Broadcasting and Receiving Intents
An Intent can be broadcast, via broadcastIntent() to the Android OS, for consumption by any
interested application (a BroadcastReceiver)
An application may both send and listen for Intent objects
Services
A Service is basically an Activity without a user interface. .Generally a service runs as a
background process that may do one specific task, or it might be a ‘clearing house’ that handles
requests from various other parties.
A Service is started via Activities and Intents by calls to startService() and bindService().
All Services exposed by an application must be registered in the AndroidManifest.xml file.
If a task requires extended use of resources, then it might best be implemented using a service.
Resource Files and Suggested Names
All resource files under /res/values directory must start with standard XML header
<?xml version="1.0" encoding="UTF-8"?>
For layout and menu files the line isn’t needed.
D:\582694522.doc
16
Android Programming Notes
Variations of the folder names can be automagically picked up by Android
1. Chinese strings stored in /res/values-zh/strings.xml
2. Layouts for portrait or landscape i
a. res/layout-port/main.xml
b. /res/layout-land/main.xml
3. Low, medium and high density screens formats in:
a. /res/drawable-ldpi/companyLogo.png
b. /res/drawable-mdpi/companyLogo.png
c. /reg/drawable-hdpi/companyLogo.png
Rules for alternate resources
1. Android tries to load from most appropriate specific resource to default resource
2. Alternative resource file names must always be named exactly the same as the default.
The resources are just in different directories (eg /res/values-zh/strings vs
/res/values/strings.xml
3. Alternative resources should always have default counterpart so something will be
loaded
4. Adding alternatives as to program size and complexity. Design default resources to be
flexible and scalable.
Resources can be obtained programmatically. To get string helloWorld in res/values/strings.xml:
String myString = getResources().getString(R.string.helloWorld)
Resource Type
Strings
String Pluralization
String Arrays
Booleans
Colors
Color state lists
required
directory
/res/
values
values
values
values
values
color
Dimensions
Integers
Integer Arrays
Mixed type arrays
Simple drawables
Graphics
values
values
values
values
values
drawable
Tweened animations
anim
Frame by frame
drawable
D:\582694522.doc
Filename (must be
lowercase)
(s- suggested)
strings.xml(s)
strings.xml(s)
strings.xml(s)
bools.xml (s)
colors.xml (s)
Eg buttonstates.xml
Indicators.xml
dimens.xml (s)
integers.xml (s)
integers.xml (s)
arrays.xml (s)
drawables.xml (s)
e.g. icon.png, logo.jpg
e.g. fadesequence.xml
spinsequence.xml
e.g. cartoon1.xml
17
XML Tag
<string>
<plurals>,<item>
<string-array>,<item>
<bool>
<color>
<selector>, <item>
<dimen>
<integer>
<integer-array>,<item.
<array>,<item>
<drawable>
Supported graphics files
or drawable definition
XML files such as shapes
<set>,<alpha>,<scale>,
<translate>,<rotate>
<animation-list><item>
Android Programming Notes
Resource Type
required
directory
/res/
Filename (must be
lowercase)
(s- suggested)
XML Tag
animation
Menus
Xml files
Raw files
menu
xml
raw
<menu>
Defined by developer
Defined by developer
Layouts
Styles and Themes
layout
values
E.g. helpmenu.xml
e.g. data.xml
E.g. song.mp3,
Myvideo.mp4
e.g main.xml, help.xml
styles.xml
themes.xml (s)
D:\582694522.doc
18
Must be layout control
<style>
Android Programming Notes
Views
View Type
Sample XML Definition and Options
Handler and/or example code
Menus
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/item01" android:title="@string/start"
android:orderInCategory="1"></item>
<item android:id="@+id/item02" android:title="@string/stop"
android:orderInCategory="2"></item>
</menu>
// To add menu to Activity add override
Public Boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.speed, menu);
return true;
}
<TextView
android:id=”@+id/TextView01” use more meaningful name
android:layout_width=”wrap_content” or fill_parent
android:layout_height=”wrap_content” or fill_parent
android:text=”@sting/text_for_this field”
/>
Get the field for program access
TextView txt = (TextView) findViewById(R.id.TextView01);
Textview
// To determine which menu item pressed implement
public boolean onOptionsItemSelected (MenuItem item) {
// add code to interegate item to
// determine which menu item pressed
return true;
}
Add contextual (hot) links by adding and autoLink property
android:autoLink=”nome” – no links
android:autoLink=”web” – link URLs to web pages
android:autoLink=”email” – link email addresses to mail client
android:autoLink=”phone” – link phone numbers to dialer app
android:autoLink=”map” – link street addresses to map app
android:autoLink=”all” – all types of links
EditText
D:\582694522.doc
You can combine multiple links with |
android:autoLink=”web|email”
<EditText
android:id=”@+id/EditText01” use more meaningful name
android:layout_width=”wrap_content” or fill_parent
android:layout_height=”wrap_content” or fill_parent
19
// Filter added to input field to ensure type of input
final EditText text_filtered = (EditText)
findViewById(R.id.input_filtered);
// setting filters by providing array of filters
Android Programming Notes
android:hint=”Enter phone number – no spaces”
android:lines=”4”
android:text=”@sting/text_for_this field”
android:autoLink=”web|email|phone|map” list multiple or use none
or all
/>
<AutoCompleteTextView
android:id="@+id/AutoCompleteTextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionHint="Pick a color or type your own"
android:completionThreshold="1" />
// filters can also be defined in the xml definition
text_filtered.setFilters(new InputFilter[]{new InputFilter.AllCaps(),
new InputFilter.LengthFilter(2) });
MultAutoCompleteTextView
<MultiAutoCompleteTextView
android:id="@+id/MultiAutoCompleteTextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:completionHint="Pick a color or type your own" />
SpinnerControl
Creates list of radio button options where the colors are defined
In /res/string in
<array name="colors">
<item>red</item>
<item>blue</item>
</array>
MultiAutoCompleteTextView mtext =
(MultiAutoCompleteTextView)
findViewById(R.id.MultiAutoCompleteTextView01);
mtext.setAdapter(adapter);
mtext.setTokenizer(new
MultiAutoCompleteTextView.CommaTokenizer());
final Spinner spin = (Spinner)findViewById(R.id.Spinner01);
AutoCompleteTextView
<Spinner
android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/colors"
android:prompt="@string/spin_prompt" />
Button
D:\582694522.doc
Basic button
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
20
Focus change
final String COLORS= {“red”,”blue”, “green”}’
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
adroid.R.layout.color_drop_down, COLORS);
AutoCompleteTextView text = (AutoCompleteTextView)
findViewById(R.id.AutoCompleteTextView01);
Text.setAdapter(adapter)
-- Get selected color when submit button (not shown)
-- is pressed.
final Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView text_sel = (TextView)spin.getSelectedView();
Toast.makeText(TextInputActivity.this, " spinner =
text_sel.getText(), Toast.LENGTH_SHORT).show();
}
});
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when submit button clicked
}
});
Android Programming Notes
RadioGroup
<RadioGroup
android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/RadioButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"></RadioButton>
<RadioButton
android:id="@+id/RadioButton02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"></RadioButton>
</RadioGroup>
final RadioGroup group =
(RadioGroup)findViewById(R.id.RadioGroup01);
group.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
TextView tv = (TextView) findViewById(R.id.buttonChoice);
if (checkedId != -1) {RadioButton rb = (RadioButton)
findViewById(checkedId);
if (rb != null) {
tv.setText("You chose: " + rb.getText());
}
} else {
tv.setText("Choose 1");
}
}
});
// To clear all radio button choices in a group
RadioGroup group = ( RadioGroup) findViewById
(R.id..yourRadioGroupId);
If (group != null) group.clearCheck();
ImageButton
CheckBox
ToggleButton
Similar to Checkbox but has
2 text fields. The first is to
display text for the on state,
the 2 to display text for the
D:\582694522.doc
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_button"
android:src="@drawable/droidsk2 "/>
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check me?"/>
<ToggleButton
android:id="@+id/toggle_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle"
21
CheckBox check_button = (CheckBox) findViewById(R.id.checkbox);
check_button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
TextView tv = (TextView)findViewById(R.id.checkbox);
tv.setText(check_button.isChecked() ? "This option is checked":
"This option is not checked");
} });
final ToggleButton toggle_button = (ToggleButton)
findViewById(R.id.toggle_button);
toggle_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {TextView tv = (TextView)
findViewById(R.id.text_feature);
Android Programming Notes
off state.
android:textOff="Disabled"
android:textOn="Enabled" />
tv.setText(toggle_button.isChecked() ? "This feature is on" : "This
feature is off");
}
});
Attributes
(from http://developer.android.com/guide/topics/ui/declaring-layout.html)
Every view and viewgroup has various attributes
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as
an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file).
There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not
need the plus-symbol, but must add the android package namespace, like so:
android:id="@android:id/empty"
With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local
resources class.
Styles
Centralize formatting in a style resource
1. Add colors to colors.xml
2. Add dimensions to dimension.xml
3. Create /res/values/styles.xml
Styles.xml
<resources>
<style name="stype_mandatory_text_field">
<item name="android:textColor">@color/mandatory_input_color</item>
D:\582694522.doc
22
Example use by TextView fields
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
Android Programming Notes
<item name="android:textSize">@dimen/mandatory_text_size</item>
<item name="android:textStyle">bold</item>
</style>
<style name="stype_optional_text_field">
<item name="android:textColor">@color/optional_text_color</item>
<item name="android:textSize">@dimen/optional_text_size</item>
<item name="android:textStyle">italic</item>
</style>
</resources>
android:layout_height="wrap_content"
android:text="@string/autolink_test"
android:stype="@style/style_mandatory_text_field" />
Themes
1. Themes are like styles but are applied at the activity level (in general that means by screen)
2. Themes are defined like styles, use the <style> tag and should be stored in the /res/values directory
3. Define the use of the theme by using the theme attribute of an activity in the AndroidManifest.xml file
Other code snippets
Making a phone call
by pressing displayed
number
A simple way to have
common menu on all
screens
D:\582694522.doc
// assume phone number in numberEntry text field
Uri number = Uri.parse(“tel:” + numberEntry.getText.toString();
// create intent
Intent dial = new Intent(Intent.ACTION_DIAL, number);
// and request intent to be acted upon
startActivity(dial);
Note that application needs android.permission.CALL_PHONE to actually make the call
1. Define your menu xml file
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
23
Android Programming Notes
android:id="@+id/choice1_menu_item"
android:title="MenuChoice1"
android:orderInCategory="1"></item>
<item
android:id="@+id/choice2_menu_item"
android:title="MenuChoice2"
android:orderInCategory="2"></item>
</menu>
2. Define a superclass with code to display menu items
public abstract class MenuActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drawmenu, menu);
menu.findItem(R.id.choice1_menu_item).setIntent(new Intent(this, DrawBitmapActivity.class));
menu.findItem(R.id.choice2_menu_item).setIntent(new Intent(this, DrawGradientActivity.class));
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
startActivity(item.getIntent());
super.onOptionsItemSelected(item);
return true;
}
}
D:\582694522.doc
24
Android Programming Notes
3. Then define subclasses of the menu class but display some other view (MyView)
public class SubActivity1 extends MenuActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
private static class MyView extends View {
public ViewWithBitmap(Context context) {
super(context);
}
…
}
List files and details
from external sdcard
D:\582694522.doc
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; //sdcard only
Cursor c = managedQuery(u, null, null, null, null);
if (c.moveToFirst()) {
do {
int max = c.getColumnCount();
for (int i = 0; i < max; i++) {
String colName = c.getColumnName(i);
String value = c
.getString(c.getColumnIndex(colName));
if (colName != null){
Log.d("columnName: ", colName);
}
if (value != null) {
Log.d("value", value);
}
}
} while (c.moveToNext());
25
Android Programming Notes
}
Displaying an array of
items
In this example the layout contains the listview. An ArrayAdapter is used to display a set of strings
1. Main.xml layout to be referenced in Activity view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
…
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/theList"
android:divider="#000"
android:isScrollContainer="true"
android:headerDividersEnabled="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical"/>
</LinearLayout>
2. In the activity, have code similar to
private String myListOfStrings = new String(){“x”,”y”,”Z”};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //<<< display main layout
private ListView listView=(ListView)findViewById(R.id.theList); // get the ListView in main.xml
// Note the following uses Andriod supplied text field
// (simple_list_item_1)
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myListOfStrings);
listView.setAdapter(adapter);
D:\582694522.doc
26
Android Programming Notes
D:\582694522.doc
27
Android Programming Notes
File Locations
In general all files are stored under /data/data/<package name>/
Preferences
…/shared_prefs/<preferences filename>.xml
Files (seq files)
…/files/
Cache files
…/cache/
Should keep cache files to 1MB max. Android will delete
cache files when needed if internal storage runs low or
when app is unistalled
SQLite database
…/databases/<databasename>
Note that this is not accessable if you don’t have root
access. So you can see on emulator but not on device
unless you have root access.
Launching ADB in command window
In this situation ADB is installed in C:\Program Files\Android\android-sdk-windows\platformtools>. The easiest thing to do is to create Windows shortcut
Target: %SystemRoot%\system32\cmd.exe
Start in: "C:\Program Files\Android\android-sdk-windows\platform-tools"
ADB commands
List connected devices
Connect to device
named emulator-5554
(when more than one
emulator/device
running
Remount file system (in
case get read only error
when it shouldn’t be)
Install apps to avd
Copy a file from PC to
emulator
D:\582694522.doc
adb devices
adb –s emulator-5554 shell
adb remount
adb shell
adb install C:\Users\Eric\Downloads\com.android.vending20131113.apk
1. Make sure directory is writeable. If not do chmod
adb shell
cd data/data/com.fisincorporated.ExerciseTracker
chmod -R 777 * (-R recursive)
2. Push the file to the device
adb push
"C:\Users\Eric\Documents\exercise_tracker.db"
28
Android Programming Notes
/data/data
/com.fisincorporated.ExerciseTracker/databases
882 KB/s (324608 bytes in 0.359s)
A menu item can contain icons, submenus, and keyboard shortcuts. A Submenu allow checkable
items, but not icons or other Submenus.
The following assumes the start and stop strings are in res/values/strings.xml and the menus
are defined in res/menu/action xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/start" android:title="@string/start" />
<item android:id="@+id/stop" android:title="@string/stop" />
</menu>
To display the menu override onCreateOptionsMenu() in the Activity
public boolean onCreateOptionsMenu(Menu menu){
getMneuInflater().inflage(R.menu.action, menu);
return true;
}
Programatically a menu can be created via
public boolean onCreateOptionsMenu(Menu menu){
super.OnCreateOptionsMenu(menu)
menu.add(“Start”.setIcon(android.R.drawable.some_start_icon).
.setIntent(new Intent(this, StartActivity.class);
menu.add(“Stop”.setIcon(android.R.drawable.some_stop_icon).
.setIntent(new Intent(this, StopActivity.class
}
Menus
A menu item can contain icons, submenus, and keyboard shortcuts. A Submenu allow checkable
items, but not icons or other Submenus.
The following assumes the start and stop strings are in res/values/strings.xml and the menus
are defined in res/menu/action xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/start" android:title="@string/start" />
<item android:id="@+id/stop" android:title="@string/stop" />
</menu>
D:\582694522.doc
29
Android Programming Notes
To display the menu override onCreateOptionsMenu() in the Activity
public boolean onCreateOptionsMenu(Menu menu){
getMneuInflater().inflage(R.menu.action, menu);
return true;
}
Programatically a menu can be created via
public boolean onCreateOptionsMenu(Menu menu){
super.OnCreateOptionsMenu(menu)
menu.add(“Start”.setIcon(android.R.drawable.some_start_icon).
.setIntent(new Intent(this, StartActivity.class);
menu.add(“Stop”.setIcon(android.R.drawable.some_stop_icon).
.setIntent(new Intent(this, StopActivity.class
}
SQLite
References: www.sqlite.org/index.html , sqlzoo.net
SQLite stores databases in /data/data/[application package name]/databases/ dbname.db. For
example:
/data/data/com.fisincorporated.images/databases/images.db
I haven’t had any luck connecting to the databases on the phone. (Maybe need root access?)
Running under an emulator.
1. Go to C:\Program Files\Android\android-sdk-windows\platform-tools
(The above is dependent on where you install Andriod. A later install is at C:\androidsdk\platform-tools
2. Start adb connecting to the emulator via
adb -s emulator-5554 shell
3. Start SQLite with the database you are interested in (it must of course been previously
created), e.g.:
# sqlite3 /data/data/com.fisincorporated.sqlite/databases/TestingData.db
4. SQLite commands start with a period (.). SQLite SQL (i.e. Select * from…) ends with an
semi-colon‘;’.
D:\582694522.doc
30
Android Programming Notes
SQLite Commands
Command
.help
.quit
.exit
.tables
.indices my_table
.schema
.schema my_table
.output /some_dir/some_file
Action
List of all SQLite commands
Exit sqlite
Exit sqlite
List tables in db
List indexs on my_table
List all DDL for all tables in the database
List the DDL used to create my_table
Send subsequent output from commands to
/some_dir/some_file
Usually output goes to stdout. To get subsequent output to
go back to stdout just use:
.output stdout
.dump my_table
.read /some_dir/some_file.sql
.separator ,
.import
/some_dir/some_file.csv
my_table
.width 5 10 8
.header on
Dumps DDL and an insert into statement for each record in
my_table. An example
.output /data/my_table_dump.txt
.dump my_table
.output stdout
Read and execute the DDL/SQL commands in some_file.sql
Import the csv records into my_table
Sets the column width of the 3 columns in subsequent sql to
5, 10 and 8 characters respectively
Display column names in
SQLite SQL Examples
CREATE TABLE tbl_authors (id INTEGER PRIMARY
KEY AUTOINCREMENT , firstname TEXT, lastname
TEXT);
Create table
CREATE TABLE tbl_books (id INTEGER PRIMARY KEY
AUTOINCREMENT , title TEXT, dateadded DATE,
authorid INTEGER NOT NULL CONSTRAINT authorid
REFERENCES tbl_authors(id) ON DELETE CASCADE);
Do not create tables starting with ‘sqlite_’
If you create a column with ‘INTEGER PRIMARY
KEY’ it becomes an alias for the rowed. So the ‘id’
column becomes an alias for the rowed(aka
D:\582694522.doc
31
Android Programming Notes
ROWID, _ROWID_, or OID ) If you explicitly use
one of those 3 names however, it will refer to
the declared column NOT the actual system
generated rowed.
Create Trigger
CREATE TRIGGER fk_insert_book BEFORE INSERT
ON tbl_books FOR EACH ROW BEGIN SELECT
RAISE(ROLLBACK, 'insert on table \"tbl_books\"
violates foreign key constraint \"fk_authorid\"')
WHERE (SELECT id FROM tbl_authors WHERE id =
NEW.authorid) IS NULL; END;`
Drop table
Drop trigger
Drop table bl_books;
Drop Trigger if exists fk_insert_book;
SQLite/Android/JDBC methods
Check for
database
existence
Open or
create if not
previously
created
Standard
SQLite config
settings
Execute sql
This is android activity method
if (Arrays.binarySearch(databaseList(), DATABASE_NAME) >= 0) {
// Delete the old database file, if it exists
deleteDatabase(DATABASE_NAME);
}
private static final String DATABASE_NAME = "test.db";
//mDatabase used in all examples below
mDatabase = openOrCreateDatabase(DATABASE_NAME,
SQLiteDatabase.CREATE_IF_NECESSARY, null);
// SET SOME DATABASE CONFIGURATION INFO
mDatabase.setLocale(Locale.getDefault()); // Set the locale
mDatabase.setLockingEnabled(true); // SQLiteDatabase is made thread-safe by using
locks around critical sections.
mDatabase.setVersion(1); // Sets the database version.
mDatabase.execSQL(“sql statement”)’
Tip: Consider putting sql statements in private static final String variables.
Execute a
compiled SQL
statement
(not a Select
SQL
statement)
Create
Transaction
Insert a record
D:\582694522.doc
SQLiteStatement sqlSelect = mDatabase
.compileStatement(CREATE_BOOK_TABLE);
sqlSelect.execute();
mDatabase.beginTransaction();
try {
…
// if this not executed then rollback will occur
mDatabase.setTransactionSuccessful();
} catch (Exception e) {
// transaction failed. Do something with exception
} finally {
mDatabase.endTransaction();
ContentValues values = new ContentValues();
32
Android Programming Notes
Update a
Record
Delete a
record
Create cursor
values.put("firstname", newAuthor.mFirstName);
values.put("lastname", newAuthor.mLastName);
newAuthor.mAuthorId = mDatabase.insertOrThrow(TABLE_AUTHOR, null,
values);
ContentValues values = new ContentValues();
values.put("title", newtitle);
mDatabase.update(TABLE_BOOK, values, "id=?", new String[] { bookId.toString() });
mDatabase.delete(TABLE_BOOK, "id=?", new String[] { bookId.toString() });
Cursor c = mDatabase.query(“tbl_books”,null,null,null,null,null,null);
…
c.close();
In the above form you need to manage the cursor. The following uses an Activity
method to manage the cursor.
Get result set
count
Moving thru
cursor
Simple queries
Cursor c = mDatabase.query(“tbl_books”,null,null,null,null,null,null);
startManagingCursor(c);
// SQLite knows # rows returned by cursor without having
// to iterate through the result set.
c.getCount();
c.moveToFirst();
while (c.isAfterLast() == false) {
for (int i = 0; i < c.getColumnCount(); i++) {
// get row values
xxx= c.getString(i);
}
c.moveToNext();
}
mDatabase.query( String tableName, String[] columnNames,
String wherePhrase, String[] wherePhraseValues, String GroupByPhrase, String
havingClause, String OrderByClause, String LimitClause)
Do not include keywords WHERE, GROUP BY, HAVING, ORDER BY, LIMIT in the
respective strings.
Complex
select sql
Use SQLite QueryBuilder
// join of 2 tables
SQLiteQueryBuilder queryBuilder2 = new SQLiteQueryBuilder();
queryBuilder2.setTables(TABLE_BOOK + ", " + TABLE_AUTHOR);// Tables to join
queryBuilder2.appendWhere("("+TABLE_BOOK + ".authorid" + "=" + TABLE_AUTHOR
+ ".id" + ")");
// how to join
queryBuilder2.appendWhere(" AND (" + TABLE_BOOK + ".title" + "
LIKE '%Prince%'" + ")");
// WHERE clauses are AND'ed together, so now we are getting all titles with 'of'
c = queryBuilder2.query(mDatabase, asColumnsToReturn, null, null, null,
null,strSortOrder);
// Union of sql
String sqlUnionExample = "SELECT title AS Name, 'tbl_books' AS OriginalTable from
tbl_books WHERE Name LIKE ? UNION SELECT (firstname||' '|| lastname) AS Name,
'tbl_authors' AS OriginalTable from tbl_authors WHERE Name LIKE ? ORDER BY Name
D:\582694522.doc
33
Android Programming Notes
ASC;";
c = mDatabase.rawQuery(sqlUnionExample, new String[]{ "%ow%",
"%ow%"});
Close
database
Delete
database
mDatabase.close();
// method part of application Context
deleteDatabase(“database.db”);
Sample Code to Use Database in Application
The following code snippets are examples and have not been checked for syntax
Define database
Create class, eg ArtTrackerDatabase that contains table and column names
1.
table/column names in
class/internal class
Note that table classes implement BaseColumns
to get _ID column
public final class eg ArtTrackerDatabase {
private eg ArtTrackerDatabase () {}
// Artist table
public static final class Artist implements BaseColumns {
private eg ArtTrackerDatabase () {}
public static final String ARTIST_TABLE = "table_artist";
public static final String ARTIST_NAME = "artist_name";
public static final String ARTIST_BORN = "artist_born";
public static final String ARTIST_DIED = "artist_died";
public static final String DEFAULT_SORT_ORDER = "artist_name ASC";
}
2.
Create subclass of
SQLiteOpenHelper with
recommended override
methods
// Art Works table
public static final class ArtWorks implements BaseColumns {
private ArtWorks() {}
public static final String ARTWORKS_TABLE = "table_artworks";
public static final String ARTWORKS_NAME = "artworks_name";
public static final Integer ARTWORKS_ARTIST_ID =
“artworks_artist_id”;
public static final String ARTWORKS_DATE = "artworks_date";
public static final String DEFAULT_SORT_ORDER = "artworks_name ASC";
}
}
Override methods are
onCreate, onUpgrade, onOpen
class ArtistTrackerDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "artist_tracker.db";
private static final int DATABASE_VERSION = 1;
ArtistTrackerDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
D:\582694522.doc
34
Android Programming Notes
@Override
public void onCreate(SQLiteDatabase db) {
// Create the Artist table
db.execSQL("CREATE TABLE " + Artist.ARTIST_TABLE + " ("
+ Artist._ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ Artist.ARTIST_NAME + " TEXT,"
+ Artist.ARTIST_BORN + " INTEGER"
+ Artist.ARTIST_DIED + " INTEGER"
+ ");");
// Create Artworks table
…
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// logic to upgrade database if needed
}
// Create the ArtWorks table
db.execSQL("CREATE TABLE " + ArtWorks.ART_WORKS+ " ("
+ ArtWorks._ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ ArtWorks.ARTWORKS_NAME + " TEXT"
+ ArtWorks.ARTWORKS_ARTIST_ID + " INTEGER"
+ “ NOT NULL CONSTRAINT “ + ARTWORKS_ARTIST_ID + “ references table “ +
ARTIST_TABLE” +”(id) ON DELETE CASCADE)”
+ ");");
// create trigger to make sure artist defined
// prior to adding artwork
//
3.
Displaying records
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
}
//
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// define tables to join
queryBuilder.setTables(Artis.ARTISTS_TABLE +", "
+Artworks.ARTWORKS_TABLE);
// define where condition
queryBuilder.appendWhere(Artist.ARTIST_TABLE + "." + Arist._ID + "=" +
Artworks.ARTWORKS_TABLE + "." + ARTWORKS_ARTIST_ID);
// define columns to return
String columnsToReturn[] = {
Artist.ARTIST_TABLE + "." + Aritst.ARTIST_NAME
,Artist.ARTIST_TABLE + "." + Artist._ID
,Artworks.ARTWORKS_TABLE + "." + Artworks.ARTWORKS_NAME };
// return cursor
mCursor = queryBuilder.query(mDB, returnColumns, null, null, null, null,
Artist.DEFAULT_SORT_ORDER);
D:\582694522.doc
35
Android Programming Notes
//let Andriod manage cursor
startManagingCursor(mCursor);
// create Adapter
ListAdapter adapter = new SimpleCursorAdapter(
this, R.layout.artist_item,
mCursor, new String[]{
Artist.ARTIST_NAME, Artworks.ARTWORK_NAME },
new int[]{
R.id.TextView_ArtistName,
R.id.TextView_ArtworkName });
// Get the listview
ListView av = (ListView)findViewById(R.id.ArtistList);
// add the adapter to the view
av.setAdapter(adapter);
Creating a query filter
(and added to adapter)
// add listener for artist
av.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(
AdapterView<?> parent, View view, int position, long id) {
// Get artworks id and then drill down
// (create intent and switch activity
// artwork details
final long artworksId = id;
…
});
}
1. Create some adapter eg.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line,
mCursorAutoComplete, new String[]
{PetType.PET_TYPE_NAME},
new int[]{android.R.id.text1}
2. Add the subclass of FitlerQueryProvider to the adapter (subclass in
#3)
adapter.setFilterQueryProvider(new MyFilterQueryProvider());
3. Create subclass of FilterQueryProvider with runQuery method
class MyFilterQueryProvider implements FilterQueryProvider {
public Cursor runQuery(CharSequence constraint) {if ((constraint !=
null) &&
(mCursorAutoComplete != null)) {
String strWhere = PetType.PET_TYPE_NAME
+ " LIKE
?";
stopManagingCursor(mCursorAutoComplete);
mCursorAutoComplete =
mDB.query(PetType.PETTYPE_TABLE_NAME, new String[] {
PetType.PET_TYPE_NAME,
PetType._ID }, strWhere, new
String[] {
"%" + constraint.toString() + "%"}, null,
null,
PetType.DEFAULT_SORT_ORDER);
startManagingCursor(mCursorAutoComplete);
}
D:\582694522.doc
36
Android Programming Notes
return mCursorAutoComplete;
}
}
Various date
manipulations
select julianday(max(substr(start_timestamp,1,10)))
, julianday(min(substr(start_timestamp,1,10)), '%w')
,julianday(min(substr(start_timestamp,1,10)))
, (julianday(max(substr(start_timestamp,1,10))) julianday(min(substr(start_timestamp,1,10))) )/7
from location_exercise ;
select min(start_timestamp) - strftime('%w', min(start_timestamp)) from
location_exercise ;
select julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)) from location_exercise;
select strftime('%w',date(min(start_timestamp,1,10))) from location_exercise;
select substr(min(start_timestamp),1,10),
select (julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp))) from location_exercise;
select
min(substr(start_timestamp,1,10))
, datetime(julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)) )
,max(substr(start_timestamp,1,10))
, julianday(max(substr(start_timestamp,1,10)))
, julianday( max(substr(start_timestamp,1,10)), 'weekday 0')
, datetime(julianday(max(substr(start_timestamp,1,10))) + strftime('weekday
0', max(start_timestamp)) )
,julianday(max(substr(start_timestamp,1,10))) + strftime('weekday 0',
max(start_timestamp))
,(julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)))
,(julianday( max(substr(start_timestamp,1,10)), 'weekday 0') (julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)))
) /7 from location_exercise;
select
datetime(julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)) )
,(julianday( max(substr(start_timestamp,1,10)), 'weekday 0') (julianday(min(substr(start_timestamp,1,10))) - strftime('%w',
min(start_timestamp)))
) /7 from location_exercise;
D:\582694522.doc
37
Android Programming Notes
Contacts Database
V1.x
URI
‘Master’
table
Phone
Numbers
Email
Addresses
Notes
People.CONTENT_URI
Where phrase to get corresponding data for person
Contacts.Phones.CONTENT_URI
Contacts.Phones.PERSON_ID +" = ?"
Contacts.ContactMethods.CONTENT_EMAIL_URI
Contacts.ContactMethods.PERSON_ID + " = ?"
Stored in People table – People.CONTENT_URI
Column People.NOTES
Postal
addresses
Contacts.ContactMethods.CONTENT_URI
Contacts.ContactMethods.PERSON_ID + " = ? AND " +
Contacts.ContactMethods.KIND + " = ?"
IM
Contacts.ContactMethods.CONTENT_URI
Contacts.Organizations.CONTENT_URI
Contacts.ContactMethods.KIND + " = ?"
Contacts.ContactMethods.PERSON_ID + " = ?"
URI
ContactsContract.Contacts
Where phrase to get corresponding data for person
ContactsContract.CommonDataKinds.Phone
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"
= ?",
Email
addresses
Notes
ContactsContract.CommonDataKinds.Email
Addresses
ContactsContract.Data
IM
ContactsContract.Data
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "
= ?"
ContactsContract.Data.CONTACT_ID + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?"
ContactsContract.Data.CONTACT_ID + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?"
ContactsContract.Data.CONTACT_ID + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?"
Organizations
V2.0+
‘Master’
table
Phone
Numbers
ContactsContract.CommonDataKinds.Note
D:\582694522.doc
38
Android Programming Notes
Organizations
ContactsContract.CommonDataKinds.Organization
General ContentProvider Setup
1. Your contentProvide must extend from ContentProvider and implement 5 methods
public class ActivityTrackerProvider extends ContentProvider{
public int delete(Uri uri, String selection, String[] selectionArgs) {
}
public String getType (Uri uri){
}
public Uri insert(Uri uri, ContentValues values){
}
public Boolean onCreate(){
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder){
}
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs){
}
2. Define a unique ‘public static final ‘ base URI, named CONTENT_URI that other applications will use to access the content provider. The
best name to use is fully qualified class name
public static final Uri CONTENT_URI = Uri.parse(content://com.fisincorporated.ActivityTrackerProvider”);
D:\582694522.doc
39
Android Programming Notes
The Emulator and DDMS
Toggling Emulator Orientation between Portrait and Landscape
Press left-cntrl/F11 (Windows)
Emulator files
The default location for emulator files are C:\Documents and
Settings\yourWindowsID\.android\avd\ (eg C:\Documents and Settings\Eric
Foertsch\.android\avd\). A subdirectory is names for each AVD created. Within each AVD
subdirectory or the various emulator files.
Defining SD Card
In the \tools directory, mksdcard is a utility to create an SD Card image file
The SDCard image file can then be referenced when creating an emulator.
Non-Writeable SD Card in emulator
For some reason the SD card in the emulator may be(become) non-writeable. To make it
writeable execute the following commands in DOS window
adb shell
su
mount -o rw,remount rootfs /
chmod 777 /mnt/sdcard
exit
Putting images on emulator SD Card
1. Images on SD Card on emulator are supposedly stored in
content://media/external/images/media (value of Media.EXTERNAL_CONTENT_URI)
2. Start the emulator
3. With the emulator running opend a DOS window and start adb with shell option:
C:\Android-Emulator Files>"C:\Program Files\Android\android-sdkwindows\platform
-tools\adb" shell
4. Create the image directory - media/external/images/media via (may be more direct
way but…)
su
(Switch to superuser)
cd sdcard
mkdir media
cd media
mkdir external
cd external
D:\582694522.doc
40
Android Programming Notes
mkdir images
cd images
mkdir media
Push/Pull Files to Emulator
1. Use DDMS
2. Go to File Explorer window in DDMS
3. Use the push/pull icons to move files
Seeing SDCard contents in emulator
1. Hook up phone and select ‘Charge only’ as USB connect type. (If phone hooks up as a
drive the SDCard folder (and others) appear empty)
2. You can see files on SD Card in DDMS File Explorer.
Getting Google Maps to work in emulator.
The version of the vending and gms packages are dependent on the version of the
Android API. After much trial and error, I found the following worked
1. Set up emulator with Android 4.1.2
2. Open command prompt and run adb (assuming adb is in path) to load the 2 apps
(the following assumes only 1 emulator running)
adb install C:\Android\Emulator-Apps-for-Maps\com.android.vending20131113.apk
adb install C:\Android\Emulator-Apps-for-Maps\com.google.android.gms20131113.apk
3. If either of the installs above fail then trying uninstalling the packages first via
adb uninstall com.android.vending (only if install fails)
adb uninstall com.google.android.gms (only if install fa
Android folders
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
http://androidforums.com/android-lounge/5930-definitive-androids-folder-structure.html








Music/ - Media scanner classifies all media found here as user music.
Podcasts/ - Media scanner classifies all media found here as a podcast.
Ringtones/ - Media scanner classifies all media found here as a ringtone.
Alarms/ - Media scanner classifies all media found here as an alarm sound.
Notifications/ - Media scanner classifies all media found here as a notification sound.
Pictures/ - All photos (excluding those taken with the camera).
Movies/ - All movies (excluding those taken with the camcorder).
Download/ - Miscellaneous downloads
D:\582694522.doc
41
Android Programming Notes
Sending a broadcast via adb
A boardcast can be set via a command similar to
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c
android.intent.category.HOME -n package_name/class_name
For example to send boot completed intent to the specified class
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c
android.intent.category.HOME -n com.bignerdranch.android.photogallery/StartupReceiver
Memory Analyzer
See http://developer.android.com/tools/debugging/debuggingmemory.html#ViewingAllocations
Add to Eclipse the Memory Analyzer Tool (MAT) (see
http://www.eclipse.org/mat/downloads.php) for how to load to Eclipse
Exerciser Monkey
Exerciser Monkey (http://developer.android.com/tools/help/monkey.html) is a testing tool
for providing random keypress to an app.
For the following example, wait 1 second (1000 millisecs) between actions and execute
500 actions, -v will display some info on the keypresses
C:\Users\Eric>adb shell monkey -p com.fisincorporated.ExerciseTracker –throttle 1000 v 500
Rerunning will give the exact same key presses unless you use the –s (seed parm).
Change the value for each run if you want to generate a different sequence of key
presses
C:\Users\Eric>adb shell monkey -p com.fisincorporated.languagetutorial --throttle 500 –s
1000 -v 500
Note: cutting/pasting may be a problem (or perhaps get some funny end char when
pasted into DOS window), so you may need to play around with it.
D:\582694522.doc
42
Android Programming Notes
Monkeyrunner
Monkeyrunner (http://developer.android.com/tools/help/monkeyrunner_concepts.html)
provides an API for writing programs that control and Android device or emulator.
The monkeyrunner used Jython, an implementation of Python using Java
Using Google API’s in app
The following uses ActivityTracker as an example
See https://console.developers.google.com/project/998934979712/apiui/api?authuser=0
1. Get an API key for each Google API you are using
2. Put the keys for both debug and test in a string xml file. In this case the file is in
values/api_keys.xml
3. If you post to a public repository(e.g. Git) make sure the api_keys.xml file is NOT
indexed.
4. In AndroidManifest.xml reference the appropriate API key string. For example:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/GoogleMapsKeyTest"/>
5. Remember to switch the key to the prod version prior to exporting and uploading
to Google Play Store
Uploading App to GooglePlay Store
All apps must be signed before loading to GooglePlay. In addition if the app include
Google API’s it must include an API key(s).
See http://developer.android.com/tools/publishing/app-signing.html for signing your app
See http://developer.android.com/distribute/index.html for details
FaceBook API install
https://developers.facebook.com/docs/android/getting-started
API’s downloaded to C:\Android\Non-Google-addins\Facebook\facebook-android-sdk3.14.1
Install to emulator (or could be phone?)
D:\582694522.doc
43
Android Programming Notes
adb install C:\Android\Non-Google-addins\Facebook\facebook-android-sdk3.14.1\bin\FBAndroid-7.0.0.apk
Get keystore hash. (OpenSSL needed to be downloaded first)
keytool -exportcert -alias androiddebugkey -keystore
C:\Users\Eric\.android\debug.keystore | "C:\Program Files\OpenSSL\bin\openssl" sha1 binary | "C:\Program Files\OpenSSL\bin\openssl" base64
D:\582694522.doc
44
Android Programming Notes
Converting an Activity to a Activity/Fragment
Old Activity
To change display of view from activity to
fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
FragmentActivity
Create general abstract super class with abstract
createFragment method
Fragment
@Override
public View onCreateView
(LayoutInflater inflater, ViewGroup
Modify old activity to implement abstract class
Implement abstract createFragment method to return
fragment
@Override
protected Fragment createFragment() {
return new ActivityDetailFragment();
container,Bundle savedInstanceState)
{return
inflater.inflate(R.layout.activity_detail
, container, false); }
See below to pass values to fragment
Receiving values from intent
Intent intent = getIntent();
Intent.getxxxExtra(key);
Intent.getxxxExtra(key, default_value);
E.g.
getIntent.getStringExtra(key);
Call fragment newInstance method passing all needed
values
Fragment = newFragment.newInstance(….);
To pass values to fragment
D:\582694522.doc
45
public static newFragment
newInstance( values)
Bundle args = new Bundle();
args.putStringArrayList(EXTRA_SELECT
IONS,
originalSelections);args.putString(EXT
RA_TITLE,title);
NewFragment fragment = new
SomeFragment();
fragment.setArguments(args);
return fragment;
}
public onCreateView(Bundle
savedInstanceState) {
if (getArguments() != null){
Android Programming Notes
Old Activity
FragmentActivity
Fragment
String arg1 =
getArguments().getString(ARG1_STRI
NG_NAME);
…
}
Remenber you might also have data
in savedInstanceState!
Using Context
…(this Activity,..)
Or
…(getContext(),…)
Finding views in layout
findViewById(int) can be called as
getView().findViewById(R.id.button3)
Menus in Activity
… (getActivity(),…)
getView().findViewById(R.id.button3)
FragmentManager must be told
fragment has menu, so call
public boolean
onCreateOptionsMenu(android.view.Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.prior_activity_detail,
menu);
return true;
}
setHasOptionsMenu(true) in
onCreate
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate( savedInstancState);
public boolean onOptionsItemSelected(MenuItem
item) {
Intent intent;
switch (item.getItemId()) {
…
}
D:\582694522.doc
// Enable the option menu for the
Fragment
setHasOptionsMenu(true);
}
Fragment menus will be added to
46
Android Programming Notes
Old Activity
FragmentActivity
Fragment
bottom of Activity menus
@Override
public void
onCreateOptionsMenu(Menu menu,
MenuInflater inflater) {
super.onCreateOptionsMenu(menu,
inflater);
inflater.inflate(R.menu.fragment1_me
nu, menu);
}
public boolean
onOptionsItemSelected(MenuItem
item) {
Intent intent;
switch (item.getItemId()) {
…
}
onSaveInstanceState
The saved bundle will be passed into
all 3 of the following methods so get
onRestoreInstanceState()
as needed
onCreate(), onCreateView() or
onActivityCreated()
References to this.
getActivity()
To exit activity
finish();
To exit fragment and calling
activity
getActivity().finish();
D:\582694522.doc
47
Android Programming Notes
Automated Testing
This is for UI testing, not the testing of individual methods.
UIAutomotor
http://developer.android.com/tools/testing/testing_ui.html
Some UI developer guidelines to ease testing
1. The app to be tested should have visible text labels,android:contentDescription
(to label ImageButton, ImageView, CheckBox, etc. )values or both.
2. Use android:hint instead of a content description for EditText fields.
3. Associate android:hint attribute with any graphical icons used by controls
4. Make sure all UI elements are accessible using a trackball or D-pad
5. Use uiautomatorviewer tool to ensure all UI components accessable to testing
framework. You can also turn on accessability services such as Talkback and
Explore by Touch and trying using app only with directional controls.
See web page for setup instructions
Note : The uiautomatorviewer can be started from the command line

uiautomatorviewer - A GUI tool to scan and analyze the UI components of an
Android application.

uiautomator - A Java library containing APIs to create customized functional UI
tests, and an execution engine to automate and run the tests.
To use these tools, you must have the following versions of the Android development tools
installed:

Android SDK Tools, Revision 21 or higher

Android SDK Platform, API 16 or higher
1. Created DemoCodeAutomatedTesting project to test DemoCode app.
2. Opened command prompt and ran
C:\Eclipse\workspace\Android\DemoCode-UIAnimator>C:\Android\sdk\tools\android
create uitest-project -n DemoCode-UIAnimator -t 7 -p C:\Eclipse\workspace\Android\
The template command is
<android-sdk>/tools/android create uitest-project -n <name> -t 1
-p <path>
D:\582694522.doc
48
Android Programming Notes
(the –t parm to be used can be found by executing the command
android list targets
and using either the id value OR (supposedly) the string name associated with the id
value. In the case above the id of 7 (which corresponds to “android-17” was used.
3. If needed, run set command for ANDROID_HOME (or put in environment variables)
set ANDROID_HOME=C:\Android\sdk
4. Go to project directory where build.xml created (from step 2 above)
cd c:\eclipse\workspace\android
4.5. Copy the build.xml file to the project directory (Not specified in online doc)
cd DemoCode-UIAnimator
copy ../build.xml (which for some reason also copied local.properties and
project.properties)
5. Execute the build
ant build
6. Push the test jar to the Android device – in this case only one emulator running so no
need to specify device
adb push C:\Eclipse\workspace\Android\DemoCode-UIAnimator\bin\DemoCodeUIAnimator.jar /data/local/tmp/
7. Execute the test
adb shell uiautomator runtest DemoCode-UIAnimator.jar -c
com.fisincorporated.democode.test.DemoListCheck
Robotium
See https://code.google.com/p/robotium/
Video - https://www.youtube.com/watch?v=T_8euppCz3k
Common problems - https://code.google.com/p/robotium/wiki/RobotiumTutorials and see
link at bottom of page for pdf
Downloaded robotium jar and javadoc files
Created test DemoCode-Robotium
D:\582694522.doc
49
Android Programming Notes
Worked easily ‘out of the box’ with minimal setup.
Appium
See http://appium.io
Cross platform – Android and iOS testing tool
Sounds good but setup and configuration much more complicated.
D:\582694522.doc
50