Our First Android Application

Similar documents
Create Parent Activity and pass its information to Child Activity using Intents.

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Android Application Development. By : Shibaji Debnath

Android Programs Day 5

05. RecyclerView and Styles

Android UI Development

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed.

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Introduction to Android Development

ANDROID PROGRAMS DAY 3

Intents. Your first app assignment

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Android Application Development

Q.1 Explain the dialog and also explain the Demonstrate working dialog in android.

Building MyFirstApp Android Application Step by Step. Sang Shin Learn with Passion!

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

By Ryan Hodson. Foreword by Daniel Jebaraj

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Vienos veiklos būsena. Theory

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

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

TPCT s College of Engineering, Osmanabad. Laboratory Manual SDL-II. Mobile Application Development (Android) For. Third Year Students (CSE)

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Topics of Discussion

COMP61242: Task /04/18

Fragments. Lecture 11

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 4. Workshop

Lab Android Development Environment

Accelerating Information Technology Innovation

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Getting Started With Android Feature Flags

Android HelloWorld - Example. Tushar B. Kute,

UNDERSTANDING ACTIVITIES

Basic GUI elements - exercises

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Android Programming Lecture 2 9/7/2011

Android Workshop: Model View Controller ( MVC):

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Tabel mysql. Kode di PHP. Config.php. Service.php

INTRODUCTION TO ANDROID

University of Stirling Computing Science Telecommunications Systems and Services CSCU9YH: Android Practical 1 Hello World

Introduction To JAVA Programming Language

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

M.A.D ASSIGNMENT # 2 REHAN ASGHAR BSSE 15126

Upon completion of the second part of the lab the students will have:

Data Persistence. Chapter 10

10.1 Introduction. Higher Level Processing. Word Recogniton Model. Text Output. Voice Signals. Spoken Words. Syntax, Semantics, Pragmatics

SD Module-1 Android Dvelopment

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Android Basics. Android UI Architecture. Android UI 1

android-espresso #androidespresso

Fragment Example Create the following files and test the application on emulator or device.

Lab 1 - Setting up the User s Profile UI

Starting Another Activity Preferences

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

Android Beginners Workshop

Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University.

Android Application Programming Tutorial

CS 4330/5390: Mobile Application Development Exam 1

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps.

StoppUhr. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start1"

Lecture 6: Android XML, Inversion of Control, Timers (Handlers), Activity

Creating a Custom ListView

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

BCA 6. Question Bank

CS 234/334 Lab 1: Android Jump Start

Mobile Application Development Android

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Manifest.xml. Activity.java

Learn about Android Content Providers and SQLite

Tutorial: Setup for Android Development

Mobile Computing Practice # 2c Android Applications - Interface

Android CardView Tutorial

android:layout_margintop="5dp" > <EditText android:layout_width="210dp"

User Interface Design & Development

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.

UI Fragment.

Workshop. 1. Create a simple Intent (Page 1 2) Launch a Camera for Photo Taking

Tip Calculator. xmlns:tools=" android:layout_width="match_parent"

Android Coding. Dr. J.P.E. Hodgson. August 23, Dr. J.P.E. Hodgson () Android Coding August 23, / 27

ANDROID USER INTERFACE

Open Lecture Mobile Programming. Intro to Material Design

Meniu. Create a project:

South Africa

Lecture 14. Android Application Development

Mobile Software Development for Android - I397

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Lecture 7: Data Persistence : shared preferences. Lecturer : Ali Kadhim Al-Bermani Mobile Fundamentals and Programming

Notification mechanism

(Refer Slide Time: 1:12)

Transcription:

Mobile Application Development Lecture 04 Imran Ihsan Our First Android Application Even though the HelloWorld program is trivial in introduces a wealth of new ideas the framework, activities, manifest, intents, UI, resources such as layouts, strings, etc. I know all just to print Hello World! There is a lot to take in regarding the Android program plumbing but an important separation principal presented in the single HelloWorld is the separation between UI design in XML and the program. Next, we consider a more complex with multiple UIs, activities and intents it's called MyFirstApp and the code is linked in so you can download and run it. What this lecture covers: The MainActivity UI and code Intents and starting another activity, namely, the DisplayMessageActivity The DisplayMessageActivity UI and code Application logging Checkout the demo project Download the demo the MyFirstApp.zip app to go with these notes. I recommend that you code this project up from the notes rather than just open the project in Android Studio and run it but feel free to do that if you really want. As a rule I will include all source code examples and projects used in course when I can. Open an existing Android project in Android Studio To open each of the demo projects we give out, you will need to do this: Click on the MyFirstApp.zip file and download and save the file on your desktop or download folder Unzip the MyFirstApp.zip and you have MyFirstApp directory/ project In Android Studio, click File >Open if you have already opened a project. Otherwise, click Open an existing Android Studio project at Welcome to Android Studio screen. Find the MyFirstApp directory and click Choose. The project should be opened and ready to run. Clean a project If for some reason there are errors try a clean. This is always a good thing to do if there are spurious errors in a project you know is clean. Go to Build >Clean Project. Hope that helped. MyFirstApp This application moves things forward. First it includes two activities. The main activity starts the second activity using an intent. When the user inputs a message on the UI of the first activity and clicks send the message is bundled up in an intent and the display activity started which displays the message on its own UI. Take a look at the screen dumps below: the first one is the UI rendered by the MainActivity UI, next the user enters a message and clicks the Send button and wham the DisplayMessageActivity is started to display the message in a larger sort of uncool font. There is a lot more to this simple program. Note, the menus for each UI is different. You can navigate back using the Up button instead of the back button from the DisplayMessageActivity UI. More on this later.

This program myfirstapp is taken from the Android developers with minor modifications. The MainActivity's UI Open the app/java folder and look at the MainActivity.java code. Create a linear layout The MainActivity's layout file is at app/res/layout/activity_main.xml <?xml version="1.0" encoding="utf 8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > </LinearLayout> Add a text field <EditText android:id="@+id/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/edit_message" /> Add String Resources By default, your Android project includes a string resource file at app/res/values/strings.xml. Add a new string named "edit_message" and set the value to "Enter a message." (You can delete the "hello_world" string.) While you re in this file, also add a "Send" string for the button you ll soon add, called "button_send". <?xml version="1.0" encoding="utf 8"?> <resources> <string name="app_name">my First App</string> <string name="edit_message">enter a message</string> <string name="button_send">send</string> <string name="menu_settings">settings</string> <string name="title_activity_main">mainactivity</string> </resources> Add a button <Button android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="@string/button_send" /> Format the Input box <EditText android:layout_weight="1" android:layout_width="0dp"... /> Final XML Open the activity_main.xml file from the res/layout/ directory. <?xml version="1.0" encoding="utf 8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout> Respond to the Send Button <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onclick="sendmessage" /> Building an Intent Open the MainActivity class (located in the project's src/ directory) and add the corresponding method: package edu.dartmouth.cs.myfirstapp; import android.content.intent; import android.view.menu; import android.view.view; import android.widget.edittext; public class MainActivity extends Activity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.message"; protected void oncreate(bundle savedinstancestate) { setcontentview(r.layout.activity_main); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; /** Called when the user clicks the Send button */ public void sendmessage(view view) { // Do something in response to button Intent intent = new Intent(this, DisplayMessageActivity.class); EditText edittext = (EditText) findviewbyid(r.id.edit_message);

String message = edittext.gettext().tostring(); intent.putextra(extra_message, message); Starting another activity To start an activity, call startactivity() and pass it your Intent. The system receives this call and starts an instance of the Activity specified by the Intent. With this new code, the complete sendmessage() method that's invoked by the Send button now looks like this:...... // Send the input string to the DisplayMessageActivity using an intent Intent intent = new Intent(this, DisplayMessageActivity.class); EditText edittext = (EditText) findviewbyid(r.id.edit_message); String message = edittext.gettext().tostring(); intent.putextra(extra_message, message); startactivity(intent); Now you need to create the DisplayMessageActivity class in order for this to work. Create another activity DisplayMessageActivity To create a new activity using Android Studio: Right click app, find New >Activity >Blank Activity and click to open the create activity dialog. Fill in the activity details:

Finally click Finish. The DisplayMessageActivity class should now look like this: package edu.dartmouth.cs.myfirstapp; import android.view.menu; protected void oncreate(bundle savedinstancestate) { setcontentview(r.layout.activity_display_message); // Show the Up button in the action bar. getactionbar().setdisplayhomeasupenabled(true); public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_display_message, menu); return true; public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case android.r.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up vs back // NavUtils.navigateUpFromSameTask(this); return true; return super.onoptionsitemselected(item); When you create an activity it provides a number of default methods which we will not use in this project. Remove: oncreateoptionsmenu(menu menu)

The DisplayMessageActivity class should now look like this: package edu.dartmouth.cs.myfirstapp; import android.view.menu; protected void oncreate(bundle savedinstancestate) { setcontentview(r.layout.activity_display_message); // Show the Up button in the action bar. getactionbar().setdisplayhomeasupenabled(true); public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case android.r.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up vs back // NavUtils.navigateUpFromSameTask(this); return true; return super.onoptionsitemselected(item); If you get an error with getactionbar().setdisplayhomeasupenabled(true) make sure that the minimum API to 11 in the manifest as shown below. Because the ActionBar APIs are available only on HONEYCOMB (API level 11) and higher, you must add a condition around the getactionbar() method to check the current platform version <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.dartmouth.cs.myfirstapp" android:versioncode="1" android:versionname="1.0" >... <uses sdk android:minsdkversion="11" android:targetsdkversion="17" /> By setting the minimum API to 11 the error is cleared. Add the title string <resources>... <string name="title_activity_display_message">my Message</string> </resources> This is included in the Manifest where the DisplayMessageActivity is specified. Add it to the manifest Take a look at the XML for the new activity.displaymessageactivity in the manifest. The code is self explanatory.

<application... >... <activity android:name="edu.dartmouth.cs.myfirstapp.displaymessageactivity" android:label="@string/title_activity_display_message" android:parentactivityname="edu.dartmouth.cs.myfirstapp.mainactivity" > <meta data android:name="android.support.parent_activity" android:value="edu.dartmouth.cs.myfirstapp.mainactivity" /> </activity> </application> Running the app You can run the app now, but not much happens. Clicking the Send button starts the second activity but it uses a default "Hello world" layout provided by the template. You'll soon update the activity to instead display a custom text view. Receive the Intent In the DisplayMessageActivity class s oncreate() method, get the intent and extract the message delivered by MainActivity: import android.content.intent; protected void oncreate(bundle savedinstancestate) { setcontentview(r.layout.activity_display_message);... // Show the Up button in the action bar. getactionbar().setdisplayhomeasupenabled(true); // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); Display the Message

To show the message on the screen, create a TextView widget and set the text using settext(). Then add the TextView as the root view of the activity s layout by passing it to setcontentview(). The complete oncreate() method for DisplayMessageActivity now looks like this: import android.content.intent; import android.widget.textview; public void oncreate(bundle savedinstancestate) {... // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); // Create the text view TextView textview = new TextView(this); textview.settextsize(40); textview.settext(message); // Set the text view as the activity layout setcontentview(textview); You are done, now run your Android firstapp! You should see the following screens on your phone or emulator Application Logging using Log.d() You can put print or log statements your code. You might want to confirm for example that an intent fired by one activity is received by another. You can use Log.d() to do this. You have to first create a TAG in your code and then call Log.d() with the tag. In the code snippet below that you need to import android.util.log, set up the TAG, and then call Log.d() package edu.dartmouth.cs.myfirstapp;

import android.content.intent; import android.util.log; import android.widget.textview; private static final String TAG = "MyFirstApp"; public void oncreate(bundle savedinstancestate) { // Get the message from the intent Intent intent = getintent(); String message = intent.getstringextra(mainactivity.extra_message); Log.d(TAG, "Got Intent"); // Create the text view TextView textview = new TextView(this); textview.settextsize(40); textview.settext(message); // Set the text view as the activity layout setcontentview(textview);... Using LogCat to view application output An easy way to monitor the output from log.d is to use the LogCat utility. LogCat is integrated into Android Studio. You ll find the LogCat by clicking the Android tab at the bottom of Android Studio. The following screenshot shows the code to print logs in LogCat and viewing logs from the LogCat window. Once you click on run and enter input you will see to logs printed out from the application: one when the user clicks send at the UI; and one when DisplayMessageActivity receives the Intent and prints the message, as shown above. This is a simple example of logging applications. Much more sophisticated logging can be done. More later on this.