L06 - Android Networking and Threading (ITP4501) 2019
L06 - Android Networking and Threading (ITP4501) 2019
and
Threading
<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"/>
<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>
ProgressBar bar1;
TextView msgWorking;
TextView tvNum;
Button bUpdate;
Button bAdd1;
final int MAX_SEC = 20; // (seconds) lifetime for background thread
tvNum= (TextView)findViewById(R.id.tvNum);
msgWorking= (TextView)findViewById(R.id.TextView01);
bar1.setProgress(100*time_elapsed/MAX_SEC*1000);
msgWorking.setText("Working..."+
bar1.getProgress() );
}
msgWorking.setText("Done!");
}
create doInBackground()
execute publishProgress()
onProgressUpdate()
onPostExecute()
ProgressBar bar1;
TextView msgWorking;
TextView tvNum;
Button bUpdate;
Button bAdd1;
final int MAX_SEC = 20; // (seconds) lifetime for background thread
UpdateProgressBarTask task = null;
}
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();
}
}
@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);
}
}
}
Enter web
address and tap
“Read
Webpage”
button
<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>
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
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();
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
}
Android Networking and Threading 36
Passing Parameters to Server
Invalid
<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);
}
try {
String parameter = "name=" + name;
parameter += "&password=" + pwd.replace(' ', '+');
url += parameter;
} 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.
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.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
• 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 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.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinnerCity = findViewById(R.id.city);
textDescription = findViewById(R.id.description);
try {
url = new URL("https://api.openweathermap.org/data/2.5/weather?
units=metric&appid=yourapikey
&q="+values[0]+",hk");