Sunday, November 23, 2014

Coursera Content provider Exercise - week 8

This lab will build off of the week 7 Location lab. This application will have the same UI elements and behaviors as the week 7 Lab.

This application, however, manages a user's Place Badges using a ContentProvider.

Because ContentProviders persist data across application sessions, when the application initially starts up, it should get all existing Place Badges from the ContentProvider and display them on the screen.

PlaceViewAdapter extends CursorAdapter - see
- Adapter that exposes data from a Cursor to a ListView widget.
- swapCursor() : Swap in a new Cursor, returning the old Cursor.

This is the most important reason why you have to use swapCursor, it doesn’t close the Cursor when you swap it with another Cursor

- content: scheme indicating data that is managed by content provider
- authority: id for content provider
-path: 0 or more segments indicating type of data accessed
-id : optional is specific record within dataset

Provider: ContentProviderCustom

course.examples.ContentProviders.StringContentProvider.StringsContentProvider class

public synchronized Uri insert(Uri uri, ContentValues value) {

User: ContentProviderCustomUser

DataContract class:
public static final String _ID = "_id";public static final String DATA = "data";public static final String DATA_TABLE = "data_table";
private static final Uri BASE_URI = Uri.parse("content://course.examples.ContentProviders.StringContentProvider/");
// The URI for this table.
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI,

CustomContactProviderDemo class:
ContentValues values = new ContentValues();
// Insert first record
values.put(DataContract.DATA, "Record1");
Uri firstRecordUri = contentResolver.insert(DataContract.CONTENT_URI, values); 

Coursera Location Exercise - week 7

The screencast for the assignment demonstrates a ListView containing a set of Place Badges.

There is a context menu in this application with a list of preconfigured locations.  The user will click on the context menu and select one of the menu items, specifically "Place One", "Place Two," or "Place No Country."

The application will be set up to listen for the context menu selections.  Moreover, when one of the menu items is chosen, the app will receive the corresponding location details.

The footer for the ListView displays the words "Get New Place." When the user clicks on the footer, the application will go out and retrieve  the place Badge based on the user's current location. Although,  when the application first starts, the user will not have any Place Badges.

Each Place Badge contains
  • a country flag
  • a country name
  • place name corresponding to the user's location when the Place Badge was acquired

For the case when the user clicks on the footer and the application does not already have a Place Badge for the location, the application will create and execute an AsyncTask subclass called PlaceDownloaderTask that acquires the data needed to create the Place Badge. As well, the application should prevent the user from clicking on the footer when the application has not selected  a valid user location.

The ListView documentation details how you work with this type of widget, such as dealing with footers.

The HelloAndroidWithMenus example application demonstrates how to of work with a context menu. 

The applications listens for location updates from a network connection. You have to create an account at Your username will need to be updated in

Coding details:

PlaceViewActivity extends ListActivity

- ListView placesListView is the list view used in the Activity
        placesListView. setFooterDividersEnabled(true);
                 - Enables or disables the drawing of the divider for footer views.
        mAdapter = new PlaceViewAdapter(getApplicationContext());

- private PlaceViewAdapter mAdapter;
implementation class provided,  extends BaseAdapter, makes use of a PlaceRecord class
- set up a Location Manager

(LocationManager) getSystemService(Context.LOCATION_SERVICE);

- private MockLocationProvider mMockLocationProvider : 
implementation class provided, has method to push a Location instance which specifies the longitude,latitude, altitude, time, elapsedRealtimeNanos. Note that the LocationManager class has a method called setTestProviderLocation()

On Resume : you start listening for location updates, get last known location if reading was recent

mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mMinTime, mMinDistance, this);

mLastLocationReading = new Location(mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)); 

Context Menu change handler method :

onOptionsItemSelected(d(MenuItem item)) - pushes location to the MockLocationProvider

ClickListener for the footer:

get a location reading:
mLastLocationReading = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if there is a reading:
if ((currentLocation != null) && (ageInMilliseconds(currentLocation) > ageInMilliseconds(mLastLocationReading))) {
           mLastLocationReading = currentLocation;

if there was already a place for this location in list:
"You already have this location badge",

Callback method used by PlaceDownloaderTask - check if the place you received has details, if so add it to list adapter:

                 boolean b = place.getCountryName().equals("");
                 if (b==false){
                 }  else {
                    "There is no country at this location",                     Toast.LENGTH_LONG).show();

Friday, November 21, 2014

Coursera (Week 8) DataManagement , Content Providers, and Services


Manage data across multiple application sessions

SharedPreferences class - small primitive data i.e. username, account name, user customizations
- persistent Map : key value pairs of simple data types
- automatically persisted across application sessions
- long term storage of customizable application data
- to get SharedPreferences class within an activity,  use Activity.getPreferences (int accessmode) - example of mode is MODE_PRIVATE
to get SharedPreferences class NOT within an activity,  use Context.getSharedPreferences(String name, in accessmode) - name example could be name of shared preferences file
- after saving object, can edit file using SharedPreferences.edit() method returns SharedPreferences.editor instance - putInt(key,value), putString(key,value), remove(key)
- SharedPreferences.editor.commit() to persist
- read it later SharedPreference object - getAll(),  getBoolean(key) , getString(key)

DataManagementSharedpreferences app

File - storage area internal (smaller, application private data sets) or
external (larger non private)
Internal device storage - medium amount data private  i.e. temp files
External device storage - large amount non private i.e. songs, pictures

File API - FileOutputStream - openFileOutput(String name, int mode)
- open private file for writing
- openFileInput() for reading
DataManagementFileInternalMemory app
- see if its exists, otherwise opens it, writes text to it, reads text, displays its
Context.openFileOuput method() - passed in an integer, Context.MODE_PRIVATE: only be accessed by applications sharing the same user ID as the calling application

databases - private structured data Complex SQL Lite databases

External memory - removable such as sdk card, appear or disappera without warning, first determine state of external emmory


DataManagementFileExternalMemory app

Cache files - temp files, cache directories, may be deleted when storage is low

- in memory relational database with small footprint

SqliteOpenHelper class
call super() from sublclass
override OnCreate() and onUpgrade()

DataManagementSql app
-DatabaseOpenHelper extends SQLiteOpenHelper
- android.database.Cursor

ContentValues values = new ContentValues(); values.put(DatabaseOpenHelper.ARTIST_NAME, "Frank Sinatra"); mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values); values.clear();

ContentValues values = new ContentValues();
values.put(DatabaseOpenHelper.ARTIST_NAME, "Johnny Cash");     mDbHelper.getWritableDatabase().update(DatabaseOpenHelper.TABLE_NAME, values, DatabaseOpenHelper.ARTIST_NAME + "=?", new String[] { "Jawny Cash" });


emulator terminal:
# adb -s  emulator-port# shell

#sqlite3 /data/data/course.examples.DataManagement.DataBaseExample/databases/artist_dbd

#sqllite3 -help


Fundamental component android : content providers - centralized repos of structured data
data to be shared across multiple app - inter-application data sharing
ContentResolver class
- databae style interfaxe for read write data
- notifies addtl services such as notify when data changed

Code running in one process access data in another process

standard content providers
Call Log
user dictionary
Represented as database table

Use URI - content providers referenced by URI

- content: scheme indicating data that is managed by content provider
- authority: id for content provider
-path: 0 or more segments indicating type of data accessed
-id : optional is specific record within dataset

example content://

following classes applications use to identify and access a ContentProvider:
- ContentResolver, URI


query returns a cursor, has input parms such as URI, columns , selection pattern, pattern args, and sort order

ContentProviderWithCursorAdapter app

- contacts provider and photo
- columns specified
- ContentResolver class reference
-query string pattern
- sort order
- query which returns cursor
-bindView method fills in view

CursorLoader - can take while to complete, avoid intensive operation
this class uses async task so its done on background thread
LoaderCallbacks interface
initLoader() - init and activate loader

callback onCreateLoader()
callback onLoadFinished()
callback onLoaderReset - previous loader reset

ContentProviderWithCursorLoader app
- getLoaderManager().initLoader(0,null,this) - this callback

onCreateLoader() method -  query returns new CursorLoader

onLoadFinished() - swap new cursor that is passed in into List adapter
OnLoaderReset() - called when last cursor to finished method is about to be closed


uri, sql pattern, pattern args

uri , parms

new field values, pattern

ContentProviders/ContactsListInsertContacts  app

mAccountList = AccountManager.get(this).getAccountsByType("");
-permission  android.permission.GET_ACCOUNTS

getContentResolver.applyBatch - does inserts all at once

Create content provider -

Implement storage system
Define a Contract class
ContentProvider subclass with insert,delete, etc
Declare it in manifest file

ContentProviderCustom app
- StringsContentProvider class
- delete method
- DataRecord object
-query method with MatrixCursor

manifest file is a provider tag
- exported to true

ContentProviderCustomUser app


Service class

Fundamental component - long running processes

work in background, one process interact with another process

remote method execution

starting it:
run in background indefinately
perform single operation, and dont transfer results
by default run on main thread
 - allows component to send requests and receive responses from a local or remote service
at binding time, start service if not started already. will run as long as one client connected


Tuesday, November 18, 2014

Links i have learned about lately - Spring Boot, Spring Data, Spring Rest and JQuery UI (see GalleryRepository class , PagingAndSortingRepository)


Angular sub topics

A few weeks ago I used angular to create a sample app.  That was a good experience. In keeping with learning more Angular,  I came a cross a podcast blog Adventures in Angular. The first episode i listened to was . This talk had training videos sessions:

Meetup Angular and bootstrap - see Plunkr
Utah Angular user group
Testing with Angular

Pluralsight has training on bootstrap 3 as well.

Wednesday, November 12, 2014

Coursera Android week 7 : Sensors, and Maps/Location

Sensors  Part 1 Presentation and Slides

Context aware computing
- location, how held, ambient light, how fast traveling with sensors

Sensors - measure physical environment such as motion, position in world or orientation, environment

motion 3 axis accelerometer - forces exerted on device such as shake

position 3 axis magnetic field  - orientation in respect to magnetic field

environment- atmospheric pressure

SensorManager manages sensors

instance to sensor manager - getSystemService(Context.SENSOR_SERVICE)

access to specific sensor SensorManager.getDefaultSensor (int type)


SensorEventListener - interface callback manager when accuracy changes and new reading

onAccuraccyChanged (Sensor sensor, int accuracy) : accuracy changed

onSensorChanged (SensorEvent event) - new reading

unregister/register with SensorManager using SensorEventListener

- public boolean registerListener ( SensorEventListener listener, Sensor sensor, int rate)
- public void unregisterListener ( SensorEventListener listener, Sensor sensor)

SensorEvent - represents a sensor event
data is sensor specific , sensor type, time stamp, accuracy, measurements data

x right to left
y bottom to top
z down to up

AccelerometerRaw app

// Get reference to SensorManager
SensorManager  mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

// Get reference to Accelerometer
mSensorManager .getDefaultSensor(Sensor.TYPE_ACCELEROMETER)))

mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);


Sensors Part 2

Accelerometer values

transforms to smooth out data
low pass filters
- deemphasize small transient force changes
- emphasize constant force changes

such as when hand shakes ie carpenters level

high pass filters
- emphasize  transient force changes
- deemphasize constant force changes

ignore gravity, but specific moves . i.e. how user shakes device

SensorFilteredAccelerometer app

SensorCompass app - accelerometer and magnetometer

// Get a reference to the magnetometer magnetometer = mSensorManager .getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);

// Users the accelerometer and magnetometer readings
// to compute the device's rotation with respect to
// a real world coordinate system - Converts device coordinates into world coordinates.
SensorManager.getRotationMatrix(rotationMatrix, null, mGravity, mGeomagnetic);

// Returns the device's orientation given // the rotationMatrix SensorManager.getOrientation(rotationMatrix, orientationMatrix);

Location & Maps  Part 1 Presentation and Slides

Location aware
- Find X from users location, Direct user from current location to place Y

Define GEOFence

Location class - position on earth
Location instance consists of:
  • Lattitude -required
  • Longitude -required
  • Timestamp -required
  • Accuracy
  • Altitude
  • Speed 
  • Bearing

Location from LocationProvider and devices have access to multiple Location providers.
- represents a location data source
- actual data may come from GPS,Cell towers, wifi access pts
- may request info from network (wifi/cell), gps (satellite), passive (piggy back on readings from other apps)

Network Provider - determines location based on cell and wifi
- permission is android.permission.ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
- cheaper, less accurate,faster, availability varies

GPS Provider - determines location based on satellite
- permission is android.permission.ACCESS_FINE_LOCATION
- expensive, accurate, slower, outdoors

Passive Provider returns locations generated by other providers
- permission is android.permission.ACCESS_FINE_LOCATION
- cheapest, fastest, not always available

LocationManager class
- service for location data
- determine last known user loc
- register for loc updates
- register for intents when moves/leaves a specific geo area

LocationListener interface
-defines callback methods when lo or LocationProvider status changes

void onLocationChanged(Location loc)
void onProviderDisabled(String provider)
void onProviderEnabled(String provider)
void onStatusChanged(provider,status,bundle)

obtain location (first determine last location)
- start listening for updates from location providers
- maintain best estimate of location
- when estimate is good enough, stop listening to updates
- use best estimate

measurement time, accuracy are factors for best location

LocationGetLocation app - last known location

// Acquire reference to the LocationManager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)

// Get the last known location from all providers
List<String> matchingProviders = mLocationManager.getAllProviders();

for (String provider : matchingProviders) {
Location location =    mLocationManager.getLastKnownLocation(provider);
float accuracy = location.getAccuracy();
long time = location.getTime();

// Register for network location updates 
if (null != mLocationManager .getProvider(LocationManager.NETWORK_PROVIDER)) 

mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, POLLING_FREQ, MIN_DISTANCE, mLocationListener); 

// Register for GPS location updates
if (null != mLocationManager .getProvider(LocationManager.GPS_PROVIDER)) 

mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, POLLING_FREQ, MIN_DISTANCE, mLocationListener);

// Schedule a runnable to unregister location listeners 
Executors.newScheduledThreadPool(1).schedule(new Runnable() 
{ @Override public void run() { 
Log.i(TAG, "location updates cancelled"); 

always check last known measurement
return updates infrequently as possible - limit measurement time
use least accurate measurement as necessary
turn off updates in onPause()

Location & Maps  Part 2 Presentation

Location -> visualize real places using Maps

Google Maps Android V2 API

Normal Map - traditional road map
satellite - aerial photographs of area
hybrid map combine
terrain map - topographical details such as elevation
customize map add markers and ground overlays on top of map
map respond to gestures
indicate the user location using special marker

GoogleMap class
MapFragment class
Camera class
Marker class

set up maps :

Google Play services SDK
obtain API key
specify settings in Application Manifest xml file
add Map to project

<uses-permission android:name  = "android.permission.INTERNET" />

<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />

- download data
uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE: />

<uses-permission android:name = ""/>

also permission is android.permission.ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
- for location

MapEarthQuakeMap app

remember NetworkingAndroidHttpClientJSON app
- earthquake data in list view

// The Map Object
private GoogleMap mMap;

private final static String URL =
"" + UNAME;

new HttpGetTask().execute(URL);

mMap.addMarker(new MarkerOptions()
// Set the Marker's position
.position(new LatLng(rec.getLat(), rec.getLng()))

// Set the title of the Marker's information window

// Set the color for the Marker
 .icon(BitmapDescriptorFactory .defaultMarker(getMarkerColor(rec .getMagnitude()))));

// Should compute map center from the actual data mMap.moveCamera(CameraUpdateFactory.newLatLng(

same data but presented in a map with markers in Map of world, color indicates magnitude

Coursera Graphics assignment

When the user touches this empty screen, one new bubble should appear on the display.  
The bubble should then begin to move around the screen. The Bubble’s size, direction and speed should be randomized within limits explained in source code skeleton.  
Assuming the Bubble’s direction is up and to he right, the Bubble shown above might be in the following location after a couple seconds.  
As the user continues to touch empty spaces on the screen, more bubbles should be added.
If the user presses the screen at a location already occupied by a bubble, then the bubble should “pop.”  
That is, it should be removed from the screen and a bubble popping sound should be played.  
The sound file is in the skeleton code in the /res/raw/ bubble_pop.wav file.   
In addition, if the user executes a "fling" gesture starting at a location already occupied on the screen, then the application should change the bubbles current direction and speed to match the direction and speed of the fling gesture.

make a new SoundPool, allowing up to 10 streams - see :

  • SoundPool mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

set a SoundPool OnLoadCompletedListener that calls a  method- see :
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
if (0 == status) {

load the sound from res/raw/bubble_pop.wav -  see : 

mSoundID = mSoundPool.load(this, R.raw.bubble_pop, 1);

get all Views in mFrame one at a time

RelativeLayout mFrame;mFrame = (RelativeLayout) findViewById(;get all Views in mFrame one at a time// using the ViewGroup.getChildAt() methodmFrame.getChildCount();(BubbleView) mFrame.getChildAt(i); 

create the scaled bitmap using size set above - see :

final Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.b128);mScaledBitmap = Bitmap.createScaledBitmap(bitmap,mScaledBitmapWidth, mScaledBitmapWidth, false);

BubbleView extends View

  • setRotation(Random r) 
  • setSpeedAndDirection(Random r) 
  • createScaledBitmap(Random r)
  • startMovement() {
  • intersects(float x, float y)
  • stopMovement(final boolean wasPopped) {
  • synchronized void deflect(float velocityX, float velocityY) {
  • moveWhileOnScreen() 
  • isOutOfView()

Sunday, November 9, 2014

Polymer Step by Step

Create Elements page :
  • npm install -g bower
  • bower init
  • bower install --save Polymer/polymer
  • bower install --save Polymer/core-elements
  • bower install --save Polymer/paper-elements
  • bower install --save Polymer/core-ajax

Chrome Dev Editor


<!DOCTYPE html><html>
<!-- 1. Load platform support before any code that touches the DOM. -->
<script src="bower_components/platform/platform.js"></script>
<!-- 2. Load the component using an HTML Import -->
<link rel="import" href="elements/my-element.html"> </head>
<!-- 3. Declare the element by its tag. -->


         <link rel="import" href="../bower_components/polymer/polymer.html"> 
         <link rel="import" href="../bower_components/core-ajax/core-ajax.html"> 
         <polymer-element name="my-element" noscript>
             <span>I'm <b>my-element</b>. This is my Shadow DOM.</span>
             <core-ajax url="" auto response="{{resp}}">
             <textarea value="{{resp}}"></textarea> 


<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/core-ajax/core-ajax.html">

<polymer-element name="proto-element">
      <span>I'm <b>proto-element</b>. Check out my prototype.</span>
<script> Polymer({
                                ready: function() {
                                        // properties and methods here

API Guide

GDG Triangle Polymer Introduction

               [ core-elements.html#core-toolbar ] :

              <body unresolved> 
          [ paper-elements.html#paper-tabs ]

           <body unresolved fullbleed> 
              <core-toolbar class="medium-tall"> 
                    <paper-icon-button icon="menu"> </paper-icon-button> 
                    <div flex>Title</div> 
                    <paper-icon-button icon="search"></paper-icon-button> 
                    <paper-icon-button icon="more-vert"></paper-icon-button> 
                    <div class="bottom fit" horizontal layout> 
                          <paper-tabs selected="0" flex style="max-width: 600px;"> 
                               <paper-tab>ITEM ONE</paper-tab> 
                               <paper-tab>ITEM TWO</paper-tab> 
                                <paper-tab>ITEM THREE</paper-tab>

Polymer Player

    <template repeat="{{sng, i in songs}}">
       <div class="song" needZ?="{{song.title === sng.title}}"> 
             <div hero-id="{{sng.title}}" hero>
                  <div class="bg" style="background-image: url(images/{{sng.img}});"> 
                         <player-color-thief song="{{sng}}"></player-color-thief>
                  <div class="footer" style="background-color: {{sng.dominantColor}}; color: {{sng.textColor}};"> 
                        <span class="title">{{sng.title}}</span>
                        <br> <small>{{sng.artist}}</small> 

<polymer-element name="player-color-thief" attributes="song">

Monday, November 3, 2014

Coursera Graphics, Touch, Multimedia (week 6)

Graphics Part 1 Presentation and Slides

2D graphics, Static and Dynamic changing elements

ImageView , Canvas
Animate - Size, position, fading

Property animation

2D on display
  • Draw graphic to view (simple)
  • Canvas  (more powerful flexible) more complex, update it frequently
Drawable class
  • Bitmap, colors,
  • ShapeDrawable
  • BitMapDrawbable
  • ColorDrawable
Attach it ImageView

XML or programmatically

  • Simple image
  • Bubble Activity
XMLfile says relative with ImageView 250dp, centered
  • BubbleActivity
  • Set ContentView
  • Layout only outermost nothing inside
  • setImageDrawable
  • Layout properties
  • Dimens.xml file
  • RalativeLayout with rule
  • Sets props on imageview

  • Simple shapes
  • Subclass of Shape such as PathShape, RectShape, OvalShape
  • Cyan color and magenta colored, overlap, intersect has different color
  • ShapeDrawACtivity
XML file RelativeLayout w 2 imageviews, 250dp
Android.src in res/drawable directory

  • shapeDrawActivity
  • Relative layout
  • Width,height,padding
  • ShapeDrawable
  • Color, height, transparency
  • Sets padding
  • Aligns it programmatically
Drawing with canvas
Bitmap:matrix of pixels
Canvas- drawing to bitmap
Drawing primitive - Rect,Path,Text,BitMap
Paint object - colors, styles

Paint class - set syle parameters w thickness size, color, anti-aliasing (smooth out)

4 rectangles - difft size style, difft border width, style, background color

setContentView with XML file
LinearLayout - 4 children TexView
Color, Size,typeface
Background xml file in res/drawable where shape is rectangle with solid color

Paint affects Text Size LineWidth

Graphics Part 2 Presentation

Drawing with Canvas - underlying bitmap

generic view (less frequent to onDraw() method) or SurfaceView (frequent update)

CustomSurfaceView sublclass , GraphicCanvasBubble application - draw view and then infrequent updates to view, thread that wakes up moves view and redraws it
postInvalidate() - thinks must be redrawn, canvas draw method

CanvaswithSurfaceView - separate non UI thread, surface dedicated drawing area, extend SurfaceView implement SurfaceHolder.callback method
Setup surface view (surfaceView.getHolder() method to get SurfaceHolder, register for callbacks with addCallback method - surfaceCreated() method , surfaceChanged() method - size changed , surfaceDestroyed() method, create thread for drawing - get lock to canvas method , drawBitmap, unlock canvas ).


Graphics Part 3 Presentation

Simple kind animation so far changed properties, Size, position, etc


Left most cyan, fades into magenta
TransitionDrawable from shape_transition.xml
Transition contains 2 items
setImageDrawable on ImageView


Animates series of drawables
Splash screen, with images counting down  to final image
view_animation .xml
animation-list with item inside it
Sets imageView as background
onWindowFocusChanged method

- create animations which transformations made to contents of view
Bubble view, animate changes to bubble
Transformations fade in, rotate, move, change size, fade out
Some are at uniform pace while other do not
view_animation.xml in res/anim dir
Alpha , rotate, translate, scale,
onWindowFocusChanged method

Property Animation

More than property change son views here
Changing general propertiy changes over given time
ValueAnimator - time interpolator
Changes as function of time
AnimateUpdateListener - every anim change this is called
TypeEvaluator interface - class a property value at given pt in time

Aniimate color red rectangle appears and will change color , slowly turns blue

Starting and ending points of animation

Creates button starts animation

ValueAnimator object - ofObject method

onAnimationUpdate method

Calls start for animation

Same as graphics tween
ViewPropertyAnimator class

Property Animation system, if you need to animate your own custom classes, which one of the following classes would implement in order to compute the specific property values being animated - Type interpolator

Touch and Gestures Part1 Presentation and Slides

MotionEvent - actioncode is type of motion, time, which device came from, how hard pressed

FingerTouchEvent - touch screen

MultiTouch Device

- emit one movement trace per touch source

- each touch source pointer - unique id, group multiple pointer per motion event, group has index
- getsure event - ACTION_DOWN - started touch screen, ACTION_POINTER_DOWN, ACTION_POINTER_UP - one of fingers has stopped touching screen, ACTION_MOVE - fingers have changed position, ACTION_UP - fingers touching have stopped touching it, ACTION_CANCEL - premature cancelled gesture

rules - touch go down one time, in groups
getActionMasked() - action code w motion event
getActionIndex() - index of pointer associated with action code
getPointerId(id pointerIndex) given index stable id of pointer associated with that index
getPointerCount - number of pointers associated w moytion event
getX(pointerIndex) getY(pointerIndex) - coordinates of pointer stored at current index
findPointerIndex(int pointerId) index associated with current pointer id

Handling Touch Events on View

onTouchEvent method - process motion event
register to receive OnTouchListener
onTouch() called a touch event occurs, called before it delivers event to touched view, returns true if it consumes event, false otherwise

multiple touches combined to form a more complex gesture - double tap is example.

TouchIndicateTouchLocation app - draws circle where user touches screen


OnTouch() - looks at actioncode


Touch and Gestures Part2 Presentation

GestureDetecture - common gestures, single tap, double tap, drag

- OnGestureListener
OnTouchEvent - touched , must be overridden

TouchGestureViewFlipper app
right to left fling gesture

ViewFlipper class in activity
new GestureDetecture


onFling() - checks velocity

fling, scroll, long press

GestureBuilder Application comes with sdk

GestureLibraries class

GestureOverlayView  class - it intercepts user gestures invokes gestures

/mnt/sdcard/gestures  to /res/raw

TouchGestures app - swiping with View

Gray with green square in middle

checkmark yes gesture or no gesture like a circle

OnGesturePerformedListener method

GestureOverlayView - intercept user gestures


onGetsurePerformed method calls recognize method

Multimedia Part1 Presentation and Slides

Rich multimedia content - audio,image, movies

encoding/decoding formats

AudioManager  class- volume, system sound effects, ringer


load and play affects , manage volume, manage peripherals

SoundPool class - audio samples

AudioVideoAudioManager app -up down button, play button of bubble sound

AudioManager reference , playSoundEffect method

SoundPool object


RingtoneManager  - audio clips phone call, email, etc


Ringtone,Notification, or Alarm

in settings , can change ringtones



What data types can be used to identify a Ringtone when attempting to retrieve a Ringtone using one of the RingtoneManager.getRingtone() methods? Its an int or URI

Multimedia Part2 Presentation

MediaPlayer - audio and video in app and control playback with state machine

MediaPlayer class - allow apps to attach listeners, allow apps to set media stream to play backusers control media playback,

setDataSource - which stream play
prepare() - syncronous
start() start playback
release() - release resource

VideoView - subclass of SurfaceView video from multiple sources

AudioVideoVideoPlay app - trip to moon



pass in URI in res/raw directory

setOnPreparedListener method

MediaRecorder  - record auio and video ,state machine


AudioVideoAudioRecording app
two toggle buttons recording , playback




Before MediaRecorder.start()
-setAUdioSOurce(), setOutputFile(), setOutputFormat()


Camera service, manage settings , start/stop preview, camera permissions

uses-permission    android.permission.CAMERA


get camera instance,

set camera parms
setup preview
start preview
take picture process data
release camera

AudioVideoCamera app

Camera class - call open()
SurfaceView() and adds callback
- created withSurfaceHolder
stopPreview() method
takePicture() method

Suppose your application wants to use the Camera. Which of the following actions will it likely need to perform?Get the Camera instance. Set Camera parameters. Set up the Preview display. Start the Preview. Take a picture. Release the Camera instance.

Saturday, November 1, 2014

DevFest at American Underground 2014

The Dev Fest is organized by  Luke Dary  +Luke Dary .  Next GDG meeting possibly will  be held in the Google office in Chapel Hill. Udacity will be partnering to do Android development course thru GDG.

Polymer  #itshackademic

Intro Video

Rob Dodson - Core Icons

what problems solving?   css is global , phone/tablets,smart tvs  etc  Front end development so it works on all devices. i.e Tabs should be easy, not easy to plop in anywhere. old frameworks can be a challenge,


tip: do a  view source of gmail
table soup, div soup
web components
-  required to have dash in name to be custom element (otherwise show as unknown)
- paper tab (material design )
- resusable
-  templates -native client side  , parsed, does not render, content inert til cloned/used,
- shadow dom - browser not rendering all, chrome has ability to show hidden structure you dont usually see
- html imports <link rel="import" href="bootstrap.html">      vulcanize - tool to concat your dependencies and do it once
- custom elements : use existing, extend others, encapsulated css