Mobile Programming Lecture 14 Communicating via the Internet.

Slides:



Advertisements
Similar presentations
The Web Warrior Guide to Web Design Technologies
Advertisements

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.
Lecture 13 Mobile Programming Google Maps Android API.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
World Wide Web1 Applications World Wide Web. 2 Introduction What is hypertext model? Use of hypertext in World Wide Web (WWW) – HTML. WWW client-server.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
1 The World Wide Web. 2  Web Fundamentals  Pages are defined by the Hypertext Markup Language (HTML) and contain text, graphics, audio, video and software.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Web server and web browser It’s a take and give policy in between client and server through HTTP(Hyper Text Transport Protocol) Server takes a request.
HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here.
Pemrograman Berbasis WEB XML part 2 -Aurelio Rahmadian- Sumber: w3cschools.com.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
Internet Skills An Introduction to HTML Alan Noble Room 504 Tel: (44562 internal)
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
JavaScript & jQuery the missing manual Chapter 11
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
XML introduction to Ahmed I. Deeb Dr. Anwar Mousa  presenter  instructor University Of Palestine-2009.
CS378 - Mobile Computing Web - WebView and Web Services.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Pemrograman Berbasis WEB XML -Aurelio Rahmadian- Sumber: w3cschools.com.
JavaScript, Fourth Edition
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
HTML5 Communication. The Setup Somewhere on the web, a server makes a ”service” available, that we wish to use in a web application The service may offer.
CS378 - Mobile Computing Web - WebView and Web Services.
Chapter 8 Cookies And Security JavaScript, Third Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.
Website Development with PHP and MySQL Saving Data.
Consuming eXtensible Markup Language (XML) feeds.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Networking: Part 1 (Web Content). Networking with Android Android provides A full-featured web browser based on Chromium, the open source browser engine.
WEB APPLICATION DEVELOPMENT For More visit:
Consuming eXtensible Markup Language (XML) feeds.
Introduction to XML This presentation covers introductory features of XML. What XML is and what it is not? What does it do? Put different related technologies.
Intro to PHP IST2101. Review: HTML & Tags 2IST210.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Web Development 101 Presented by John Valance
Server - Client Communication Getting data from server.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
Submitted To: Ms. Poonam Saini, Asst. Prof., NITTTR Submitted By: Rohit Handa ME (Modular) CSE 2011 Batch.
Dr. Chunbo Chu Week 3. XML Not a replacement for HTML. XML and HTML were designed with different goals: XML was designed to transport and store data,
 defined as Extensible Markup Language (XML) is a set of rules for encoding documents  Defines structure and data.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
RESTful Web Services A MIDAS MISSION PRESENTATION APRIL 29, 2015.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
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.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
Dave Salinas. What is XML? XML stands for eXtensible Markup Language Markup language, like HTML HTML was designed to display data, whereas XML was designed.
JQUERY AND AJAX
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
XML Introduction to XML Extensible Markup Language.
CSE 154 LECTURE 18: FORMS AND UPLOADING FILES. Exercise: Baby name web service JSON Modify our babynames.php service to produce its output as JSON. For.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
Day 22, Slide 1 CSE 103 Day 22 Non-students: Please logout by 10:12. Students:
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
IS333D: MULTI-TIER APPLICATION DEVELOPMENT
// Please Setting App_name to Send Successful
Presentation transcript:

Mobile Programming Lecture 14 Communicating via the Internet

Agenda A look at HTML HttpUrlConnection HttpGet A more in-depth look at XML Introducing JSON Introducing Web APIs ProgrammableWeb.com

A look at HTML Go to and search for your favorite movie Right click on the page and view the source Not surprisingly, you will find that the source behind the page is not easy to read

A look at HTML You can load HTML into a WebView Try this WebView wv = (WebView) findViewById(R.id.webView); wv.loadData(" Hi Mom! Dad," + " sup? ", "text/html", "UTF-8");

A look at HTML HTTP defines 9 methods/verbs indicating the desired action to be performed on a URL For now, we will only look at 2 of the verbs o GET o POST

A look at HTML HTTP GET o Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effectretrieve data HTTP POST o Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request.HTML form

A look at HTML Get is like a query. You can usually modify the arguments to the query directly Not the same with POST!

A look at HTML What if you want to read this data (the HTML source) in Android?

HttpUrlConnection used to send and receive data over the web data may be of any type and length

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); }

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } We will use this WebView to display a page

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } We need to run network routines on a separate thread, otherwise we will get Exceptions

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } To run a block of code on a separate thread (i.e., not on the UI aka main thread)

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Create an instance of Thread

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Pass an anonymous inner Runnable class as the argument to the Thread constructor

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Override the run() method of Runnable

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Add your code block to the run() method

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Call start() on the Thread

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } URL object identifies the location of an Internet resource

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } HttpURLConnection used to (send and) receive data over the Internet

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Get an instance of it by calling openConnection() on the URL

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Get an InputStream for reading in the data

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } A one-liner that I stole from here for reading in all of the data using the InputStream here

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); } Release the resources held by the connection

data should now contain the HTML returned by the URL. We load the data into the WebView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.webView); new Thread(new Runnable() public void run() { URL url = new URL(" HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); data = new java.util.Scanner(in).useDelimiter("\\A").next(); urlConnection.disconnect(); wv.loadData(data, "text/html", "UTF-8"); } }).start(); }

A look at HTML HTML tells the browser how the server wants to display information to the user How would the server send this information to your device, efficiently?

HttpUrlConnection See HttpUrlConnectionExample.tar

HttpUrlConnection What happens if we try to open a connection to an invalid URL? URL url = new URL(" with an extra "s" after mobile, instead of URL url = new URL("

HttpUrlConnection We need to check the HTTP response code for errors first, then act accordingly

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); }

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } This takes care of a bunch of mumbo jumbo that you don't want to deal with

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } Use HttpGet to retrieve whatever information is identified by the request-URI

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } set the URI!

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } Check this link out to learn more about status codes.this link 200 means OK!

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } If the status is OK, then write the rest of the code that will handle a successful GET

HttpGet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) sb.append(line + NL); in.close(); browser.loadData(sb.toString(), "text/html", "UTF-8"); } Then you may also wish to handle cases when the status is NOT OK.

HttpGet See HttpGetExample.tar

In-depth Look at XML XML doesn't replace HTML XML doesn't do anything o something is done with the XML You can invent your own tags with XML

In-depth Look at XML Simplifies data sharing Simplifies data transport You can invent your own tags with XML

In-depth Look at XML Tove Jani Reminder Don't forget me this weekend!

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm "bookstore" is the root element

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm bookstore has 3 children

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm each one is a "sibling" to the other (title, author, year, price)

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm An element may have children (book element has 4 children in this case)

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm and or attributes

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm and/or data

In-depth Look at XML Everyday Italian Giada De Laurentiis Harry Potter J K. Rowling Snow White Brothers Grimm attribute values must always be within double quotes

In-depth Look at XML You can use an XML parser in Java to parse an XML file, in order to get the desired information

In-depth Look at XML How do we get the movie information from IMDB? We can only hope that someone has made the data available to us via XML

In-depth Look at XML Go to and search for your favorite movie again Woops, the data is not represented as XML o append the string "&r=xml" to the end of the URL o or click here to be inceptedhere Take a look at the XML data o Can you interpret it? o Can a machine interpret it?

Parsing XML In Android, you may want to read this XML data, parse it, then display some parts of the data on an Android device

Parsing XML First, use HttpGet to execute a request to the same URL which returns data in XML format Then, if the status is OK, fetch the data and store it into a String (String raw for this example) Then...

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } });

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); There are several XML parsers available to you. Here we use the W3C DOM parser

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); This Document represents the entire XML document

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); Take a look at the XML file in the browser again. Here we get all of the elements having the tag "movie", in this case there's just one

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); From the list of movies (although there's only one), here we get the first movie element

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); As you can see, it would be easy to iterate through multiple movie elements using an index

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); The movie element has a plot attribute, that's what we want to retrieve in this example

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); Now we want to update the TextView, but we're not currently inside of the UI thread

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); So we need to do fancy stuff.

Parsing XML DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(raw))); NodeList movies = doc.getElementsByTagName("movie"); final Element movie = (Element) movies.item(0); final String moviePlot = "" + movie.getAttribute("plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); The post() method of the View class takes a runnable, and runs it on the UI thread

Parsing XML See HttpGetXmlExample.tar

XML Efficiency How can we represent this data more efficiently? Tove Jani Reminder Don't forget me this weekend!

XML Efficiency How can we represent this data more efficiently? Tove Jani Reminder Don't forget me this weekend! 133 characters { "to":"Tove", "from": "Jani", "heading":"Reminder", "body":"Don't forget me this weekend!" } 88 characters

XML Efficiency How can we represent this data more efficiently? Tove Jani Reminder Don't forget me this weekend! 133 characters This syntax called JSON { "to":"Tove", "from": "Jani", "heading":"Reminder", "body":"Don't forget me this weekend!" } 88 characters

JSON Values "title" : "IT Business Analyst Intern" "organization" : "Medtronic" "city" : "Brooklyn Park"

JSON Arrays "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"]

JSON Objects { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/10", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] }

Parsing JSON JSONObject json = new JSONObject(raw); final String moviePlot = "" + json.getString("Plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } });

Parsing JSON JSONObject json = new JSONObject(raw); final String moviePlot = "" + json.getString("Plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); JSONObject is a set of name/value mappings, can represent a JSON document

Parsing JSON JSONObject json = new JSONObject(raw); final String moviePlot = "" + json.getString("Plot"); mTextMoviePlot.post(new Runnable() public void run() { mTextMoviePlot.setText(moviePlot); } }); Retrieve the plot of the movie

Parsing JSON Parsing JSON is not always this simple however, but it's usually straightforward once you understand JSON A JSONObject may consist of more JSONObjects, JSONArrays, Strings, Booleans, Integers, etc

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] }

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } This is a JSONObject

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } You can get title by calling getString("title") on the JSONObject

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } You can get organization by calling getString("organization") on the JSONObject

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } Etcetera, etcetera...

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } This however, is not a String, but an array. Get this by calling getJSONArray() on the JSONObject

Parsing JSON { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] } After which you can use the getters on the JSONArray to get the desired data

Parsing JSON How would you represent this data using XML? { "title" : "IT Business Analyst Intern", "organization" : "Medtronic", "city" : "Brooklyn Park", "state" : "MN", "start_date" : "05/10", "end_date" : "07/11", "details" : [ "bla bla bla", "drank some soda", "hit manager in face with pie"] }

Parsing JSON See HttpGetJsonExample.tar

Introducing Web APIs In our IMDB example, we saw data that we wanted to use on another machine Luckily, someone created imdbapi.com, allowing us to read this data from a machine Data isn't always available however, the developer of the web site has to make the data available to other developers o Take VISA for example, they wouldn't just make your private data available! o Or ESPN, who only recently opened up an API for developers to use

Introducing Web APIs What is a Web API? According to Wikipedia... A Web API is a defined set of HTTP request messages along with a definition of the structure of response messages, typically expressed in JSON or XMLHTTPJSON

Introducing Web APIs You use a Web API because there's data somewhere that you want to use, and the best way for you to retrieve the data is via JSON or XML You don't want to see the data graphically, you just want to use it

Introducing Web APIs Some more examples of GET requests

Introducing Web APIs - Twitter Let's look at the Twitter public API, a more complicated example Look at this Twitter profile Let's get the profile image from here

Introducing Web APIs - Twitter See JsonTwitterExample.tar

Introducing Web APIs Communication in this way involves a client (your device) and a server (twitter.com)

Introducing Web APIs Note: Sometimes you need an API key in order to use an API

References The Busy Coder's Guide to Android Development - Mark Murphy The Busy Coder's Guide to Android Development - Mark Murphy Android Developers The Mobile Lab at Florida State University