USING ANDROID WITH THE INTERNET. Slide 2 Network Prerequisites The following must be included so as...
-
Upload
crystal-patrick -
Category
Documents
-
view
216 -
download
0
Transcript of USING ANDROID WITH THE INTERNET. Slide 2 Network Prerequisites The following must be included so as...
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 tag should be an immediate child of <manifest>
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Slide 3
HTTP (Introduction) In most cases the transfer protocol is
HTTP We connect our device to a server and get
data We then process that data somehow
Two HTTP clients HttpClient HttpURLConnection
Both support HTTPS and IPV6 Use HttpURLConnection for post
Lollypop devices
Slide 4
Checking for Network Access The network might be unavailable for
many reasons We may have WiFi service or just cell
service Note that service might be metered so
we need to limit bandwidth
Slide 5
The ConnectivityManager The ConnectivityManager answers
questions about the state of the network
The getSystemService( Context.CONNECTIVITY_SERVICE) method gets an instance of the class
Slide 6
The NetworkInfo Class The getActiveNetworkInfo class
returns an NetworkInfo instance Call the isConnected method to
determine whether there is a network connection
See http://developer.android.com/reference/android/net/NetworkInfo.html
Slide 7
Introduction to Multithreading Many activities can take a while to
complete Some activities might not complete at
all A thread is a concurrent unit of
execution There is a thread for the UI We can create other threads
This is a complicated topic but I’ll provide just enough here for you to create a thread and run it
Slide 8
The AsyncTask Class (Introduction) The android.os.AsyncTask allows
background operations to be performed and returned to the UI thread
It is a helper class that wraps the Thread class
Use it to perform short-lived background tasks
Params, Progress, Result
Slide 9
The AsyncTask Class (Creating) To use the AsyncTask create a subclass
with three generic parameters The first contains the data passed to the
thread The second, if used contains an integer
used to report the thread’s progress The third, if used contains the data type of
the thread value. If the parameter is Void, then it will not be
used
Slide 10
The AsyncTask Class (Example) Extend AsyncTask
A string is passed to the task There is no progress reporting A string is returned from the task
When the background task is executed, it goes through four steps
Slide 11
The AsyncTask Class (Implementing – Step 1) onPreExecute is invoked on the UI
thread before the task begins It is here that you setup the task Initialize a progress meter, for example
Implementing this step is optional
Slide 12
The AsyncTask Class (Implementing – Step 2) doInBackground is the worker It executes immediately after onPreExecute finishes
It is here that you perform the background computation
The parameters are passed to this procedure
The results are returned in this step Call publishProgress(Progress…) to
publish progress results (optional)
Slide 13
The AsyncTask Class (Implementing – Step 2) String… denotes a variable length
array of type String So urls contains the parameters
Slide 14
The AsyncTask Class (Implementing – Step 3) onProgressUpdate is invoked on the UI
thread It gets called as a result of the publishProgress call
Use it to update a progress meter or log Implementing this method is optional
Slide 15
The AsyncTask Class (Implementing – Step 4) onPostExecute is invoked on the UI
thread The parameter contains the result of the
asynchronous method call
Slide 16
STATUS You now know how to set up the
asynchronous infrastructure
Net we will see how to send a HTTP request with a URL and process the result
Slide 17
Android URL and HTTP Related Classes The URL class
Slide 18
The URL Class The java.net.URL class represents a url
Convert strings to URLs Convert URLs to strings
http://developer.android.com/reference/java/net/URL.html
Slide 19
The URL Class
Slide 20
Opening a Connection (1) The URL.openConnectcion() method
establishes a connection to a resource Over this connection, you make the
request and get the response We will use HTTP here but other
protocols are supported
Slide 21
Opening a Connection (2) The setReadTimeout setter defines the
time to wait for data The setConnectTimeout setter the time
to wait before establishing a connection The setRequestMethod defines
whether the request will be a GET or a POST
The setDoInput setter, if true allows receiving of data
Slide 22
Opening a Connection (3) Calling the connect() method opens
the connection getResponseCode() gets the HTTP
response code from the server -1 if there is no response code. Such as 404 not found?
getInputStream() gets the input stream from which you can read data Works just like an open file
Slide 23
Opening A Connection (Example)
Slide 24
Reading the Input
Slide 25
Introduction to XML XML is briefly discussed here as it
provides a generalized means to get URL data Many services return data as XML
Slide 26
What XML Does
Nothing
Slide 27
What XML is Philosophically (1) It’s a language designed to describe
data in a hierarchical way By itself, XML is useless XML does not process the data it describes Simply put, XML elements are collected
together into an XML document It’s up to “something else” to process that
document
Slide 28
What XML is Philosophically (2) Hierarchical XML data can represent
anything Even though XML does nothing with the
data That’s because XML describes data
XML does not describe the meaning of data There are other XML “recommendations”
that give meaning to XML data
Slide 29
A First XML Example The answer (question) to the universe is
42
<?xml version="1.0" encoding="utf-8" ?><Universe> <Answer>42</Answer></Universe>
Slide 30
How XML Works (1) An XML document is processed using a
generic XML parser Companies that support XML have an
implementation of an XML parser The XML Document Object Model (DOM)
represents an XML document in-memory Again, this representation is defined by the W3C .NET supports the “level 2” DOM representation
Slide 31
How XML Works (2) An XML parser processes hierarchical XML
data, which is made up of: markup – Tags, references, and declarations,
which are processed by the XML parser character data – Data appearing between the
markup Character data is not processed by the XML
parser It’s the document’s data
Slide 32
XML Documents (Introduction) XML syntax is simple but rigorous
An XML document must be syntactically correct to be well formed
As opposed to HTML document which can be processed even though the are incorrect
An XML document must adhere to the rules set for by a DTD or XSD to be valid
Formally, an XML document is an instance of a class defined by the DTD or XSD
More on this topic later when we get to document validation
Slide 33
Introduction to XML Syntax (1) XML tags resemble HTML tags but they are not
predefined That is, you give names to tags just as you give
names to variables and other identifiers Starting tags appear as <tag> Ending tags appear as </tag> Empty elements can appear as <tag/>
XML elements MUST have an ending tag unlike HTML A starting and ending tag makes up an element
Slide 34
Introduction to XML Syntax (2) An element can have different types of
content If an element contains other elements, it has
element content If an element contains text and other elements,
the element has mixed content If an element contains only data, then the element
has simple content Elements can also have 0, 1 or more
attributes
Slide 35
Introduction to XML Syntax (3) Tags can be nested
These are hierarchical nodes Tags MUST be nested correctly though
There must be only one root tag White space is preserved in XML documents
This is a big departure from HTML A new line is represented with the LF character Space and Tab characters are also considered
white space
Slide 36
XML Attributes (Introduction) Tags can have one or more attributes
Attributes appear after the tag name Attributes are conceptually similar to properties
An attribute could also be implemented as a nested element
The choice is yours As you will see, a schema restricts and
attribute’s values or occurrences
Slide 37
XML Attributes (Syntax 1) Attributes appear as key=value pairs
An attribute must have both a key and a value Attribute keys do not appear in quotation
marks Attribute values must appear in quotation
marks Remember, single and double quotes are
interchangeable A space separates each key=value pair
Slide 38
XML Attributes (Example) In the following example, id is the
attribute
<?xml version="1.0" encoding="utf-8" ?><Universe id="1" size="Infinite"> <Answer>42</Answer></Universe>
Slide 39
Comparing Attributes and Elements The following 2 documents are (roughly)
equivalent<?xml version="1.0" encoding="utf-8" ?><student id="12345"> <name>Bill</name></student><?xml version="1.0" encoding="utf-8" ?><student> <id>12345</id> <name>Bill</name></student>
Slide 40
Processing XML In Android There are several Android and Java
classes with which we can process an XML document
Generally speaking we can Read the data sequentially using a SAX
parser Read the data into an in-memory XML
document, with which we can do some DOM processing
We will use a DOM parser My demo continues to work with the
weather.
Slide 41
Processing XML All XML nodes
have a typehttp://www.w3schools.com/dom/dom_nodetype.asp
Slide 42
Processing XML Create a DocumentBuilder via the
DocumentBuilderFactory Call the parse method on an input
stream to read and parse the document Using the Document object, navigate
and work with the in-memory XML document
Slide 43
Classes We Need DocumentBuilderFactory DocumentBuilder Document NodeList Node InputSource StringReader
Slide 44
The DocumentBuilderFactory Class
It lets applications get a parser that produced XML object trees from XML documents This is pretty much the same DOM with
which you are familiar (JavaScript) As the name implies, we use a factory
class and method to create the
Slide 45