Programming for Mobile I

Why Look at Mobile Programming in This Course?

  • A great example of a rapidly changing area
  • To get exposure to programming with more hardware constraints (although this is quickly changing as well)
  • It is an example of event-based programming

Event Based Programming

  • So far the programming we have been doing has focused on a set of instructions to be executed roughly in sequence
  • Instead of providing the order to execution when programming, we can define handlers that will be executed in response to a specific event
  • Events are sent from a dispatcher
    • In the case of web programming, the dispatcher is the web browser
    • In the case of mobile programming, the dispatcher is part of the mobile OS
    • The dispatcher could be hardware based too, like a sensor ( see NodeBots )
  • The alternative to using events would be to program an instruction to check the status of something through out your code

The Current State of Programming for Mobile

  • iOS
    • Programming was primarily in Objective-C until 2014
    • Apple introduced its own language to replace Objective-C called Swift in 2014
  • Android
    • Programming is primarily done in Java*
    • What we will look at in this course
  • Everything else
    • Windows - C#, C++ and related langauges
    • Blackberry - C, C++ traditionally, have released a few Android phones so far...

Android

  • Android is an open source operating system whose development is shepareded by Google
  • The core of the operating system is based on Linux (C and C++)
  • The primary language for development is Java
    • Android also allows code to be written in other languages, and while it is theoretically possible to write an entire application in another language, the intent is to write at least the GUI code in Java

Resources

Java on Android

  • While programming for Android uses Java, and its syntax, there are some notable differences
  • The byte code generated during compilation is different
    • The Dalvik byte code has different instructions then standard Java byte code
    • The architecture of the virtual hardware in the virtual machine is different
  • In the most recent Android versions, the byte code is compiled to phone-dependent native code upon installation

Developing for Android

  • The Google sanctioned enviroment for creating Android applications is Android Studio
    • Free
    • Based on the IntelliJ IDE
    • Includes Android Emulators
  • Generates the file structure of an application for you

Android Program Basics

  • The GUI is defined in an XML file
  • The Java Code is used to define how interactions happen and the logic of the program
  • Is this similar to any other setup?
    • Why use XML?

Android App Layout

  • Can be created through drag and drop in Android Studio or by coding the XML
  • We will be focusing on the XML today
  • A single screen the user sees is called an Activity in Android

Layout

  • In the simplest android applications, the top level element in the XML will be a Layout tag
    • In addition to grouping the widgets on the screen together, the Layout tag tells the application how the widget should be laid out
  • Main Layouts
    • LinearLayout
    • RelativeLayout
    • GridLayout

ID Attribute Syntax

  • Android uses special syntax in the attributes of elements to save typing
  • One of the attributes that uses some shortcuts is android:id
    • Internally the ID is a number, so by prefixing it with an @ sign, we letting the XML parser know this is a string placeholder that needs to essentially be dereferenced
    • To declare a new id, place the + after the @ sybol
    • When referencing, don't use the +
<TextView android:id="@+id/anID" />
<TextView android:layout_below="@id/anID" />

Buttons

  • There are two main types of buttons in Android
    • Button which is used for text buttons and text and image combination buttons
    • ImageButton which is used for a button consisting of only an image
    • The button's main event is onclick
  • For an image button, the src attribute indicates where in the projects res folder the image is found
<Button
                android:text="New Button"
                android:id="@+id/button"/>
<ImageButton
                android:src="@drawable/IMAGE"
            />

EditText

  • The EditText element is used for all types of text input
  • The specific type of input is set with the android:inputType attribute
  • Specifying the type of input is perhaps more important on mobile than the web
    • The user does not have a full keyboard available
    • The input type will help indicate the default type of keyboard for that input
  • By default, there are no events for EditText, but you can add a button to be displayed when the text field is opened

Common inputTypes for EditText

  • Android comes with many many different inputTypes
  • Common ones:
    • text - Plain text
    • textAutoCorrect- Text that autocorrects
    • textPostalAddress - A postal address
    • phone - A phone number
    • number - Any number

CheckBox

  • CheckBox is used to creat a checkbox
  • A user can select any number of checkboxes
    • In Android they are not formally grouped because of this
  • Each checkbox specifies an onClick handler, but multiple checkboxes can use the same one
<CheckBox
        android:text="Checkbox Text"
    />

RadioButton

  • Radio buttons represent a question where once choice may be selected
  • Because multiple radio buttons represent a choice for the same question, they are grouped together in a RadioGroup
  • The element that holds the radio button itself is RadioButton
  • Just like CheckBox each radio button has its own onClick attribute
<RadioGroup>
    <RadioButton android:text="Radio Button 1"/>
    <RadioButton android:text="Radio Button 2"/>
</RadioGroup>

ToggleButton / Switch

  • ToggleButton ans Switch both represent something that can be on or off
  • A ToggleButton looks like a regular button, but can either be depressed(on) or not depressed(off)
  • In Android 4, Switch was introduced, which uses a slider to show both options at once, and which is currently selected
<ToggleButton
    android:textOff="OFF"
    android:textOn="ON" />

<Switch 
    android:text="Switch Label" />

Spinner (Dropdown)

  • A Spinner is the Android term for a dropdown interface, like select in HTML
  • The Android documentation recomends if you have more choices than can fit on a screen horizonitally, to use a Spinner rather than a CheckBox
  • The entries for a Spinner are defined either programatically or through a seperate XML file with the choices
    <Spinner
    android:entries="@array/ChoicesFromFile" />
    

Images

  • To display an image, the XML is almost idenctical to an ImageButton
  • The element is named ImageView
  • Once again, the location of the image it defined by the android:src attribute
<ImageView
        android:src="@drawable/ImageFile" />

The Static Class R

  • As part of the building process, a static class known as R is dynamically created
  • This class holds constants that refer to all the resources specified in the res directory
  • For example, to get the numerical id associated with the id string "myId"
    int numericalId = R.id.myId;
    

The Activity Class

  • As mentioned last class, each screen in an application is known as an activity
  • All activities have their own class, which inherits from Activity or one of Activity's subclasses
  • There are several methods that should be overridden, the most important being onCreate
    • This is the first method called when the Activity starts up
    • This method is responsible for specifiying the layout file and setting up any event listeners usually.
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }
}

Acessing Elements

  • Another method inherited from the Activity class is findViewById
    • This method takes an integer id and returns the View object coressponding to the UI element
    • Use the R class to get the interger Id
  • This method returns a View object, but the element we are getting is usually a subclass of View
    • The return value should be casted to the appropriate subclass

Input Events

  • Android provides two ways to attach event handlers
    • The attachment method dictates how the event handler is implemented
  • The event handler is always passed an object of the View class, which is the base class for all UI elements
    • This object represents the specific UI element that the event was triggered from
  • Common events for input are onClick, onLongClick, onKey, and onFocusChanged

Attaching Events in the XML

  • The simplest way to attach event handlers is through use on an XML attribute
  • To attach the handler for the onClick event to a button, use the following:
    <Button
                  android:text="New Button"
                  android:id="@+id/button"
                  android:onClick="aMethod"/>
    
  • The value of android:onClick is the name of a method located in the activity class
    • The method must be public and return void
    • The method must take one parameter, a View object

Attaching Events Programatically

  • Attaching events in XML is convient, but quickly becomes hard to manage
  • It is also necesarry sometimes to change the event handlers dynamically
  • Android offers methods to attach events programatically
    Button myButton = (Button) getViewById('myButtonId');
    myButton.setOnClickListener(new MyListenerObject());
    

Listener Classes

  • The MyListenerObject in the previous code is a class created by the programmer
  • The class must implement the approriate Listener interface.
    • For an onClick event, the class will implement OnClickListener
    • Each interface only has one method to override, which is named after the event, ie onCLick
      class MyListenerObject implements OnClickListener{
            public void onClick(View v) {
                \\Respond to event
            }
      }
      

Events on the Activity Itself

  • Sometimes it is useful to list to events on the activity
  • These can serve as default events
    • ie onTouchEvent will handle all clicks,etc not handled by the UI elements themselves
  • Some events are to enable your program to be a "good citizen" in the OS enviroment
    • The onLowMemory event is triggered when the OS is low on memory and all applications should evaluate their memory and free any unneeded memory.
  • All events on the Activity are methods implemented directly in the activity class