Mobile Programming Lecture 1

Mobile Programming Lecture 1

Android Programming Lecture 4 Activity, Intent and UI Superclass Constructor Interface Inner class 2

RoadMap and Learning Objectives Learn to use the basic UI widgets Learn to switch Activities using Explicit Intent 3 UI Development 4 Basic Input Controls Input controls are used to take data from user

o Widgets TextView Button CheckBox RadioButton Spinner o Text Fields o Dialogs 5 Text Fields Text Fields allow users to type text in your application. Text Fields have different types like: o

o o o o o o o o o Plain Text Person Name Password Email

Phone Postal Address Multiline Text Time Date Number (Signed/Unsigned) All of the Text Fields mentioned above are merely attributes of EditText http://developer.android.com/guide/topics/ui/controls/text.html 6 Text View TextView is used to display

text on screen. o EditText, Button are direct subclasses of TextView. TextView doesn't allow editing in itself It works more like a label http://developer.android.com/reference/android/widget/TextView.html 7 Buttons Buttons allows user to perform some action. Android have following button types available, sequence

is Control Name (Class Name): o Button (Button) o Image Button (ImageButton) o Toggle Buttons (ToggleButton) o Radio Buttons (RadioButton) All buttons have different classes and XML tags to represent them unlike the Text Fields (That had only one tag i.e. EditText) http://developer.android.com/guide/topics/ui/controls/button.html 8 ImageView

ImageView is used to display an image. Can load images from various sources, e.g., drawables/content providers. Various other display options available like scaling & tinting. 9 R.java R.java: hook the resources and java by providing each resource item an ID

Reference a resource in Java codes [.]R.. o : name of the package in which the resource is located (not required when referencing resources from your own package). o : resource type. o : the resource filename without the extension or the android:name attribute value in the XML element. findViewById(R.id.***): identify a view on XML by its id setContentView(R.layout.***): apply the layout for the content view 10 Demo

11 Create a project, and open the layout xml file to make the layout as follows. TextView EditText Button 12 Create an id for the Button,

EditText and TextView, respectively. This is by specifying the android:id attribute, with formate @+id/anId You can arbitrarily name the id, but make sure that the id is unique 13 Open the MainActivity.java file in the java directory. The codes look like below. This is created automatically by the template. You may have more codes over

there. If that is the case, no worries. You probably just adopt another template and it is also going to work. In the next slides, we are going to elaborate on the codes. 14 This defines a package, and include your MainActivity class in the package. My project is named as EditGreeting. So the package name is com.example.editgreeting. You may have different package name here as you use another project name. Can you roughly guess the directory of your MainActivity.java file based on the package name? Do you have an idea why we use a reversed order of the organization for the package name?

15 This imports an package, which define the Activity class. You can find the source file in your ADT directory \sdk\sources\android-22\android\app 16 This defines a package, and include your MainActivity class in the package. Can you roughly guess the directory of your MainActivity.java file based on the package name?

This imports an package, which define the Activity class. You can find the source file in your ADT directory \sdk\sources\android22\android\app Declare a class 17 This defines a package, and include your MainActivity class in the package. Can you roughly guess the directory of your MainActivity.java file based on the package name?

Declare a class This imports an package, which define the Activity class. You can find the source file in your ADT directory \sdk\sources\android22\android\app Declare the inheritance 18 This defines a package, and include

your MainActivity class in the package. Can you roughly guess the directory of your MainActivity.java file based on the package name? Declare a class Declare the inheritance This imports an package, which define the Activity class. You can find the source file in your ADT

directory \sdk\sources\android22\android\app Specify the superclass 19 Java use the @Override annotation to indicate that the method is created by overriding. When we use this annotation for a method, it tells compiler that we are trying to override a superclass method, and enable the compiler to double check it for us if the method is indeed defined in the superclass. http://www.journaldev.com/817/overriding-methods-injava-always-use-override-annotation You can consider the onCreate

method to be the entry point which is called first by the system in an app. Adopt the activity_main.xml as the layout http://developer.android.com/reference/android/app/Activity.html 20 Java use the @Override annotation to indicate that the method is created by overriding. http://www.javapractices.com/topic/TopicAction.do?Id=223

You can consider the onCreate method to be the entry point which is called first by the system in an app. 21 Create three variables for your MainActivity class. They represents the widgets in your layout which are you going to use later You get the error, because the compiler does not know what EditText, TextView and Button mean.

You have to explicitly specify the definition of those classes 22 The needed libraries are automatically imported Create three variables for your MainActivity class. They represents the widgets in your layout which are you going to use later 23 Input this line of codes.

The purpose of this line is to glue the EditText widget you created in the layout with an object in the Java code. This is by using the method findViewById(int id_of_the_view) In this way, we are able to reference the widgets using Java codes 24 Type casting to ensure that the returned result of findViewById belong to the desired data type 25 Input another line of code, which associates the TextView

widget in the layout with a TextView object t in the codes 26 Can you add the codes for the button in the same manner as we do for TextView and EditText? This is because that we are also going to use the Button in the Java codes later. 27 The codes look like this 28

Your codes would look like 29 Add the codes like this 30 You may encounter some error on the codes. This is because that the compiler does not know

what OnClickListener interface is. 31 Call the setOnClickListener method of the button b The method enables the button to capture the users click operation on the button

32 Call the setOnClickListener method of the button b The method enables the button to capture the users click operation on the button The method MyButtonOnClickListener () is the constructor of the class. 33

Define the MyButtonOnClickListener class indicate that the class adopts the OnClickListener interface 34 Inside the onClick method, input the line of code. From the name of the method, you can roughly guess that this is to set the text of the TextView t, using the content of the EditText e This is by retrieving the text of e using the method getText(), and then

call the setText() method of t 35 By associating the button with the a click listener. The onClick method is called automatically when the listener detect the users click operation on the button 36 Run the app in AVD. Input some text in the EditText and click the button to see if this is working. To summarize: 1. We have created the widgets on the layout, and create an id for each widget

2. We have called the findViewById() method to glue the widget on layout with the Java codes 3. We have set up a class implement the OnClickListener, and apply it to the Button. This allows the button the capture the users click operation. 4. We have revised the onClick() method to retrieve the text of the EditText and give it to the TextView 37 Android Studio Hotkeys Reformat code: CTRL + ALT + L (Win) OPTION + CMD + L (Mac) Quick Fix: Alt + Enter

Jump to source: F4 https://developer.android.com/sdk/installing/studio-tips.html 38 View.OnClickListener Defined in android.view.View.OnClickListener Interface definition for a callback to be invoked when a view is clicked Create an OnClickListener protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send);

// Create an object of the custom onClickListener YourOnClickListener anOnClickListener = new YourOnClickListener(); // Attach the created onClickListener with the button button.setOnClickListener(anOnClickListener); } class YourOnClickListener implements OnClickListener{ @Override public void onClick(View v) { } } Refer to http://developer.android.com/guide/topics/ui/ui-events.html for detailed information 39

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send); // Create an object of the custom onClickListener YourOnClickListener anOnClickListener = new YourOnClickListener(); // Attach the created onClickListener with the button button.setOnClickListener(anOnClickListener); } class YourOnClickListener implements OnClickListener{ @Override public void onClick(View v) { }

} Using Anonymous Inner Class protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button_send); // Using the anonymous inner class button.setOnClickListener(new OnClickListener() { // Create the anonymous inner class @Override public void onClick(View v) { }

}); } 40 Using UI Widgets: Step 1 1. Create in XML layout 1. Create an id using android:id="@+id/newID" 2. Specify the necessary attributes android:layout_width="match_parent" android:layout_height="match_parent

User 58 // in Monique.java public class Monique extends Activity { // Variables (attributes) that the Monique class; // Methods (behaviours) of the Monique class; } Monique 59

// in Gorge.java // in Monique.java public class Monique extends Activity { public class Gorge extends Activity { // Variables (attributes) that the Monique class; // Methods (behaviours) of the Monique class; } // Variables (attributes) that the Gorge class;

// Methods (behaviours) of the Gorge class; } Intent Monique Gorge 60 public class Monique extends Activity { // variables and methods of Monique }

public class Gorge extends Activity { // variables and methods of Gorge } public class Selina extends Activity { // variables and methods of Selina } public class Adam extends Activity { // variables and methods of Adam } Intent Intent

Intent 61 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { } @Override protected void onStart() { } @Override protected void onResume() {

} @Override protected void onPause() { } @Override protected void onStop() { } @Override protected void onRestart() { } @Override protected void onDestroy() { } }

http://developer.android.com/reference/android/app/Activity.html 62 Lifecycle of an Activity An activity's lifecycle is a set of states and methods performed at each state o Get prepared to work, start working, transfer the work to others When the current state of an activity changes, the Android OS notifies the activity of that change The Android developer manages the activity's lifecycle by implementing the standard callback methods that

are called on the activity object when its state changes Callback implementation is the only leverage the developer has over activities 63 The three callbacks, onCreate(), onStart(), onResume(), are called in sequence, when creating a new instance of an activity. After sequence of callbacks complete, the activity reaches the Resumed state where the user can interact with the activity onStart(): Called when the activity is about to become visible onResume(): Called when the activity is visible and will start interacting with the user.

64 Pausing & Resuming an Activity When the foreground activity is obstructed by other visual components, e.g., a semi-transparent activity opens such as dialog, onPause() is called and the activity waits in the Pause state. If the user returns to the activity while its still paused, the system calls onResume() 65 Pausing: onPause() We usually use the onPause()

callback to: 1. Stop animations or other ongoing actions that could consume CPU. 2. Commit unsaved changes (such as a draft email) 3. Release system resources, such as handles to sensors (like GPS), or any resources that may affect battery life. @Override public void onPause() { // Always call the superclass method first

super.onPause(); // because we // might need if Release the Camera don't need it when paused and other activities to use it. (mCamera != null) { mCamera.release() mCamera = null;

} } Operations in onPause() must be kept simple in order to allow for a speedy transition to the users next destination 66 Stoping & Restarting an Activity When the activity is fully-obstructed and not visible, the system calls onStop() to stop the activity. If the user returns while the activity is stopped, the system calls onRestart(), quickly followed by onStart() and onResume().

67 There are a few of key scenarios in which activity is stopped and restarted: 1. User opens the Recent Apps window and switches from the app to another app. If the user returns to the app from the Home screen launcher icon or the Recent Apps window, the activity restarts.

2. When a new Activity is launched. The current activity is stopped when the second activity is created. 3. The user receives a phone call while using your app on his or her phone. We should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database 68 Summary: Activitys Lifetime 69

Demo 1 Download the codes on Cloud Deakin/Resource/Week 4 70 Demo 2 Video Tutorial: Topic #5 and #6 on the Life Cycle of Activity: https://www.youtube.com/playlist? list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E 71

Intent Intent Monique Gorge 72 What is Intent Intents are messages which allow Android components to request functionality from other components of the Android system. Intent are used for requesting information, computation, or

event signalling All intents objects are instances of android.content.Intent Intent 73 Start an Activity with Intent Explicit Intent Activity 1 Activity 2 Intent Intent anIntent = new Intent(this, Activity2.class);

startActivity(anIntent); Activity 1 Activity 2 Intent Intent AnotherIntent = new Intent(this, Activity1.class); startActivity(AnotherIntent); 74 Anonymous inner class

75 1. Activity A creates an Intent with an Action description and passes it to startActivity(). 2. The Android System searches all apps for an intent filter that matches the intent. 3. When a match is found, the system starts the matching activity (Activity B) by invoking its onCreate() method and passing it the Intent. 76 Demo Video Tutorial: Topic #13 How to Start New Activity On

Button Click via Intent : https://www.youtube.com/playlist? list=PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E Create a note named Explicit Intent and copy the codes on Evernote 77 Manifest.xml 78 What is Android Manifest File Every application must have an Android

Manifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system. o information the system must have before it can run any of the application's code. 79 Tags in Manifest xml File

http://developer.android.com/guide/topics/manifest/manifest-intro.html 80 AndroidManifest.xml Applications should declare everything needed on the the AndroidManifest.xml file One AndroidManifest.xml for application .. What's contained in it? o Permissions o Hardware and Software resources used by the Application o Activities

o Intent-filters 81

Recently Viewed Presentations

  • Craig McLean Chief Scientist (Acting), NOAA NOAA and

    Craig McLean Chief Scientist (Acting), NOAA NOAA and

    The marine areas in the U.S. Arctic comprise four discrete large marine ecosystems (LME). NOAA's unique capabilities and expertise enable it to provide critically important support to the Nation as it implements the U.S. National Strategy for the Arctic Region.
  • Credit and Debit Card Fraud

    Credit and Debit Card Fraud

    Credit/debit card fraud prevention. Could Dave have prevented the theft of his parents' credit card information? Maybe. Check the mail daily. Shred any documents or mail that contains personal identifiable information. Let's go back and take a look at Dave's...
  • Lecture 5 - Houston Community College

    Lecture 5 - Houston Community College

    GPE is the energy acquired by an object by virtue of its position in a gravitational field-- typically by being raised above the surface of the Earth. In SI, GPE = mgh in units of joules. In Engineering English units,...
  • Valuing College AND Career Readiness in State Accountability

    Valuing College AND Career Readiness in State Accountability

    Destination Known. Provides a roadmap for the measures and strategies states can use in an accountability system to support all students in reaching their destination: success after high school.. It's a matter of equity, as fewer youth from traditionally underserved...
  • NCAA Division III Bylaw 17 Playing Seasons

    NCAA Division III Bylaw 17 Playing Seasons

    NCAA Division III Bylaw 17 Playing Seasons. aka Mo Harty and Joni Williamson. Overview. ... The penalty assessed will be a mathematical calculation that will effect a team's win-loss percentage and strength of schedulewithin the championship selection criteria.
  • DOCUMENT ANALYSIS OPVLs I N O R D

    DOCUMENT ANALYSIS OPVLs I N O R D

    In order to analyze a source, you must first know what it is. Sometimes not all of these questions can be answered. The more you do know about where a document is coming from, the easier it is to ascertain...
  • Study within a Trial (SWAT) to increase the

    Study within a Trial (SWAT) to increase the

    Title to go here. Body copy to go here. What is a SWAT? 'A self contained research study that has been embedded within a host trial with the aim of evaluating or exploring alternative ways of delivering or organizing a...
  • Health Care 2012: Challenges and Opportunities

    Health Care 2012: Challenges and Opportunities

    The States can implement RomneyCare everywhere. 26 Attorney Generals file suit against the Federal Plan 35 States applied/received grants to implement Federal Plan