Mobile Application Development
Produced
David Drohan (ddrohan@wit.ie)
by
Department of Computing & Mathematics
Waterford Institute of Technology
http://www.wit.ie
Android Multithreading "
& Networking
Android Multithreading & Networking
2!
Agenda & Goals
❑ Understand what multithreading is and the need for it in
Android development
❑ Be aware of the different approaches available in Android
multithreading
❑ Be aware how to implement some of these approaches
(including AsyncTasks) in an Android app.
❑ Understand JSON & Googles Gson
❑ Investigate the use of Volley in Android Networking
❑ Revisit our Donation Case Study
Android Multithreading & Networking
3!
Background Processes in General
❑ One of the key features of Android (and iPhone) is the ability
to run things in the background
■ Threads
⬥ Run something in the background while user interacts
with UI
■ Services
⬥ Regularly or continuously perform actions that don’t
require a UI
Android Multithreading & Networking
4!
Threads
❑ Recall that Android ensures responsive apps by
enforcing a 5 second limit on Activities
❑ Sometimes we need to do things that take longer than 5
seconds, or that can be done while the user does
something else
❑ Activities, Services, and Broadcast Receivers run on the
main application thread
❑ But we can start background/child threads to do other
things for us
Android Multithreading & Networking
5!
Threads
h"p://developer.android.com/reference/java/lang/Thread.html
q A Thread is a concurrent unit of execution.
q Each thread has its own call stack. The call stack is used on
method calling, parameter passing, and storage for the called
method’s local variables.
q Each virtual machine instance has at least one main thread."
q Threads in the same VM interact and synchronize by the use
of shared objects and monitors associated with these objects.
Android Multithreading & Networking
6!
Threads
Process 1 (Virtual Machine 1)
Process 2 (Virtual Machine 2)
Common memory
resources
Common memory
resources
Main
thread
Thread-2
main
Thread-1 thread
Android Multithreading & Networking
7!
Android Thread Constraints
❑ Child threads cannot access UI elements (views); these
elements must (and can only) be accessed through the
main thread
❑ So what do you do?
■ You give results to the main thread and let it use the
results
Android Multithreading & Networking
8!
Advantages of Multithreading
❑ Threads share the process' resources but are able to execute
independently.
❑ Applications responsibilities can be separated
■ main thread runs UI, and
■ slow tasks are sent to background threads.
❑ Threading provides an useful abstraction of concurrent
execution.
❑ A multithreaded program operates faster on computer
systems that have multiple CPUs. "
(Java 8 supports multi-core multi-threading)
Android Multithreading & Networking
9!
Disadvantages
!
!
q Code tends to be more complex
A1
q Need to detect, avoid, resolve
A3
deadlocks
A2
A1
!
A2
!
WaiBng for A2 WaiBng for A1
to finish to finish
Android Multithreading & Networking
10!
Android‘s Approach to Slow Activities
!
Problem: An application may involve a Bme-consuming operaBon.
Goal: We want the UI to be responsive to the user in spite of heavy load.
Solu<on: Android offers two ways for dealing with this scenario:
!
!
1. Do expensive operaBons in a background service, using
no#fica#ons to inform users about next step
!
!
2. Do the slow work in a background thread.
!
!
Using Threads: InteracBon between Android threads is accomplished using
(a) a main thread Handler object and
(b) posBng Runnable objects to the main view.
Android Multithreading & Networking
11!
Thread Execution – Example
There are basically two main ways of having a Thread execute application code.
!
!
q Create a new class that extends Thread and override its
run() method.
MyThread t = new MyThread();
t.start();
!
!
q Create a new Thread instance passing to it a Runnable object.
!
Runnable myRunnable1 = new
MyRunnableClass(); Thread t1 = new
Thread(myRunnable1); t1.start();
!
!
In both cases, the start() method must be called to actually execute the new
Thread.
Android Multithreading & Networking
12!
Multithreading – Our Splash Screen
2 secs
later
Android Multithreading & Networking
13!
Using the AsyncTask class
h"p://developer.android.com/reference/android/os/AsyncTask.html
q The AsyncTask class allows to perform background operations and
publish results on the UI thread without having to manipulate threads and/
or handlers.
q An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
q An asynchronous task is defined by
3 Generic Types 4 Main States 1 Auxiliary Method
Params, onPreExecute, publishProgress
Progress, doInBackground,
Result onProgressUpdate
onPostExecute.
Android Multithreading & Networking
14!
Using the AsyncTask class
AsyncTask <Params, Progress, Result>
AsyncTask's generic types
Params: the type of the input parameters sent to the task at execuBon.
Progress: the type of the progress units published during the background computaBon.
Result: the type of the result of the background computaBon.
q Not all types are always used by an asynchronous task. To mark a
type as unused, simply use the type Void
Note:
Syntax “String ...” indicates (Varargs) array of String values, similar to “String[]”
Android Multithreading & Networking
15!
Using the AsyncTask class
❑ onPreExecute
■ is invoked before the execution.
❑ onPostExecute
■ is invoked after the execution.
❑ doInBackground
■ the main operation. Write your heavy operation here.
❑ onProgressUpdate
■ Indication to the user on the current progress. It is
invoked every time publishProgress() is called.
Android Multithreading & Networking
16!
Using the
AsyncTask class
1!
2!
3!
4!
Android Multithreading & Networking
17!
Using the AsyncTask class
AsyncTask's methods
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to
setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing.
This step is used to perform background computation that can take a long time. The parameters of the asynchronous
task are passed to this step. The result of the computation must be returned by this step and will be passed back to
the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These
values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing
of the execution is undefined. This method is used to display any form of progress in the user interface while the
background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a
text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the
background computation is passed to this step as a parameter.
Android Multithreading & Networking
18!
The Asynchronous Calls
Android Multithreading & Networking
19!
AsyncTask Lifecycle
PENDING! ASYNCTASK.STATUS.PENDING!
RUNNING! ASYNCTASK.STATUS.RUNNING!
FINISHED!
ASYNCTASK.STATUS.FINISHED!
Android Multithreading & Networking
20!
Let’s look at our !
Donation Example!
Android Multithreading & Networking
21!
http://donationweb-4-0.herokuapp.com!
What do we want?
Android Multithreading & Networking
22!
Donation 5.0 Project Structure
■ api classes for calling REST
service (we’ll investigate these classes in
our networking section)
■ Googles gson for parsing
JSON strings included in build
Android Multithreading & Networking
23!
Donation 5.0 – Donate Activity
Android Multithreading & Networking
24!
Donation 5.0 – Donate Activity
Android Multithreading & Networking
25!
Donation 5.0 – Donate Activity
Android Multithreading & Networking
26!
Donation 5.0 – Donate Activity
Android Multithreading & Networking
27!
Donation 5.0 – AsyncTask : GetAllTask
Android Multithreading & Networking
28!
Donation 5.0 – AsyncTask : GetAllTask
Android Multithreading & Networking
29!
Donation 5.0 – AsyncTask : InsertTask
Android Multithreading & Networking
30!
Donation 5.0 – AsyncTask : InsertTask
Android Multithreading & Networking
31!
Donation 5.0 – ResetTask
Android Multithreading & Networking
32!
Donation 5.0 – ResetTask
Android Multithreading & Networking
33!
Donation 5.0 – ResetTask
Android Multithreading & Networking
34!
Donation 5.0 – Report Activity
Android Multithreading & Networking
35!
Donation 5.0 – Report Activity
Android Multithreading & Networking
36!
Donation 5.0 – Report Activity
Android Multithreading & Networking
37!
Donation 5.0 – Report Activity
Android Multithreading & Networking
38!
Donation 5.0 – Report Activity
Android Multithreading & Networking
39!
Donation 5.0 – Report : GetAllTask
Android Multithreading & Networking
40!
Donation 5.0 – Report : GetAllTask
Android Multithreading & Networking
41!
Donation 5.0 – Report : GetTask
Android Multithreading & Networking
42!
Donation 5.0 – Report : GetTask
Android Multithreading & Networking
43!
Donation 5.0 – Report : DeleteTask
Android Multithreading & Networking
44!
Donation 5.0 – Report : DeleteTask
Android Multithreading & Networking
45!
Donation 5.0 – Report : DonationAdapter
Android Multithreading & Networking
46!
Donation 5.0 – Report : DonationAdapter
Android Multithreading & Networking
47!
A bit about !
JSON !
&!
Googles !
Gson!
Android Multithreading & Networking
48!
Question?
❑ Given a particular set of data, how do you store it permanently?
■ What do you store on disk?
■ What format?
■ Can you easily transmit over the web?
■ Will it be readable by other languages?
■ Can humans read the data?
❑ Examples:
■ A Square
■ A Dictionary
■ A Donation…
Android Multithreading & Networking
49!
Storage Using Plain Text
❑ Advantages
■ Human readable (good for debugging / manual editing)
■ Portable to different platforms
■ Easy to transmit using web
❑ Disadvantages
■ Takes more memory than necessary
❑ Alternative? - use a standardized system -- JSON
■ Makes the information more portable
Android Multithreading & Networking
50!
JavaScript Object Notation – What is it?
❑ Language Independent.
❑ Text-based.
❑ Light-weight.
❑ Easy to parse.
Android Multithreading & Networking
51!
JavaScript Object Notation – What is it?
§ JSON is lightweight text-data interchange format
§ JSON is language independent*
§ *JSON uses JavaScript syntax for describing data objects
§ JSON parsers and JSON libraries exists for many different
programming languages.
§ JSON is "self-describing" and easy to understand
§ JSON - Evaluates to JavaScript Objects
§ The JSON text format is syntactically identical to the code for
creating JavaScript objects.
§ Because of this similarity, instead of using a parser, a JavaScript
program can use the built-in eval()*** function and execute JSON
data to produce native JavaScript objects.
Android Multithreading & Networking
52!
When to use JSON?
❑ SOAP is a protocol specification for exchanging structured
information in the implementation of Web Services.
❑ SOAP internally uses XML to send data back and forth.
❑ REST is a design concept.
❑ You are not limited to picking XML to represent data, you
could pick anything really (JSON included).
Android Multithreading & Networking
53!
JSON example
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
Android Multithreading & Networking
54!
JSON to XML
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<firstName>John</firstName>
<lastName>Smith</lastName>
<age>25</age>
<address>
<streetAddress>21 2nd Street</streetAddress>
<city>New York</city>
<state>NY</state>
<postalCode>10021</postalCode>
</address>
<phoneNumbers>
<phoneNumber>
<number>212 555-1234</number>
<type>home</type>
</phoneNumber>
<phoneNumber>
<number>646 555-4567</number>
<type>fax</type>
</phoneNumber>
</phoneNumbers>
</person>
</persons>
Android Multithreading & Networking
55!
JSON vs XML size
❑ XML: 549 characters, 549 bytes
❑ JSON: 326 characters, 326 bytes
❑ XML ~68,4 % larger than JSON!
❑ But a large data set is going to be large regardless of the data
format you use.
❑ Most servers gzip or otherwise compress content before
sending it out, the difference between gzipped JSON and
gzipped XML isn’t nearly as drastic as the difference between
standard JSON and XML.
Android Multithreading & Networking
56!
JSON vs XML
Favor XML over JSON when any of these is true:
❑ You need message validation
❑ You're using XSLT
❑ Your messages include a lot of marked-up text
❑ You need to interoperate with environments that don't support JSON
Favor JSON over XML when all of these are true:
❑ Messages don't need to be validated, or validating their deserialization is simple
❑ You're not transforming messages, or transforming their deserialization is simple
❑ Your messages are mostly data, not marked-up text
❑ The messaging endpoints have good JSON tools
Android Multithreading & Networking
57!
Security problems***
❑ The eval() function can compile and execute any JavaScript.
This represents a potential security problem.
❑ It is safer to use a JSON parser (like Gson) to convert a JSON
text to a JavaScript object. A JSON parser will recognize only
JSON text and will not compile scripts.
❑ In browsers that provide native JSON support, JSON parsers
are also faster.
❑ Native JSON support is included in newer browsers and in the
newest ECMAScript (JavaScript) standard.
Android Multithreading & Networking
58!
JSON Schema
❑ Describes your JSON data format
❑ http://jsonschemalint.com/
❑ http://json-schema.org/implementations
❑ http://en.wikipedia.org/wiki/
JSON#Schema_and_Metadata
Android Multithreading & Networking
59!
JSON Values
JSON values can be:
❑ A number (integer or floating point)
❑ A string (in double quotes)
❑ A boolean (true or false)
❑ An object (in curly brackets)
❑ An array (in square brackets)
❑ null
Android Multithreading & Networking
60!
JSON Values
❑ Object
■ Unordered set of name-value pairs
■ names must be strings
■ { name1 : value1, name2 : value2, …, nameN : valueN }
❑ Array
■ Ordered list of values
■ [ value1, value2, … valueN ]
Android Multithreading & Networking
61!
Value
v a lu e
s trin g
num ber
o b je c t
a rra y
true
false
null
Android Multithreading & Networking
62!
Strings
❑ Sequence of 0 or more Unicode characters
❑ No separate character type
■ A character is represented as a string with a length of 1
❑ Wrapped in "double quotes"
❑ Backslash escapement
Android Multithreading & Networking
63!
String
s trin g
A n y U N I C O D E c h a ra c te r e x c e p t
" "
" o r \ o r c o n t r o l c h a r a c t e r
q u o ta tio n m a rk
\ "
re v e rs e s o lid u s
\
s o lid u s
/
bac k s pac e
b
fo rm fe e d
f
n e w lin e
n
c a rria g e re tu rn
r
h o riz o n ta l ta b
t
u 4 h e x a d e c im a l d ig its
Android Multithreading & Networking
64!
Numbers
❑ Integer
❑ Real
❑ Scientific
❑ No octal or hex
❑ No NaN or Infinity
■ Use null instead
Android Multithreading & Networking
65!
Number
num ber
0 . d ig it
-
d ig it
e
1 - 9
d ig it E
+
d ig it
-
Android Multithreading & Networking
66!
Booleans
❑ true
❑ false
Android Multithreading & Networking
67!
null
❑ A value that isn't anything
Android Multithreading & Networking
68!
Object
❑ Objects are unordered containers of key/value pairs
❑ Objects are wrapped in { }
❑ , separates key/value pairs
❑ : separates keys and values
❑ Keys are strings
❑ Values are JSON values
■ struct, record, hashtable, object
Android Multithreading & Networking
69!
Object
o b je c t
{ s trin g : v a lu e }
{
"_id":"560515770f76130300c69953",
"usertoken":"11343761234567808125",
"paymenttype":"PayPal",
"__v":0,
"upvotes":0,
"amount":1999
}!
Android Multithreading & Networking
70!
Array
❑ Arrays are ordered sequences of values
❑ Arrays are wrapped in []
❑ , separates values
❑ JSON does not talk about indexing.
■ An implementation can start array indexing at 0 or 1.
Android Multithreading & Networking
71!
Array
a rra y
[ v a lu e ]
[
{"_id":"560515770f76130300c69953","usertoken":"11343761234567808125","
paymenttype":"PayPal","__v":0,"upvotes":0,"amount":1999},
{"_id":"56125240421892030048403d","usertoken":"11343761234567808125","
paymenttype":"PayPal","__v":0,"upvotes":5,"amount":1234},
{"_id":"5627620ac9e9e303005b113c","usertoken":"11343761234567808125","
paymenttype":"Direct","__v":0,"upvotes":2,"amount":1001}
]
Android Multithreading & Networking
72!
MIME Media Type & Character Encoding
❑ application/json
❑ Strictly UNICODE.
❑ Default: UTF-8.
❑ UTF-16 and UTF-32 are allowed.
Android Multithreading & Networking
73!
Versionless
❑ JSON has no version number.
❑ No revisions to the JSON grammar are anticipated.
❑ JSON is very stable.
Android Multithreading & Networking
74!
Rules
❑ A JSON decoder must accept all well-formed JSON
text.
❑ A JSON decoder may also accept non-JSON text.
❑ A JSON encoder must only produce well-formed JSON
text.
❑ Be conservative in what you do, be liberal in what you
accept from others.
Android Multithreading & Networking
75!
Donation 5.0, !
Googles Gson & REST!
Android Multithreading & Networking
76!
Google’s Gson
https://sites.google.com/site/gson/gson-user-guide
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON string
to an equivalent Java object. Gson is an open-source project hosted at
http://code.google.com/p/google-gson.
Gson can work with arbitrary Java objects including pre-existing objects
that you do not have source-code of.
Android Multithreading & Networking
77!
Donation 5.0 & Google’s Gson
Android Multithreading & Networking
78!
Donation 5.0 & Google’s Gson
Android Multithreading & Networking
79!
Donation 5.0 & Google’s Gson
Android Multithreading & Networking
80!
Summary
❑ JSON is a standard way to exchange data
■ Easily parsed by machines
■ Human readable form
❑ JSON uses dictionaries and lists
■ Dictionaries are unordered
■ Lists are ordered
❑ GSON is Googles JSON parser
■ Very simple to use
Android Multithreading & Networking
81!
What is REST?
"REST " was coined by Roy Fielding "
in his Ph.D. dissertation [1] to describe a design
pattern for implementing networked systems.
[1] http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm!
Android Multithreading & Networking
82!
Why is it called "Representational State Transfer"?
http://www.boeing.com/aircraft/747!
Client! Resource!
Fuel requirements!
Maintenance schedule!
...!
Boeing747.html!
• The Client references a Web resource using a URL. !
• A representation of the resource is returned (in this case as an HTML document).!
• The representation (e.g., Boeing747.html) places the client in a new state. !
• When the client selects a hyperlink in Boeing747.html, it accesses another
resource. !
• The new representation places the client application into yet another state. !
• Thus, the client application transfers state with each resource representation.!
Android Multithreading & Networking
83!
REST Characteristics
❑ REST is not a standard (unlike SOAP)
■ You will not see the W3C putting out a REST specification.
■ You will not see IBM or Microsoft or Sun selling a REST developer's toolkit.
❑ REST is just a design pattern
■ You can't bottle up a pattern.
■ You can only understand it and design your Web services to it.
❑ REST does prescribe the use of standards:
■ HTTP
■ URL
■ XML/HTML/GIF/JPEG/etc. (Resource Representations)
■ text/xml, text/html, image/gif, image/jpeg, etc. (Resource Types, MIME
Types)
Android Multithreading & Networking
84!
REST Principles
❑ Everything is a resource
❑ Every resource is identified by a unique identifier
❑ Use simple and uniform interfaces
❑ Communication is done by representation
❑ Be Stateless
❑ We’ll look at these, and more, next year J.
Android Multithreading & Networking
85!
Donation 5.0 & Rest.java
Android Multithreading & Networking
86!
Donation 5.0 & Rest.java – GET Request
Android Multithreading & Networking
87!
Donation 5.0 & Rest.java – POST Request
Android Multithreading & Networking
88!
Donation 5.0 & Rest.java – DELETE Request
Android Multithreading & Networking
89!
Android Networking!
(Using Volley)!
Android Multithreading & Networking
90!
Volley is an HTTP library developed by Google that
makes networking for Android apps easier and most
importantly, faster. Volley is available through the
open AOSP repository.
Introduced during Google I/O 2013, it
was developed because of the absence, in the
Android SDK, of a networking class capable of
working without interfering with the user experience.
Android Multithreading & Networking
91!
Volley
❑ Volley offers the following benefits:
■ Automatic scheduling of network requests.
■ Multiple concurrent network connections.
■ Transparent disk and memory response caching with standard HTTP
cache coherence.
■ Support for request prioritization.
■ Cancellation request API. You can cancel a single request, or you can set blocks
or scopes of requests to cancel.
■ Ease of customization, for example, for retry and backoff.
■ Strong ordering that makes it easy to correctly populate your UI with data fetched
asynchronously from the network.
■ Debugging and tracing tools.
Android Multithreading & Networking
92!
Why Volley?
❑ Avoid HttpUrlConnection and HttpClient
■ On lower API levels (mostly on Gingerbread and Froyo),
HttpUrlConnection and HttpClient are far from being perfect.
There are some known issues and bugs that were never fixed.
■ Moreover, HttpClient was deprecated in the last API update (API
22), which means that it will no longer be maintained and may be
removed in a future release.
■ These are sufficient reasons for deciding to switch to a more
reliable way of handling your network requests.
Android Multithreading & Networking
93!
Why Volley?
❑ Avoid AsyncTask
■ Since the introduction of Honeycomb (API 11), it's been mandatory to
perform network operations on a separate thread, different from the
main thread. This substantial change led the way to massive use of
the AsyncTask<Params, Progress, Result> specification.
■ The class is pretty straightforward, way easier than the
implementation of a service, and comes with a ton of examples
and documentation.
■ The main problem (next slide), however, is the serialization of the
calls. Using the AsyncTask class, you can't decide which request
goes first and which one has to wait. Everything happens FIFO, first
in, first out.
Android Multithreading & Networking
94!
Problem Solved…
❑ The problems arise, for example, when you have to load a list of items
that have attached a thumbnail. When the user scrolls down and
expects new results, you can't tell your activity to first load the JSON of
the next page and only then the images of the previous one. This can
become a serious user experience problem in applications such as
Facebook or Twitter, where the list of new items is more important than
the thumbnail associated with it.
❑ Volley aims to solve this problem by including a powerful cancellation
API. You no longer need to check in onPostExecute whether the
activity was destroyed while performing the call. This helps avoiding
an unwanted NullPointerException.
Android Multithreading & Networking
95!
Why Volley?
❑ It's Much Faster
■ Some time ago, the Google+ team did a series of performance
tests on each of the different methods you can use to make
network requests on Android. Volley got a score up to ten times
better than the other alternatives when used in RESTful
applications.
❑ Small Metadata Operations
■ Volley is perfect for small calls, such as JSON objects, portions of
lists, details of a selected item, and so on. It has been devised for
RESTful applications and in this particular case it gives its very
best.
Android Multithreading & Networking
96!
Why Volley?
❑ It Caches Everything
■ Volley automatically caches requests and this is something truly life-
saving. Let’s return for a moment to the example given earlier. You
have a list of items—a JSON array let’s say—and each item has a
description and a thumbnail associated with it. Now think about what
happens if the user rotates the screen: the activity is destroyed, the list
is downloaded again, and so are the images. Long story short, a
significant waste of resources and a poor user experience.
■ Volley proves to be extremely useful for overcoming this issue. It
remembers the previous calls it did and handles the activity
destruction and reconstruction. It caches everything without you
having to worry about it.
Android Multithreading & Networking
97!
Why Not Volley?
❑ It is not so good, however, when employed for
streaming operations and large downloads. Contrary to
common belief, Volley's name doesn't come from the
sport dictionary. It’s rather intended as repeated bursts
of calls, grouped together. It's somehow intuitive why
this library doesn't come in handy when, instead of a
volley of arrows, you want to fire a cannon ball.
Android Multithreading & Networking
98!
Under the Hood
❑ Volley works on
three different
levels with each
level operating on
its own thread.
Android Multithreading & Networking
99!
Under the Hood
❑ Main Thread
■ On the main thread, consistently with what you already do in the
AsyncTask specification, you are only allowed to fire the request
and handle its response. Nothing more, nothing less.
■ The main consequence is that you can actually ignore everything
that was going on in the doInBackground method. Volley
automatically manages the HTTP transactions and the catching
network errors that you needed to care about before.
Android Multithreading & Networking
100!
Under the Hood
❑ Cache and Network Threads
■ When you add a request to the queue, several things happens under
the hood. First, Volley checks if the request can be serviced from
cache. If it can, the cached response is read, parsed, and delivered.
Otherwise it is passed to the network thread.
■ On the network thread, a round-robin with a series of threads is
constantly working. The first available network thread dequeues the
request, makes the HTTP request, parses the response, and writes it
to cache. To finish, it dispatches the parsed response back to the
main thread where your listeners are waiting to handle the result.
Android Multithreading & Networking
101!
Getting Started With Volley
❑ Download the Volley Source
■ git clone https://android.googlesource.com/platform/frameworks/volley
❑ Import Source as Module
■ File -> New Module, choose Import Existing Project
■ Add dependency compile project(':volley')
❑ Alternative – unofficial mirror site so beware
■ compile 'com.mcxiaoke.volley:library-aar:1.0.15'
Android Multithreading & Networking
102!
Using Volley
❑ Volley mostly works with just two classes, RequestQueue
and Request. You first create a RequestQueue, which
manages worker threads and delivers the parsed results
back to the main thread. You then pass it one or more
Request objects.
❑ The Request constructor always takes as parameters the
method type (GET, POST, etc.), the URL of the resource,
and event listeners. Then, depending on the type of request,
it may ask for some more variables.
Android Multithreading & Networking
103!
Using Volley *
❑ Here we create a RequestQueue
object by invoking one of Volley's
convenience methods,
Volley.newRequestQueue.
This sets up a RequestQueue
object, using default values defined
by Volley.
❑ As you can see, it’s incredibly
straightforward. You create the
request and add it to the request
queue. And you’re done.
❑ If you have to fire multiple requests
in several activities, you should
avoid using this approach - better
to instantiate one shared request
queue and use it across your
project (CoffeeMate 5.0)
Android Multithreading & Networking
104!
CoffeeMate Example!
(Using Volley)!
Android Multithreading & Networking
105!
CoffeeMate 5.0 API & Callback Interface
■ api class for calling
REST service
■ callback mechanism to
update UI
Android Multithreading & Networking
106!
CoffeeMate 5.0 & Volley
❑ Here we ‘attach’ our VolleyListener to the
Fragment (CoffeeFragment) and then getAll() of
the current users coffees.
❑ This method triggers a call to setList() via the
callback interface, which in turn updates the UI
ONLY when our API call completes.
❑ We use a similar approach for Updating, Deleting
etc.
Android Multithreading & Networking
107!
CoffeeApi –
refactored with
Volley *
❑ Here we create a StringRequest
GET request.
❑ On a successful RESPONSE we convert
the result into a List of coffees and
❑ Trigger the callback to set the list in the
fragment (and cancel the refresh
spinner)
Android Multithreading & Networking
108!
CoffeeFragment (Extracts) *
Overriding the necessary
methods from the
interface
Android Multithreading & Networking
109!
CoffeeMate 5.0 – Using AsyncTasks Vs Volley
❑ Using AsyncTasks
❑ Using Volley
■ CoffeeApi
■ CoffeeApi
■ CallBackListener
■ VolleyListener
■ Rest
■ TaskManager
■ CRUD Tasks x 6
❑ Total = 10 Classes
❑ Total = 2 Classes
Android Multithreading & Networking
110!
Summary
❑ We looked at data persistence and multithreading in Android
Development and how to use an SQLite database
❑ We covered a brief overview of JSON & Googles Gson
❑ We covered in detail the use of AsyncTasks and Volley
to execute background tasks and make API calls
❑ We Compared the two in our CoffeeMate Case Study
Android Multithreading & Networking
111!
References
❑ Victor Matos Notes – Lesson 13 (Cleveland State
University)
❑ Android Developers
h"p://developer.android.com/index.html
Android Multithreading & Networking
112!
Sources
❑ http://en.wikipedia.org/wiki/JSON
❑ http://www.w3schools.com/json/
❑ http://www.json.org/
❑ http://json-schema.org
❑ http://www.nczonline.net/blog/2008/01/09/is-json-
better-than-xml/
❑ http://en.wikipedia.org/wiki/SOAP_(protocol)
❑ http://en.wikipedia.org/wiki/REST
❑ http://stackoverflow.com/questions/16626021/json-
rest-soap-wsdl-and-soa-how-do-they-all-link-together
Android Multithreading & Networking
113!
Questions?!
Android Multithreading & Networking
114!