Upload
junda-ong
View
1.289
Download
1
Tags:
Embed Size (px)
DESCRIPTION
A 1 day NTU workshop for kickstarting Android development. Includes using the newest & better IDE - Android Studio - and a thorough process from developing you idea > mockup > coding > polishing > distributing.
Citation preview
Android Programming 101for NTU Workshop 2013
About Me
Name
Work at
No of apps
Find me at
Junda Ong
Hoiio
20+
just2mecom samwizecom
samwize G+
Hoiio API
Hoiio Business Communication
Hoiio Phone
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
About Me
Name
Work at
No of apps
Find me at
Junda Ong
Hoiio
20+
just2mecom samwizecom
samwize G+
Hoiio API
Hoiio Business Communication
Hoiio Phone
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Hoiio API
Hoiio Business Communication
Hoiio Phone
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Hoiio Business Communication
Hoiio Phone
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Hoiio Phone
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
My Hobby Projects
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
txeet
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
SG 4D
BAD Example of Porting
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
About You
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Todayrsquos Programme
8am - 10am Setting Up Android Studio
10am - 12pm Introduction to Android Programming
12pm - 1pm Lunch
1pm - 5pm 3 x hands-on (each 1 hr)
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Objectives
Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Pre-requisite Java Programming
Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Introduction to Android
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The Android OS
bull Linux Kernel
bull Write in Java code
bull Dalvik Virtual Machine
bull Application Framework
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Android Architecture
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Platform Versions
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Development Process
Design
Develop
Distribute
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Learn how to Design
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
bull PrinciplesGuidelines
bull UI Components
bull Common Patterns
Understanding Design
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Design Principles
bull Simple
bull Looks the same act the same
bull Customizable
bull Icon style
bull Donrsquot mimic iPhone UI
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
UI Components
bull Buttons
bull Text Fields
bull Dialogs
bull Spinners
bull Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Change view on a set of data
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Select multiple items
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Dashboard
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Devices amp Resolutions
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
dpi = dots per inch
for graphics
for fonts
dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)
sp = scale independent pixels
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
App Icon
48x48 dp
48x48 px 72x72 px 96x96 px 144x144 px
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Learn how to Code
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
AndroidManifestxml
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
4 Main Components
1 Activity
2 Service
3 Content Provider
4 Broadcast Receiver
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Activity
bull Activity = Screen
bull An app is made up of 1 or more activities
bull Stack of activitiesscreens
bull Activity lifecycle
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
bull App-X can activate App-Y component
bull Intent
bull App-X can access App-Y shared data
bull Content Resolver
Activity
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
HelloWorldActivity
Activity class has functions to handle onCreate onResume onPause etc
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Activity
bull Launch an Activity by calling startActivity(intent)
Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)
Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Activity
bull Activity must be declared in AndroidManifestxml
ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt
HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Service
bull Service runs in the background even when user is not interacting with your app
bull Service or Thread
bull To start call startService()
bull Similar to Activity has its lifecycle and various event callbacks
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
ContentProvider
bull A way to share data across applications including apps such as phonebook calendar etc
bull You can access the phonebook data using a ContentResolver
bull Have query insert delete methods (SQLite)
ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo
projectionselection selectionArgsortOrder)
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
BroadcastReceiver
bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
User Interfaces
Slides on httpwwwslidesharenetsamwize
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
View Hierarchy
1 View - Android UI component view or widget 2 ViewGroup - Layout or container view
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
View
bull UI components can be found in androidwidget package
bull Basic UI
bull TextView
bull Button
bull TextField
bull Progress bar
bull List
bull etc
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
ViewGroup(aka layout manager)
A simple LinearLayout
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
ViewGroup
TableLayout
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
ViewGroup
RelativeLayout
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
User Interfaces
bull 3 ways to construct UI
1 Drag-and-drop interface builder
2 XML
3 Code
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
looks in resvaluesstringxml and find the value for the key ldquohellordquo
Equivalently
androidtext=Hello world too
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The way of XML
ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt
reslayoutmainxml
Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
setContentView() inflate mainxml and set the views
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The way of Code
package comjust2ushelloandroid
import androidappActivityimport androidosBundleimport androidwidgetTextView
public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)
Creating a TextView and set the text
Similarly to the way of XML setContentView()
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Preferences
bull The easiest way to store information
bull NOT only store preferencessettings but also arbitrary key-value pairs
bull SharedPreference class
bull getBoolean setBoolean etc
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile
Override protected void onCreate(Bundle state) superonCreate(state)
Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)
Override protected void onStop() superonStop()
We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)
Commit the edits editorcommit()
Preferences
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Network
bull Connect to web services over HTTP
bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt
bull A few different ways to connect
bull HttpClient is most robust
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Network - GET
HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)
Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)
sbappend(line + NL)inclose()String content = sbtoString()
Do what you need with content
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Network - POST
HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)
Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))
Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia
bull Camera
bull Playback audio and video
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - Camera
bull 2 ways to capture photo
bull Using capture intent
bull Using Camera class directly
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
Capture photo
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri
Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)
create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name
intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high
start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)
Capture video
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user
Handling after photovideo is captured by camera app
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - MediaPlayer
bull Play audio and video from
bull resraw
bull File system (internal or external)
bull Stream over Internet
bull MediaPlayer class
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Multimedia - MediaPlayer
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()
Playing resrawsound_file_1mp3
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
1 Hello World [60 min]
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Objectives
bull Create new project
bull Understand project structure
bull Navigate in Android Studio
bull Run amp Debug
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Demo
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Project Structure
Java Code
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Project Structure
Resources
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The steps in brief
bull Create new project
bull Change App name
bull Run
bull View logs
bull Debug
Refer to hand-out 1 notes
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
2 Stopwatch [60 min]
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Objectives
bull Create widgets in design mode
bull Edit widgets in XML text mode
bull Code how stopwatch works
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Demo
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The steps in brief
bull Create 2 buttons
bull Edit the names and id
bull Code the stopwatch logic
Refer to hand-out 2 notes
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
3 Polish Stopwatch [60 min]
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Objectives
bull Create Responsive Layout
bull Style the UI
bull Enhance UX
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Demo
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
The steps in brief
bull Edit layout
bull Add background image
bull Custom font
bull Button with background image
bull Button with states
Refer to hand-out 3 notes
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Whatrsquos Next
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Database
bull Tabular data
bull SQLite behind the scenes
bull Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)
DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)
Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Database
bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object
bull With SQLiteDatabase call query() to execute SQL queries
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
More Topics
bull Location (GPS) and Map
bull Bluetooth
bull USB host and accessory
bull Animation
bull OpenGL ES
bull Push Messaging (GCM)
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Arduino amp Bluetooth
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom
Important Resources
bull httpdeveloperandroidcom
bull httpstackoverflowcom
bull httpwwwgooglecom