David Sutton MOBILE INTERNET. OUTLINE  This week’s app – an RSS feed reader  Mobile internet considerations  Threads (recap)  RSS feeds  Using AsyncTask.

Slides:



Advertisements
Similar presentations
HTML 5 and CSS 3, Illustrated Complete Unit L: Programming Web Pages with JavaScript.
Advertisements

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
USING ANDROID WITH THE INTERNET. Slide 2 Network Prerequisites The following must be included so as to allow the device to connect to the network The.
Inheritance Inheritance Reserved word protected Reserved word super
Road Map Introduction to object oriented programming. Classes
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
VBA Modules, Functions, Variables, and Constants
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Unit 9: Arrays Declaring and Processing Arrays.
Multiple Choice Solutions True/False a c b e d   T F.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
1 Web Based Programming Section 6 James King 12 August 2003.
JavaScript & jQuery the missing manual Chapter 11
Systems Analysis and Design in a Changing World, Fifth Edition
CS378 - Mobile Computing Web - WebView and Web Services.
Chapter 5: Investigate! Lists, Arrays, and Web Browsers.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 5: Investigate! Android Lists, Arrays,
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
SAX Parsing Presented by Clifford Lemoine CSC 436 Compiler Design.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Processing of structured documents Spring 2002, Part 2 Helena Ahonen-Myka.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Using Client-Side Scripts to Enhance Web Applications 1.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS378 - Mobile Computing Responsiveness. An App Idea From Nifty Assignments Draw a picture use randomness Pick an equation at random Operators in the.
Android networking 1. Network programming with Android If your Android is connected to a WIFI, you can connect to servers using the usual Java API, like.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
David Sutton SMS TELEPHONY IN ANDROID. OUTLINE  This week’s exercise, an SMS Pub Quiz  Simulating telephony on an emulator  Broadcast Intents and broadcast.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Chapter 5: Investigate! Lists, Arrays, and Web Browsers.
Chapter 3: Using Methods, Classes, and Objects
“Real Simple Syndication” (RSS)
Mobile Computing With Android ACST 4550 Android Database Storage
Android Topics Asynchronous Callsbacks
Java Programming Language
Presentation transcript:

David Sutton MOBILE INTERNET

OUTLINE  This week’s app – an RSS feed reader  Mobile internet considerations  Threads (recap)  RSS feeds  Using AsyncTask for network operations  The … notation for parameters  Displaying web pages

THIS WEEK’S APPLICATION “BEHIND THE HEADLINES” READER  We will create a simple application that connects to the NHS “Behind the Headlines” RSS Feed.  The app will display a list of news items that have been covered by the Behind the Headlines service with links to the NHS web pages on which those news items are analysed.

MOBILE INTERNET CONSIDERATIONS  When writing mobile apps that access the internet we need to pay attention to several issues that might be of less importance when writing a desktop application. Specifically:  Limited bandwidth and reliability of connection  Need to maintain responsiveness (our app will get killed by the OS if we don’t!)  Battery life

ANDROID NETWORKING REQUIREMENTS  An app that accesses the internet must have the android.permission.INTERNET uses permission.  If you are targetting SDKs lower than Honeycomb then you should not perform networking operations on the main thread because the app will become unresponsive while the operation is performed.  If you are targetting Honeycomb or higher then you cannot perform networking operations on the main thread because a NetworkOnMainThreadException will be thrown.

PICKING UP THE THREADS OF THREADS  Recap of material covered in prerequisite module.  If you are performing some complex task, it is often useful to divide it into separate sequences of operations.  An example from real life: Suppose you want to prepare cauliflower cheese. You could divide the preparation into the following sequences of operations. Chop cauliflower Boil for 5 minutes Drain Grate cheese Make white sauce Add cheese to sauce Put cauliflower into ovenproof dish Add sauce Bake until brown on top The preparation of veg and sauce can be done in parallel We can’t boil the cauliflower until after we have chopped it, but it doesn’t matter whether we do it before or after grating the cheese

THREADS  A modern desktop OS will allow many processes to run in parallel. For example you can browse the internet while you wait for your client to download messages.  Many languages, including Java, allow a singleprocess to contain multiple threads which also execute in parallel and act as lightweight processes.

THREADS IN ANDROID  When an Android application is launched a single thread, called the “main thread” is created and, by default, all of the application’s code will run in this thread.  However you can create additional threads. In fact if you wish to perform network operations you have to create additional threads.  You can create a thread by instantiating the Java Thread class. However the Android API includes a class AsyncTask that simplifies the creation of threads (we will look at it in more detail later in the lecture).

SOME ANDROID INTERNET CLASSES  The standard classes from the java.net package are available, for example java.net.URL can be used to represent URLs  The standard Java SAX and DOM parsers for XML are also available. However the Android SDK also includes an XMLPullParser class which may run more efficiently on a mobile platform.  The SDK also includes a WebView class. This is a subclass of View that can be used to view HTML retrieved from the net, or supplied as a String.  You can also view web pages by using an implicit Intent to start the native web browser.

BEHIND THE HEADLINES The NHS “Behind the Headlines” service provides evidence- based analysis of health stories that appear in the media. It is available as an RSS feed.

RSS FEEDS  RSS Stands for “Really Simple Syndication”, or “Rich Site Summary” depending on who you wish to believe.  It is a simple means of publishing frequently updated information.  There is a standard XML format for RSS Feeds.

RSS FORMAT Index of Lost Things Those we have lost Lost Sock Red knee length sock Lost Cat …. Channel element describes the feed and usually contains several items. Each item must have a title, link, and description. There are other, optional, child elements.

UI FOR APPLICATION Do exercise 1 TextView to display status ListView to display items retrieved from feed.

A CLASS TO REPRESENT ITEMS public class Item { private String title; private String link; public Item(String title, String link) { this.title = title; this.link = link; } public String getTitle(){ return title; } public String getLink() { return link; } public String toString() { return title; } Do exercise 2

ADAPTER FOR ITEMS public class BTHActivity extends Activity { private TextView statusTxt; private ListView itemsLst; private ArrayList items = new ArrayList (); private ArrayAdapter protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bth); statusTxt = (TextView) findViewById(R.id.status_txt); itemsLst = (ListView) findViewById(R.id.items_lst); itemsAdapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, items); itemsLst.setAdapter(itemsAdapter); Do exercise 3

READING IN THE BACKGROUND  We must not read data from the internet in the main thread.  However we must not update UI components outside of the main thread.  We need to read data from the internet, and then update our UI components, so we have to run operations in different threads, and synchronize them so that we are not trying to update the UI before we have read all the necessary data.  Fortunately the Android SDK’s AsyncTask class allows us to do exactly that. It is designed to be subclassed, and contains some methods that will run in the main thread, and others that will run in a separate thread, with appropriate synchronisation.

ASYNCTASK AsyncTask +execute(Params… params) #doInBackground() #onPostExecute(Result result) #onPreExecute() #onProgressUpdate(Progress… p) #publishProgress(Progress… p) Public method that we call in order to perform the task Protected method that is performed in a separate thread. Designed to be overridden Protected method that is performed in the main thread, after doInBackground has completed. Designed to be overridden Other methods documented at

INNER CLASSES  We could create a completely separate class that will extend AsyncTask. However it will be more convenient to create an inner class.  An inner class is defined within another class. The differences between inner classes and standard classes are that:  Each object of the inner class is associated with an object of the enclosing class and has access to all of the fields and methods of the enclosing object (even the private ones).  An inner class can be private. public class A { …. private class B { … }

UML NOTATION FOR INNER CLASSES public class Out { …. private class In { … } Out In

TYPE PARAMETERS FOR ASYNCTASK  The declaration of the AsyncTask in the Android developer reference looks like this AsyncTask The identifiers inside the are formal type parameters. When we subclass AsyncTask we supply corresponding actual type parameters, much as we do when we instantiate an ArrayList. For example private class ReaderTask extends AsyncTask > The declarations of AsyncTask methods make use of the formal parameters. For example Result doInBackground(Params... params) The methods in the subclass will have the types specified by the corresponding actual parameters. For example protected ArrayList doInBackground(URL... params) We will explain what this … means later

TYPE PARAMETERS FOR ASYNCTASK  When we subclass AsyncTask we supply three type parameters, as illustrated by the following example private class ReaderTask extends AsyncTask > The parameter supplied to the execute method is an array of whatever type we specify here. In this case it will be an array of URL objects. The doInBackground method returns a result of whatever type we specify here, which is passed as a parameter to the onPostExecute method. The type supplied here is passed as an argument to the publishProgress method. If we don’t want to use it we can make it Void (note capital ‘V’).

OUR ASYNCTASK private class ReaderTask extends AsyncTask >{ private String protected ArrayList doInBackground(URL... params) { … protected void onPostExecute(ArrayList result) { … } We will use this field to store a message to be displayed in the UI text field. Code to read the feed and return a list of Items representing its content. Code that uses the values of the fields to update the UI (runs in main thread),

THE … NOTATION The signature of the doInBackground method of the AryncTask class is protected ArrayList doInBackground(URL... params) the … means that the method can be called with a variable number of parameters, so long as they are all of type URL. For example if we were calling it directly then call could be like this doInBackground(url1) or like this doInBackground(url1, url2, url3) We do not call the method directly, but we do call it indirectly when we call the execute method. This also can take a variable number of parameters of type URL (we will in fact pass only one parameter).

THE … NOTATION Within the body of the doInBackground method, we treat the params parameter as an array. If we pass only one actual parameter then this is at element 0 of the array. Hence the code that establishes the input stream for the parser will look something like this. We will explain what the XMLPullParserFactory class does later XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); parser = factory.newPullParser(); parser.setInput(params[0].openStream(), null); protected ArrayList doInBackground(URL... params)

EXECUTING THE TASK ReaderTask readerTask = new ReaderTask(); try { URL url = new URL( " readerTask.execute(url); } catch (MalformedURLException ex){ //this should not happen statusTxt.setText("Bad URL"); } Do exercise 4

PARSING XML  The standard Java API provides classes that implement two kinds of parser for XML:  DOM parsers convert an entire XML document into a tree structure.  SAX parsers allow the programmer to write code that responds to events that occur as an XML document is read (an example of an event would be parser encountering a start tag).  The Android SDK also provides a simple, event based, parser class XMLPullParser.  An XMLPullParser reads an XML document and interprets what it reads, as a set of events. The first event is the “start document” event. Subsequent events may be “start tag” events (i.e. the parser has just encountered the start tag for an element), “end tag” events, “text” events, and so on.

SOME XMLPULLPARSER METHODS voidsetInput(Reader in)Sets the input stream for the parser int getEventType ()Returns an integer describing the type of the current event. Possible return values are identified by constants, START_TAG, START_DOCUMENT, END_TAG, etc. int next()Move on to the next event. String getName ()Get the name of the current tag (if the current event type is START_TAG or END_TAG). String getText ()Get the text content of the current event. Full details at

OBTAINING AN XMLPULLPARSER  The XMLPullParser class is abstract, so we cannot instantiate it directly using the keyword ‘new’.  Instead we make use of the XMLPullParser factory class. The constructor for this class is protected, so we can’t use ‘new’ to instantiate it either. We have to use its static newInstance method.  Here is how we create a parser: XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XMLPullParser parser = factory.newPullParser();

A USEFUL METHOD /** * Determine whether a parser is currently parsing the start of a given element parser The XMLPullParser being use name Name of the tag true if the parser is currently at the named tag, false otherwise XmlPullParserException */ private boolean isStartTag(XmlPullParser parser, String name) throws XmlPullParserException { return (parser.getEventType() == XmlPullParser.START_TAG) && parser.getName().equalsIgnoreCase(name); } We can define a similar methods isEndTag, isEndDocument, etc..

ANOTHER USEFUL METHOD /* * Get the textual contact of a named element The element has textual content parser The XMLPullParser being used name Name of the element Textual content of the element XmlPullParserException IOException */ private String getTagText(XmlPullParser parser, String name) throws XmlPullParserException, IOException { String result = null; while (!isEndTag(parser, name) && !isEndDoc(parser)) { if (parser.getEventType() == XmlPullParser.TEXT) { result = parser.getText(); } parser.next(); } return result; }

GETTING ITEM DATA FROM FEED In order to read the data we need to create an Item from the RSS feed. We need to look for “item” tags, then read the “title” and “link” child elements, ignoring other child elements Does housework count towards exercise targets? …

GETTING ITEM DATA FROM FEED private Item getItem(XmlPullParser parser) throws XmlPullParserException, IOException { String title = "???"; String link = null; while (!isEndTag(parser, "item") && !isEndDoc(parser)) { if (isStartTag(parser, "title")) { title = getTagText(parser, "title"); } else if (isStartTag(parser, "link")) { link = getTagText(parser, "link"); } parser.next(); } if (isEndTag(parser, "item")) { return new Item(title, link); } else { return null; }

UPDATING THE protected void onPostExecute(ArrayList result) { statusTxt.setText(statusMessage); items.clear(); items.addAll(result); itemsAdapter.notifyDataSetChanged(); } This is the result returned by the doInBackground method

WHAT YOU SHOULD SEE Do exercise 5

DISPLAYING WEB PAGES  Each Item in the list we have populated contains a link to a web page. We could display that web page in two different ways:  Launch the native browser by starting an activity whose action string is Intent.ACTION_VIEW and whose data attribute is the web link.  Write a new Activity whose UI includes a WebView  The first of those two methods is easier, so we’ll go with that one.

DISPLAYING WEB PAGES protected void onCreate(Bundle savedInstanceState) { … itemsLst.setOnItemClickListener(new OnItemClickListener() public void onItemClick(AdapterView parent, View view, int position, long id) { launchBrowser(position); } }); … private void launchBrowser(int position) { Item item = items.get(position); String link = item.getLink(); Uri uri = Uri.parse(link); Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uri); startActivity(launchBrowser); } Do exercise 6

SUMMARY  Network operations must not be performed in the main thread.  The AsyncTask class makes it easy to perform operations in a separate thread.  The XMLPullParser class provides a simple, event based, XML parser  We can display web pages by using an implicit intent to launch the native browser, or by using the WebView class.