mobile programming lecture 14

92
Mobile Programming Lecture 14 Communicating via the Internet

Upload: reece

Post on 25-Feb-2016

35 views

Category:

Documents


0 download

DESCRIPTION

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 http://www.imdb.com and search for your favorite movie - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Mobile Programming Lecture 14

Mobile ProgrammingLecture 14

Communicating via the Internet

Page 2: Mobile Programming Lecture 14

Agenda

• A look at HTML

• HttpUrlConnection

• HttpGet

• A more in-depth look at XML

• Introducing JSON

• Introducing Web APIs

• ProgrammableWeb.com

Page 3: Mobile Programming Lecture 14

A look at HTML

• Go to http://www.imdb.com 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

Page 4: Mobile Programming Lecture 14

A look at HTML

You can load HTML into a WebView

Try this

WebView wv = (WebView) findViewById(R.id.webView);wv.loadData("<html><body><h1>Hi Mom!</h1><br/><h2>Dad," +

" sup?</h2></body></html>", "text/html", "UTF-8");

Page 5: Mobile Programming Lecture 14

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 verbso GETo POST

Page 6: Mobile Programming Lecture 14

A look at HTML

• HTTP GETo Requests a representation of the specified resource.

Requests using GET should only retrieve data and should have no other effect

• HTTP POSTo 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.

Page 7: Mobile Programming Lecture 14

A look at HTML

Get is like a query. You can usually modify the arguments to the query directly

Not the same with POST!

Page 8: Mobile Programming Lecture 14

A look at HTML

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

Page 9: Mobile Programming Lecture 14

HttpUrlConnection

• used to send and receive data over the web

• data may be of any type and length

Page 10: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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();

}

Page 11: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 12: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 13: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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)

Page 14: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 15: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 16: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 17: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");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

Page 18: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 19: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");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

Page 20: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 21: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 22: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 23: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 24: Mobile Programming Lecture 14

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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

Page 25: Mobile Programming Lecture 14

data should now contain the HTML returned by the URL. We load the data into the WebView

HttpUrlConnection@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

wv = (WebView) findViewById(R.id.webView);

new Thread(new Runnable() {

@Override public void run() {

URL url = new URL("http://mobile.cs.fsu.edu/");

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();

}

Page 26: Mobile Programming Lecture 14

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?

Page 27: Mobile Programming Lecture 14

HttpUrlConnection

See HttpUrlConnectionExample.tar

Page 28: Mobile Programming Lecture 14

HttpUrlConnection

What happens if we try to open a connection to an invalid URL?

URL url = new URL("http://mobiles.cs.fsu.edu/");

with an extra "s" after mobile, instead of

URL url = new URL("http://mobile.cs.fsu.edu/");

Page 29: Mobile Programming Lecture 14

HttpUrlConnection

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

Page 30: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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");

}

Page 31: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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

Page 32: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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

Page 33: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));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!

Page 34: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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.200 means OK!

Page 35: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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

Page 36: Mobile Programming Lecture 14

HttpGetHttpClient client = new DefaultHttpClient();

HttpGet request = new HttpGet();

request.setURI(new URI("http://mobile.cs.fsu.edu/androids"));

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.

Page 37: Mobile Programming Lecture 14

HttpGet

See HttpGetExample.tar

Page 38: Mobile Programming Lecture 14

In-depth Look at XML

• XML doesn't replace HTML

• XML doesn't do anythingo something is done with the XML

• You can invent your own tags with XML

Page 39: Mobile Programming Lecture 14

In-depth Look at XML

• Simplifies data sharing

• Simplifies data transport

• You can invent your own tags with XML

Page 40: Mobile Programming Lecture 14

In-depth Look at XML<?xml version="1.0"?><note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body></note>

Page 41: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING">

<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

Page 42: Mobile Programming Lecture 14

In-depth Look at XML<bookstore> <book category="COOKING">

<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

"bookstore" is the root element

Page 43: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING"><title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN"><title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN"><title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

bookstore has 3 children

Page 44: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING">

<title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

each one is a "sibling" to the other (title, author, year, price)

Page 45: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING"><title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price>

</book> <book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

An element may have children (book element has 4 children in this case)

Page 46: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING">

<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

and or attributes

Page 47: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING">

<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

and/or data

Page 48: Mobile Programming Lecture 14

In-depth Look at XML<bookstore>

<book category="COOKING">

<title lang="en">Everyday Italian</title>

<author>Giada De Laurentiis</author>

<year>2005</year>

<price>30.00</price>

</book>

<book category="CHILDREN">

<title lang="en">Harry Potter</title>

<author>J K. Rowling</author>

<year>2005</year>

<price>29.99</price>

</book>

<book category="CHILDREN">

<title lang="en">Snow White</title>

<author>Brothers Grimm</author>

<year>1812</year>

<price>39.95</price>

</book>

</bookstore>

attribute values must always be within double quotes

Page 49: Mobile Programming Lecture 14

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

Page 50: Mobile Programming Lecture 14

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

Page 51: Mobile Programming Lecture 14

In-depth Look at XML

• Go to http://www.imdbapi.com and search for your favorite movie again

• Woops, the data is not represented as XMLo append the string "&r=xml" to the end of the URLo or click here to be incepted

• Take a look at the XML datao Can you interpret it?o Can a machine interpret it?

Page 52: Mobile Programming Lecture 14

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

Page 53: Mobile Programming Lecture 14

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 ...

Page 54: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

Page 55: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

There are several XML parsers available to you. Here we use the W3C DOM parser

Page 56: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

This Document represents the entire XML document

Page 57: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic 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

Page 58: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

From the list of movies (although there's only one), here we get the first movie element

Page 59: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

As you can see, it would be easy to iterate through multiple movie elements using an index

Page 60: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

The movie element has a plot attribute, that's what we want to retrieve in this example

Page 61: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

Now we want to update the TextView, but we're not currently inside of the UI thread

Page 62: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

So we need to do fancy stuff.

Page 63: Mobile Programming Lecture 14

Parsing XMLDocumentBuilder 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() {

@Overridepublic void run() {

mTextMoviePlot.setText(moviePlot);}

});

The post() method of the View class takes a runnable, and runs it on the UI thread

Page 64: Mobile Programming Lecture 14

Parsing XML

See HttpGetXmlExample.tar

Page 65: Mobile Programming Lecture 14

XML EfficiencyHow can we represent this data more efficiently?

<?xml version="1.0"?><note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body></note>

Page 66: Mobile Programming Lecture 14

XML EfficiencyHow can we represent this data more

efficiently?

<?xml version="1.0"?><note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this

weekend!</body></note>

133 characters

{"to":"Tove","from": "Jani","heading":"Reminder",

"body":"Don't forget me this weekend!"

}

88 characters

Page 67: Mobile Programming Lecture 14

XML EfficiencyHow can we represent this data more

efficiently?

<?xml version="1.0"?><note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this

weekend!</body></note>

133 characters

This syntax called JSON

{"to":"Tove","from": "Jani","heading":"Reminder",

"body":"Don't forget me this weekend!"

}

88 characters

Page 68: Mobile Programming Lecture 14

JSON Values

• "title" : "IT Business Analyst Intern"

• "organization" : "Medtronic"

• "city" : "Brooklyn Park"

Page 69: Mobile Programming Lecture 14

JSON Arrays

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

Page 70: Mobile Programming Lecture 14

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"]

}

Page 71: Mobile Programming Lecture 14

Parsing JSONJSONObject json = new JSONObject(raw);

final String moviePlot = "" + json.getString("Plot");

mTextMoviePlot.post(new Runnable() {@Overridepublic void run() {mTextMoviePlot.setText(moviePlot);

}});

Page 72: Mobile Programming Lecture 14

Parsing JSONJSONObject json = new JSONObject(raw);

final String moviePlot = "" + json.getString("Plot");

mTextMoviePlot.post(new Runnable() {@Overridepublic void run() {mTextMoviePlot.setText(moviePlot);

}});

JSONObject is a set of name/value mappings, can represent a JSON document

Page 73: Mobile Programming Lecture 14

Parsing JSONJSONObject json = new JSONObject(raw);

final String moviePlot = "" + json.getString("Plot");

mTextMoviePlot.post(new Runnable() {@Overridepublic void run() {mTextMoviePlot.setText(moviePlot);

}});

Retrieve the plot of the movie

Page 74: Mobile Programming Lecture 14

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

Page 75: Mobile Programming Lecture 14

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"]

}

Page 76: Mobile Programming Lecture 14

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

Page 77: Mobile Programming Lecture 14

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

Page 78: Mobile Programming Lecture 14

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

Page 79: Mobile Programming Lecture 14

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 ...

Page 80: Mobile Programming Lecture 14

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

Page 81: Mobile Programming Lecture 14

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

Page 82: Mobile Programming Lecture 14

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"]

}

Page 83: Mobile Programming Lecture 14

Parsing JSON

See HttpGetJsonExample.tar

Page 84: Mobile Programming Lecture 14

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 developerso 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

Page 85: Mobile Programming Lecture 14

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 XML

Page 86: Mobile Programming Lecture 14

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

Page 87: Mobile Programming Lecture 14

Introducing Web APIs

Some more examples of GET requests

http://droidelicious.com/rest_example/api.php/api/users

http://droidelicious.com/rest_example/api.php/api/users/3

Page 88: Mobile Programming Lecture 14

Introducing Web APIs - Twitter

Let's look at the Twitter public API, a more complicated example

Look at this Twitter profile https://twitter.com/#!/Android

Let's get the profile image from here https://twitter.com/statuses/user_timeline/Android.json

Page 89: Mobile Programming Lecture 14

Introducing Web APIs - Twitter

See JsonTwitterExample.tar

Page 90: Mobile Programming Lecture 14

Introducing Web APIs

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

Page 91: Mobile Programming Lecture 14

Introducing Web APIs

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

Page 92: Mobile Programming Lecture 14

References

• The Busy Coder's Guide to Android Development - Mark Murphy

• Android Developers

• The Mobile Lab at Florida State University