0% found this document useful (0 votes)
13 views

L06 - Android Networking and Threading (ITP4501) 2019

The document discusses Android networking and threading. It explains that networking operations should run asynchronously on a separate thread to prevent blocking the user interface. It describes how to create threads in Android using both Thread/Handler and AsyncTask, with examples showing progress bar updates from a background thread to avoid janking the UI.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

L06 - Android Networking and Threading (ITP4501) 2019

The document discusses Android networking and threading. It explains that networking operations should run asynchronously on a separate thread to prevent blocking the user interface. It describes how to create threads in Android using both Thread/Handler and AsyncTask, with examples showing progress bar updates from a background thread to avoid janking the UI.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Android Networking

and
Threading

Android Networking and Threading 1


Networking and Threading
• Connecting to internet is one of the most
important tasks and services for mobile
devices.
• Network operations can involve
unpredictable delays.
• To prevent this from causing a poor user
experience, always perform network
operations on a separate thread from the
UI.

Android Networking and Threading 2


Threading
• A Thread is a concurrent unit of execution.
• Each thread has its own call stack and
stores their arguments and local variables.
• Each virtual machine instance has at least
one main Thread running when it is started.
• Then, the main Thread may create other
several threads for specific purposes, such
as I/O process.

Android Networking and Threading 3


Threading
• Android modifies the user interface and
handles input events from the main thread
(also called UI thread).
• Usually all code of an Android application
runs in this thread.
• If you perform a long lasting operation, e.g.
loading a file or accessing data from the
Internet, the user interface of your
application blocks until the corresponding
code has finished.

Android Networking and Threading 4


Threading
• To provide a good user experience all
potentially slow running operations in an
Android application should run
asynchronously, i.e. on another thread.
• Android enforced that with an Application
not responding (ANR) dialog if an activity
does not react within 5 seconds to user
input. From this dialog the user can choose
to stop the application.

Android Networking and Threading 5


Threading

* User Address Space is the memory allocated for storing


variables.
Android Networking and Threading 6
Threading
• Advantages of Multi-Threading
1. Threads share the process' resources but
are able to execute independently.
2. Applications responsibilities can be
separated.
 main thread runs UI, and
 slow tasks are sent to background threads.
3. Threading provides an useful abstraction
of concurrent execution.
4. Under multiple CPUs system, it can
achieve true multi-process, thus the
operations are faster.
Android Networking and Threading 7
Threading
• There are two ways to create Threads and
enable its communications with the main
thread on Android:
1. Thread and Handler
2. AsyncTask
• AsyncTask is simpler and easier.
Throughout this chapter we will use
this technique.

Android Networking and Threading 8


Example of Multi-Threading
• The program intends to display a horizontal
progress bar widget showing the progress
of a slow background operation (20s).

• While the Progress is


being updated, user
can also click the “Add
1” button to increase
the number in the
TextView object by 1.

Android Networking and Threading 9


XML Layout of Example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView android:id="@+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Working ...."
android:textSize="18sp"
android:textStyle="bold" />

<ProgressBar android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />

<Button
android:id="@+id/bUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Updating Progress Bar"
android:onClick="update"/>

Android Networking and Threading 10


XML Layout of Example
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp" >
</LinearLayout>

<EditText
android:id="@+id/tvNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="0" >

<requestFocus />
</EditText>

<Button
android:id="@+id/bAdd1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add 1"
android:onClick="add1"/>

</LinearLayout>

Android Networking and Threading 11


Activity Code [No AsyncTask] (1)
public class Progress_BarActivity extends ActionBarActivity {

ProgressBar bar1;
TextView msgWorking;
TextView tvNum;
Button bUpdate;
Button bAdd1;
final int MAX_SEC = 20; // (seconds) lifetime for background thread

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar1= (ProgressBar) findViewById(R.id.progress);
bar1.setMax(MAX_SEC);
bar1.setProgress(0);

tvNum= (TextView)findViewById(R.id.tvNum);
msgWorking= (TextView)findViewById(R.id.TextView01);

bUpdate = (Button) findViewById(R.id.bUpdate);


bAdd1 = (Button) findViewById(R.id.bAdd1);

Android Networking and Threading 12


Activity Code [No AsyncTask] (I1)
public void update(View v) {
Random rnd= new Random();
int time_elapsed = 0; // in msec
bar1.setProgress(0);
msgWorking.setText("Waiting to start.");
while (time_elapsed < MAX_SEC*1000) {
// Sleep randomly from 0.5 to 1 second
int t = 500 + (int) rnd.nextInt(500) ;
try { The UI Thread
Thread.sleep(t); // sleep t msec
} cannot do anything
catch (InterruptedException e) { until “update”
e.printStackTrace(); finishes
}
time_elapsed += t;

bar1.setProgress(100*time_elapsed/MAX_SEC*1000);
msgWorking.setText("Working..."+
bar1.getProgress() );
}
msgWorking.setText("Done!");
}

public void add1(View v) {


I nt n = Integer.parseInt(tvNum.getText().toString());
tvNum.setText(n+1+"");
} Android Networking and Threading 13
Using AsyncTask
• AsyncTask allows you to perform
asynchronous work on your user interface.
• It performs the blocking operations in a
worker thread and then publishes the
results on the UI thread, without requiring
you to handle threads and/or handlers
yourself.
• To use it, you must subclass AsyncTask and
implement the doInBackground() callback
method, which runs in a pool of background
threads.

Android Networking and Threading 14


Using AsyncTask
• To update your UI, you should implement
onPostExecute(), which delivers the result
from doInBackground() and runs in the UI
thread, so you can safely update your UI.
• You can then run the task by calling
execute() from the UI thread.
• You can specify the type of the parameters,
the progress values, and the final value of
the task, using generics.
• The method doInBackground() executes
automatically on a worker thread
Android Networking and Threading 15
Using AsyncTask
Main Thread Worker Thread

Activity MyAsyncTask extends AsyncTask

create doInBackground()
execute publishProgress()
onProgressUpdate()

onPostExecute()

Android Networking and Threading 16


Using AsyncTask
• onPreExecute(), onPostExecute(), and
onProgressUpdate() are all invoked on
the UI thread
• The value returned by doInBackground() is
sent to onPostExecute()
• You can call publishProgress() at anytime in
doInBackground() to execute
onProgressUpdate() on the UI thread
• You can cancel the task at any time, from
any thread

Android Networking and Threading 17


Example of Using AsyncTask
• Only the main process can access the
(main) activity’s view.
• The background (Worker) thread will not
interact with the UI.

Android Networking and Threading 18


AsyncTask Class
AsyncTask is a generic class, it uses 3
types: AsyncTask<Params, Progress,
Result>
• Params – the input. what you pass to
the AsyncTask
• Progress – if you have any updates,
passed to onProgressUpdate()
• Result – the output. what returns
doInBackground()

Android Networking and Threading 19


doInBackground(String...
params)
params represents an unknown number
of parameters. For example:
new AsyncHttpPost().execute(s1,s2,s3);
• params[0] is the first string s1
• params[1] is the second string s2
• params[2] is the third string s3

Android Networking and Threading 20


Activity Code [Using AsyncTask] (1)
public class Progress_BarActivity_AsyncTask extends ActionBarActivity {

ProgressBar bar1;
TextView msgWorking;
TextView tvNum;
Button bUpdate;
Button bAdd1;
final int MAX_SEC = 20; // (seconds) lifetime for background thread
UpdateProgressBarTask task = null;

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar1 = (ProgressBar) findViewById(R.id.progress);
bar1.setMax(100);
bar1.setProgress(0);

tvNum = (TextView) findViewById(R.id.tvNum);


msgWorking = (TextView) findViewById(R.id.TextView01);

bUpdate = (Button) findViewById(R.id.bUpdate);


bAdd1 = (Button) findViewById(R.id.bAdd1);

}
Android Networking and Threading 21
Activity Code [Using AsyncTask] (1)
public void update(View v) {
if (task == null || task.getStatus().equals(AsyncTask.Status.FINISHED)) {
bar1.setProgress(0);
msgWorking.setText("Waiting to start.");
task = new UpdateProgressBarTask();
task.execute();
}
}

public void add1(View v) {


int n = Integer.parseInt(tvNum.getText().toString());
tvNum.setText(n + 1 + "");
}

private class UpdateProgressBarTask extends AsyncTask<String, Integer, String> {


@Override
protected String doInBackground(String... values) { // parameters not used here
Random rnd = new Random();
int time_elapsed = 0; // in msec

while (time_elapsed <= MAX_SEC * 1000) {


// Sleep randomly from 0.5 to 1 second
int t = 500 + (int) rnd.nextInt(500);
try {
Thread.sleep(t); // sleep t msec
} catch (InterruptedException e) {
e.printStackTrace(); Android Networking and Threading 22
Activity Code [Using AsyncTask] (1)
time_elapsed += t;
int x = 100 * time_elapsed / MAX_SEC * 1000;
publishProgress(new Integer(100 * time_elapsed
/ (MAX_SEC * 1000)));
}
return "Done!"; //return to onPostExecute
}

@Override
protected void onProgressUpdate(Integer... values) {
bar1.setProgress(values[0].intValue());
msgWorking.setText("Working..." + bar1.getProgress() + "%");
}

@Override
protected void onPostExecute(String result) {
msgWorking.setText(result);
}
}
}

Android Networking and Threading 23


Activity Code [Using AsyncTask] (1)
Questions: What happens if we move the lines
bar1.setProgress(0);
msgWorking.setText("Waiting to start.");
to the beginning of doInBackground?
public void update(View v) {
if (task == null || task.getStatus().equals(AsyncTask.Status.FINISHED)) {
bar1.setProgress(0);
msgWorking.setText("Waiting to start.");
task = new UpdateProgressBaeTask();
task.execute();
}
}

public void add1(View v) {


int n = Integer.parseInt(tvNum.getText().toString());
tvNum.setText(n + 1 + "");
}

private class UpdateProgressBaeTask extends AsyncTask<String, Integer, String> {


@Override
protected String doInBackground(String... values) { // parameters not used here
Random rnd = new Random();
int time_elapsed = 0; // in msec

Android Networking and Threading 24


HTTP
• HTTP stands for hyper text transport protocol.
• HTTP is the standard transport protocol for web
browser <----> web server communication.
• One of the key features of HTTP is that
communication is stateless between requests.
• Android contains the Apache HttpURLConnection
library for performing network operations in Android.
• Obtain a new HttpURLConnection by calling
URL.openConnection() and casting the result to
HttpURLConnection.

Android Networking and Threading 25


Internet Permission
• To access the internet your application requires the
"android.permission.INTERNET" permission in the
file AndroidManifests.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ict.mobile"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET" />

<application android:icon="@drawable/icon" android:label="@string/app_name">


<activity android:name=".JSONExample"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Networking and Threading 26
Networking Functions
• Beginning from Android 3.0, all networking functions
MUST be handled in a separated thread.
• To simplify the programs, the networking examples
are all implemented without multi-thread except the
next one.
• That means you either run those programs on
Android 2.3.3 devices/emulators or change them to
using AsyncTask.

Android Networking and Threading 27


Example 1 - FetchAPageSource
• This example demonstrates how to fetch a web page
and display the content in using a TextView.

Enter web
address and tap
“Read
Webpage”
button

Android Networking and Threading 28


Example 1 - FetchAPageSource
• Note:
1. The address should be typed correctly and the
protocol (i.e. http://) MUST be included! (or your
program can add it automatically if not present)
2. To access internet behind a proxy, you need to
set up the emulator proxy information.
Method 1
Start the emulator with -http-proxy option. e.g.
emulator -http-proxy http://hqproxy.vtc.edu.hk:8080 -avd Android2_3_3

Android Networking and Threading 29


Example 1 - FetchAPageSource
Method 2
[Eclipse Menu] > [Run] > [Run Configuration] >
[Target] tab > [Additional Emulator Command
Line Options] > Enter proxy and port option.

3. For simplicity, the network connection is done in


the UI thread. The phone will have no response if
the network connection is slow or held up. In
fact, the network operations should be done in a
separated thread to ensure the responsiveness.
Android Networking and Threading 30
FetchAPageSource – main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/address"></EditText>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Webpage"
android:id="@+id/ReadWebPage"
android:onClick="clickHandler"></Button>
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/pagetext"
android:scrollbars="vertical"></TextView>
</LinearLayout>

Android Networking and Threading 31


FetchAPageSource.java
public class FetchAPageSource extends ActionBarActivity {
private EditText urlText;
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

urlText = (EditText) findViewById(R.id.address);


textView = (TextView) findViewById(R.id.pagetext);
}

public void clickHandler(View view) {


InputStream inputStream = null;
String result = "";

URL url = null;


try {
textView.setText("");

Android Networking and Threading 32


FetchAPageSource.java
url = new URL(urlText.getText().toString());
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
// Make GET request
// May omit this line since "GET" is the default.
con.setRequestMethod("GET");
con.connect();

// Get response string from inputstream of connection


inputStream = con.getInputStream();
BufferedReader bufferedReader = new
BufferedReader(new
InputStreamReader(inputStream));
String line = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();

textView.setText(result);
} catch (Exception e) {
textView.setText(e.getMessage());
}
}
}
Android Networking and Threading 33
FetchAPageSource.java (With AsyncTask)
public class FetchAPageSource extends ActionBarActivity {
private EditText urlText;
private TextView textView;
FetchPageTask task = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

urlText = (EditText) findViewById(R.id.address);


textView = (TextView) findViewById(R.id.pagetext);
}

public void clickHandler(View view) {


textView.setText("");

if (task == null ||
task.getStatus().equals(AsyncTask.Status.FINISHED)) {
task = new FetchPageTask();
task.execute(urlText.getText().toString());
}
}
Android Networking and Threading 34
FetchAPageSource.java (With AsyncTask)
private class FetchPageTask extends AsyncTask<String, Integer,
String> {
@Override
protected String doInBackground(String... values) {
InputStream inputStream = null;
String result = "";
URL url = null;

try {
url = new URL(values[0]);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();

// Make GET request


con.setRequestMethod("GET");
con.connect();

Android Networking and Threading 35


FetchAPageSource.java (With AsyncTask)
// Get response string from inputstream of connection
inputStream = con.getInputStream();
BufferedReader bufferedReader = new
BufferedReader(new InputStreamReader(inputStream));

String line = "";


while((line = bufferedReader.readLine()) != null)
result += line;

Log.d("doInBackground", "get data complete");


inputStream.close();
} catch (Exception e) {
result=e.getMessage();
}
return result;
}

@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
}
Android Networking and Threading 36
Passing Parameters to Server

• Typically, an HTTP request to a server is


accompanied by information needed by the
server to process the request.

Android Networking and Threading 37


Passing Parameters to Server
 e.g. Login in case.
• A server must authenticate a client using the client’s
user ID and password.
• The client sends the user ID and password along with
the HTTP request.
• Two techniques are used to send data to the server: GET
or POST request methods.
• The GET request method requires that data be
concatenated to the URL of the server.
• The POST request method requires that each pair value
be written to the output stream (NOT covered in this
chapter).
Android Networking and Threading 38
Passing Parameters to Server
• Data sent to a server must be in a pair value set:
◦ field name
◦ the value associated with the field.
• The field name and value must be separated by an equal sign
(=).
• The pair value sets are separated from the URL by a question
mark (?).
• Each pair value set is separated from other pair value sets by
an ampersand (&).
• The space character is converted to a plus (+) sign.
• For example, the following request sends two parameters:
pOne="one bit" and pTwo="two"
http://localhost/midp/simple?pOne=one+bit&pTwo=two
• Question: How to send a plus sign (+)? Ans: use %2B
Android Networking and Threading 39
Example : NetworkLogin

• User enters a login id and a password


• The Activity sends the request to the web server
• The web server executes a simple php script and
validates the user according to the following
table
Login ID Password
andy cat
paul panda
jacky doctor
peter a1 b

Android Networking and Threading 40


Example : NetworkLogin
Valid
Login

Invalid

Android Networking and Threading 41


NetworkLogin – main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout android:layout_width="match_parent"
android:layout_height="match_parent" android:stretchColumns="1"
android:padding="10dip">
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Login ID" />
<EditText android:id="@+id/editTextID"
android:padding="10dip"></EditText>
</TableRow>

<TableRow
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:text="Password" />
<EditText android:id="@+id/editTextPwd"
android:padding="10dip"></EditText>
</TableRow>
<Button android:layout_height="wrap_content"
android:layout_width="match_parent" android:text="Login"
android:onClick="clickHandler"></Button>
</TableLayout>
</ScrollView>
Android Networking and Threading 42
NetworkLogin.java
public class NetworkLogin extends ActionBarActivity {
private EditText idText;
private EditText pwdText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
idText = (EditText) findViewById(R.id.editTextID);
pwdText = (EditText) findViewById(R.id.editTextPwd);
}

public void clickHandler(View view) {


InputStream inputStream = null;
String result = "";
String name = idText.getText().toString();
String pwd = pwdText.getText().toString();
String url =
” http://ictlab.tyict.vtc.edu.hk/~nelsonc/mobile/login_demo.php?";
URL urlAddress = null;

try {
String parameter = "name=" + name;
parameter += "&password=" + pwd.replace(' ', '+');
url += parameter;

Android Networking and Threading 43


NetworkLogin.java
urlAddress = new URL(url);
HttpURLConnection con = (HttpURLConnection)
urlAddress.openConnection();

// Make GET request


con.setRequestMethod("GET");
con.connect();

// Get response string from inputstream of connection


inputStream = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));

String line = "";


while((line = bufferedReader.readLine()) != null)
result += line+ "\n";

result = result.trim(); // ignore all white spaces


inputStream.close();

Android Networking and Threading 44


NetworkLogin.java
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
if (result.equalsIgnoreCase("OK")) {
alertbox.setMessage("Login is successful!");
} else {
// Create the alert box
alertbox.setMessage("Login fails!");
}
alertbox.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
}
});
alertbox.show();

} catch (Exception e) {
Log.e("Error:", e.getMessage());
}
}
}

Hint: Make sure your link is correct by coping and pasting the link
(e.g. http://ictlab.tyict.vtc.edu.hk/~nelsonc/mobile/login_demo.php?name=andy&password=cat )
to the browser and check the connection and result returned.
Android Networking and Threading 45
Embedded Browser (WebView)
• There are several reasons why an application may
want to have access to a web browser.
• Example: display HTML fragments, access external
services, open Google search etc.
• Additionally, accessing HTTP resources without a
web browser abstraction layer is tedious and
unnecessary.
• Android provides two solutions to this issue:
1. Use an Intent to cause Android to launch its own system
browser (discussed in another chapter).
2. Embed a WebView controller inside an Activity
• Both of these approaches have their own unique
advantages and disadvantages.
Android Networking and Threading 46
Using WebView
• The WebView controller allows for HTML
fragments and web pages to be displayed in
an activity.
• WebView interacts with an Android activity
like any other widget.
• As such, an activity can capture events and
as well as interact with the DOM on the page.
• Unfortunately, the WebView implementation
does not support AJAX out of the box.

Android Networking and Threading 47


WebViewExample
Three widgets:
1. EditText contains the URL to load.
2. A Go button to start page loading.
3. A WebView to display the page

Note:
4. The protocol (e.g. http://) is
required.
5. If the URL (e.g. http://www.vtc.edu.hk) has a redirect, the default
behavior for Android is to launch a browser to handle it.
6. You may use WebViewClient and shouldOverrideUrlLoading() to
catch the redirect and re-route them back to the WebView.

Android Networking and Threading 48


WebViewExample – main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent” android:layout_height="match_parent"
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent”
android:layout_height="wrap_content">
<EditText
android:id="@+id/url_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0”
android:lines="1"
android:inputType="textUri"
android:imeOptions="actionGo" />
<Button
android:id="@+id/go_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout>
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0" />
Android Networking and Threading 49
</LinearLayout>
WebViewExample.java
public class WebViewExample extends ActionBarActivity {
private EditText urlText;
private Button goButton;
private WebView webView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get a handle to all user interface elements


urlText = (EditText) findViewById(R.id.url_field);
goButton = (Button) findViewById(R.id.go_button);
webView = (WebView) findViewById(R.id.web_view);

// The following code is to force WebView to load links


webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView
view,
String url) {
return false;
}});
Android Networking and Threading 50
WebViewExample.java
// Setup event handlers
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
openBrowser();
}
});
urlText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
openBrowser();
return true;
}
return false;
}
});
}

/** Open a browser on the URL specified in the text box */


private void openBrowser() {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(urlText.getText().toString());
}
} Android Networking and Threading 51
REST Web Services
• REST stands for Representational State
Transfer.
• REST is a style of software architecture for
distributed hypermedia systems such as the
World Wide Web.
• A RESTful web service (also called a RESTful
web API) is a simple web service
implemented using HTTP and the principles
of REST.

Android Networking and Threading 52


JSON
• JavaScript Object Notation (JSON) is a
lightweight text-based open standard
designed for human-readable data
interchange.
• It is derived from the JavaScript
programming language and is language-
independent, with parsers available for most
programming languages.
• Similar to XML and has quickly become one of
the most popular formats for data exchange
on the internet.

Android Networking and Threading 53


JSON
• Example A JSON personal record

• Why JSON?
• JSON is faster and easier than XML.
Android Networking and Threading 54
JSON
• JSON Syntax Rules
◦ Data is in name/value pairs
◦ Data is separated by commas
◦ Curly braces hold objects
◦ Square brackets hold arrays

• JSON Name/Value Pairs


 JSON data is written as name/value pairs:
"firstName" : "John"
 JSON value can be: a number, a string, a Boolean, an
array, an object or null
 Can you give an example for each of the JSON value type
from the above JSON personal record?

Android Networking and Threading 55


JSON
• JSON Objects
◦ JSON objects are written inside curly brackets,
◦ Objects can contain multiple name/values pairs:
{ "firstName":"John" , "lastName":"Doe" }

• JSON Arrays
◦ JSON arrays are written inside square brackets.
◦ An array can contain multiple objects:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Android Networking and Threading 56
Parsing JSON Data
• A typical Android network application is to retrieve a
JSON data from internet.
• Your task is to parse it and obtain the values it
stores.
• Android provides a set of API to parse a JSON data.
• Your very first step is to create a JSON object for the
data received:
JSONObject jObj = new JSONObject(data);
• Then you can use this object with the getXXX
methods to extract the values from the JSON data.

Android Networking and Threading 57


JSONObject get Methods
Object get(String name)
Returns the value mapped by name.
boolean getBoolean(String name)
Returns the value mapped by name if it exists and is a boolean or
can be coerced to a boolean.
double getDouble(String name)
Returns the value mapped by name if it exists and is a double or can
be coerced to a double.
int getInt(String name)
Returns the value mapped by name if it exists and is an int or can be
coerced to an int.
JSONArray getJSONArray(String name)
Returns the value mapped by name if it exists and is a JSONArray.
JSONObject getJSONObject(String name)
Returns the value mapped by name if it exists and is a JSONObject.
long getLong(String name)
Returns the value mapped by name if it exists and is a long or can be
coerced to a long.
String getString(String name)
Returns the value mapped by name if it exists, coercing it if
necessary.
Android Networking and Threading 58
Parsing JSONObject

• Suppose data stores the string shown


and a JSONObject is created
JSONObject jObj = new JSONObject(data);
• To get the first name you use
String fName = jObj.getString("firstName");
• To get the age you use
int age = jObj.getInt("age");
• A slightly more complicated example: to get the city you need
two steps:
JSONObject addrObj = jObj.getJSONObject("address");
String city = addrObj.getString("city");
Android Networking and Threading 59
Parsing JSONArray
• JSONArray provides similar
getXXX methods as JSONObject
with index, instead of name, as
the parameter. Also it provides the
method length() which returns the
numbers of element it holds.
• The index begins from 0.
• For example, to get the fax number (index 1) you need three
steps:
JSONArray phoneArray = jObj.getJSONArray("phoneNumbers");
JSONObject faxObj = phoneArray.getJSONObject(1);
String fax = faxObj.getString("number");
• The above lines can be combined into one statement:
String fax = jObj.getJSONArray("phoneNumbers").
getJSONObject(1).getString("number");

Android Networking and Threading 60


API JSON Example
• There are many public API provides a RESTful web
service for HTTP clients. We are going to write an
application that can provide Hong Kong weather
information.
• Usually we need to apply a API Key before to apply
the API in your app.
• Please go to https://openweathermap.org to apply
your own api key.
• You can directly use an URL in a browser to test
your API and get the corresponding JSON.
• Following URL can get the current Hong Kong
weather:
• http://api.openweathermap.org/data/2.5/weather?q=Hong%20kon
g,hk&units=metric&appid=
yourapikey
Android Networking and Threading 61
API JSON Example
Widgets:
1. One Spinner object (Cities List).
2. One Button to get the JSON.
3. One TextView to hold the result.

Android Networking and Threading 62


API JSON Example
• The following table lists the required URL
arguments.
Argument Example Description
q q=Hong%20Kong,hk city and country.
units units=metric use Celsius.

key to use this api, you must sign up


appid appid=yourapikey at openweathermap.org and then get
the key.

Android Networking and Threading 63


API JSON Example
• API documents for current weather
• https://openweathermap.org/current
• JSON sample:

Android Networking and Threading 64


API JSON Example
public class JSONExample extends Activity {
private Spinner spinnerCity;
private TextView textDescription;
FetchPageTask task = null; //use the Async Class in Slide 35

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinnerCity = findViewById(R.id.city);
textDescription = findViewById(R.id.description);

// Spinner user interface uses standard layouts


String cities[] = { "Hong Kong", "Kowloon", "Central", "Mongkok",
"Kowloon City", "Sheung Wan", "Tsuen Wan", "Tsim Sha Tsui"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cities);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(adapter);

// Automatically select first spinner items


spinnerCity.setSelection(0); // English (en)
}

Android Networking and Threading 65


API JSON Example
public void onClick(View view) {
if (task == null || task.getStatus().equals(AsyncTask.Status.FINISHED)) {
task = new FetchPageTask();
task.execute(spinnerCity.getSelectedItem().toString());
}
}

private class FetchPageTask extends AsyncTask<String, Integer, String> {


@Override
protected String doInBackground(String... values) { // parameters not
String result="";
URL url = null;
InputStream inputStream = null;

try {
url = new URL("https://api.openweathermap.org/data/2.5/weather?
units=metric&appid=yourapikey
&q="+values[0]+",hk");

//use codes in slide 35


...
}

Android Networking and Threading 66


API JSON Example
@Override
protected void onPostExecute(String result) {
// Parse to get weather information in String result
try {
JSONObject jObj = new JSONObject(result);
JSONArray weather = jObj.getJSONArray("weather");
String description = weather.getJSONObject(0)
.getString("description");
String temp = jObj.getJSONObject("main")
.getString("temp");
String temp_min = jObj.getJSONObject("main")
.getString("temp_min");
String temp_max = jObj.getJSONObject("main")
.getString("temp_max");
textDescription.setText(description+"\n"+
"Current Temperature: "+temp+"\n"+
"Minimum Temperature: "+temp_min+"\n"+
"Maximum Temperature: "+temp_max);
} catch (Exception e) {
String error = e.getMessage();
textDescription.setText(error);
}
}
Android Networking and Threading 67

You might also like