Lesson 10 Asynctask Parsing Json
Lesson 10 Asynctask Parsing Json
AsyncTask
Http Connection
Parsing JSON
A. AsyncTask
Concurrency Control
Using the AsyncTask Class
1. The AsyncTask class allows the execution of
background operations and the publishing of
results on the UI’s thread without having to
manipulate threads and/or handlers.
Params: the type of the input parameters sent to the task at execution.
Progress: the type of the progress units published during the background
computation.
Result: the type of the result of the background computation.
Note:
The Java notation “String ...” called Varargs indicates an array of String values. This
syntax is somehow equivalent to “String[]” (see Appendix B).
4
Concurrency Control
Using the AsyncTask Class
private class VerySlowTask extends AsyncTask<String, Long, Void> {
}
// this is the SLOW background thread taking care of heavy tasks
// cannot directly change UI
2 protected Void doInBackground(final String... args) {
... publishProgress((Long) someLongValue);
}
// periodic updates - it is OK to change UI
@Override
3 protected void onProgressUpdate(Long... value) {
}
// End - can use UI thread here
4 protected void onPostExecute(final Void unused) {
}
}
50
Concurrency Control
Using the AsyncTask Class
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.
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.
Reference: http://developer.android.com/reference/android/os/AsyncTask.html 51
Concurrency Control
Example: Using the AsyncTask Class
The main task invokes an AsyncTask to do some slow job. The AsyncTask method
doInBackgroud(…) performs the required computation and periodically uses the
onProgressUpdate(…) function to refresh the main’s UI. In our the example, the AsyncTask
manages the writing of progress lines in the UI’s text box, and displays a ProgressDialog box.
52
Concurrency Control
Example : Using the AsyncTask Class - XML Layout
<?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" >
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp" />
<Button
android:id="@+id/btnSlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:text="Do some SLOW work" />
<Button
android:id="@+id/btnQuick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:text="Do some QUICK work" />
</LinearLayout> 53
Concurrency Control
Example: Using the AsyncTask Class - XML Layout
public class MainActivity extends Activity {
Button btnSlowWork;
Button btnQuickWork;
EditText txtMsg;
Long startingMillis;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMsg = (EditText) findViewById(R.id.txtMsg);
// slow work...for example: delete databases: “dummy1” and “dummy2”
btnSlowWork = (Button) findViewById(R.id.btnSlow);
this.btnSlowWork.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
1 new VerySlowTask().execute("dummy1", "dummy2");
}
});
btnQuickWork = (Button) findViewById(R.id.btnQuick);
this.btnQuickWork.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
txtMsg.setText((new Date()).toString()); // quickly show today’s date
}
}); 54
}// onCreate
Concurrency Control
Example: Using the AsyncTask Class - XML Layout
private class VerySlowTask extends AsyncTask<String, Long, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
String waitMsg = "Wait\nSome SLOW job is being done... ";
2 protected void onPreExecute() {
startingMillis = System.currentTimeMillis();
txtMsg.setText("Start Time: " + startingMillis);
this.dialog.setMessage(waitMsg);
this.dialog.setCancelable(false); //outside touch doesn't dismiss you
this.dialog.show();
}
3
protected Void doInBackground(final String... args) {
// show on Log.e the supplied dummy arguments
Log.e("doInBackground>>", "Total args: " + args.length );
Log.e("doInBackground>>", "args[0] = " + args[0] );
try {
for (Long i = 0L; i < 5L; i++) {
Thread.sleep(10000); // simulate the slow job here . . .
publishProgress((Long) i);
}
} catch (InterruptedException e) {
Log.e("slow-job interrupted", e.getMessage());
}
return null; 55
}
Concurrency Control
Example: Using the AsyncTask Class - XML Layout
// periodic updates - it is OK to change UI
@Override
4 protected void onProgressUpdate(Long... value) {
super.onProgressUpdate(value);
dialog.setMessage(waitMsg + value[0]);
txtMsg.append("\nworking..." + value[0]);
}
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}// AsyncTask
}// MainActivity
11
Concurrency Control
Example: Using the AsyncTask Class
Comments
1. The MainActivity instantiates our AsyncTask passing dummy parameters.
2. VerySlowTask sets a ProgressDialog box to keep the user aware of the
slow job. The box is defined as not cancellable, so touches on the UI will
not dismiss it (as it would do otherwise).
3. doInBackground accepts the parameters supplied by the .execute(…)
method. It fakes slow progress by sleeping various cycles of 10 seconds
each. After awaking it asks the onProgressUpdate() method to refresh
the ProgressDialog box as well as the user’s UI.
4. The onProgressUpdate() method receives one argument coming from
the busy background method (observe it is defined to accept multiple
input arguments). The arriving argument is reported in the UI’s textbox
and the dialog box.
5. The OnPostExecute() method performs house-cleaning, in our case it
dismisses the dialog box and adds a “Done” message on the UI.
12
B. HTTP Connection
Android Networking
Network Prerequisites
14
Android Networking
Protocols
15
Android Networking
HTTP
16
Android Networking
HTTP
17
Android Networking
The URL class
18
Android Networking
The URL class
19
Android Networking
Opening a connection
20
Android Networking
Opening a connection
21
Android Networking
Opening a connection
22
Android Networking
Sending GET request
URL url = new URL("http://httpbin.org/get");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Log.v("TAG", response.toString()); 23
Android Networking
Download file
URL url = new URL(" https://file-examples.com/wp-
content/uploads/2017/11/file_example_MP3_1MG.mp3");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
outputStream.close();
inputStream.close();
24
Android Networking
Sending POST request
URL url = new URL("http://httpbin.org/post");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//print result
Log.v("TAG", response.toString()); 25
Android Networking
3rd party libraries
Http Client:
- Volley https://github.com/google/volley
- OKHttp http://square.github.io/okhttp/
- Retrofit http://square.github.io/retrofit/
Image Loader:
- Picasso http://square.github.io/picasso/
- Universal Image Loader
https://github.com/nostra13/Android-Universal-
Image-Loader
26
C. Parsing JSON
Parsing JSON
What is JSON
28
Parsing JSON
JSON syntax
29
Parsing JSON
JSON values
31
Parsing JSON
Parsing JSON string
32
Parsing JSON
Parsing JSON string – Retrieving data
33
Parsing JSON
Example: Parsing JSON data from URL
▪ Steps:
▪ Implement a class extended from AsyncTask to get data in
background
▪ Implement GET request by using URLConnection
▪ Parse JSON by using JSONArray and JSONObject classes
▪ Show data using ListView
34
Serialize object to JSON
Convert JAVA object to JSON string
35
D. Working with
Socket class
Working with Socket class
Setup a client socket
String serverIP = "192.168.0.167";
int serverPort = 9000;
int timeOut = 5000;
37
Working with Socket class
Receive data from server
String result = "";
byte buffer[] = new byte[1024];
while (client.isConnected() && !client.isClosed()) {
38
Working with Socket class
Send data to server
String data = "Hello server";
OutputStreamWriter writer = new
OutputStreamWriter(client.getOutputStream());
writer.write(data);
writer.flush();
// Không đóng output stream để tránh client bị đóng
39