http and threads. download some code i’ve created an android project which gives examples of...

70
HTTP and Threads

Upload: nathan-morris-sanders

Post on 25-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP and Threads

Page 2: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Download some code

• I’ve created an Android Project which gives examples of everything covered in this lecture.

• Download code here.

Page 3: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Getting Data from the Web

• Believe it or not, Android apps are able to pull data from the web.

• Developers can download bitmaps and text and use that data directly in their application.

Page 4: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

How to use HTTP with Android

1. Ask for permission

2. Make a connection

3. Use the data

Page 5: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Step 1: Ask for Permission

• An application’s Android Manifest specifies which permissions are needed in order for the application to run.

• For application wanting to access the internet, it must list that permission in its Manifest.

Page 6: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Step 1: Ask for Permission

• Open your project’s AndroidManifeset.xml

Add the following xml:<uses-permission android:name="android.permission.INTERNET"/>

Page 7: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Step 1: Ask for Permission<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidhttp" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.androidhttp.MainActivity" 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>

Page 8: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Permission

• When a user downloads an app from the Android Play Store, they’ll have to accept and agree to all permissions required by the app before it is installed.

• Usually users don’t read the small text and just agree, but it’s still good to know.

Page 9: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Don’t forget to ask

• If you fail to add the permission to your AndroidManifest.xml you will NOT get a runtime or compile time error.

• Your application will simply fail to connect to the internet.

Page 10: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Step 2: Make a connectionpublic Bitmap loadImageFromNetwork(String imgUrl) {

Bitmap img = null;URL url;try { //A uniform resource locator aka the place where the data is //located url = new URL(imgUrl); //Opens an HTTPUrlConnection and downloads the input stream into a //Bitmap img = BitmapFactory.decodeStream(url.openStream());} catch (MalformedURLException e) { Log.e("JMM", "URL is bad"); e.printStackTrace();} catch (IOException e) { Log.e("JMM", "Failed to decode Bitmap"); e.printStackTrace();}return img;

}

Page 11: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Using a URL to create a Bitmap url = new URL(imgUrl);

//Opens an HTTPUrlConnection and downloads the input stream into a //Bitmapimg = BitmapFactory.decodeStream(url.openStream());

Page 12: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Step 3: Use the datapublic Bitmap loadImageFromNetwork(String imgUrl) {

Bitmap img = null;URL url;try { //A uniform resource locator aka the place where the data is //located url = new URL(imgUrl); //Opens an HTTPUrlConnection and downloads the input stream into a //Bitmap img = BitmapFactory.decodeStream(url.openStream());} catch (MalformedURLException e) { Log.e("JMM", "URL is bad"); e.printStackTrace();} catch (IOException e) { Log.e("JMM", "Failed to decode Bitmap"); e.printStackTrace();}return img;

}

Page 13: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Full Code for Making a Connectionpublic Bitmap loadImageFromNetwork(String imgUrl) {

Bitmap img = null;URL url;try { //A uniform resource locator aka the place where the data is //located url = new URL(imgUrl); //Opens an HTTPUrlConnection and downloads the input stream into a //Bitmap img = BitmapFactory.decodeStream(url.openStream());} catch (MalformedURLException e) { Log.e("JMM", "URL is bad"); e.printStackTrace();} catch (IOException e) { Log.e("JMM", "Failed to decode Bitmap"); e.printStackTrace();}return img;

}

Page 14: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Convert Bitmap to DrawableBitmap img = loadImageFromNetwork("http://path-to-image/img.png");

//Convert bitmap to drawableDrawable d = new BitmapDrawable(getResources(), img);

Page 15: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Decode Bitmap from stream

• http://stackoverflow.com/a/5776903/1222232

Page 16: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

NetworkOnMainThreadException

• The exception that is thrown when an application attempts to perform a networking operation on its main thread.

Page 17: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Single Threaded

• When launching your Android application, a single system process with a single thread of execution is spawned.

• By default your app has 1 process and 1 thread.

Page 18: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

UI Thread

• That single thread has several names:– main application thread– main user interface thread– main thread– user interface thread

• Mostly known as the UI Thread

Page 19: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Why UI Thread

• This is the thread where the following occurs– Layout– Measuring– Drawing– Event handling– Other UI related logic

• A developer should use the UI Thread for UI

Page 20: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Blocking the UI Thread

• Anytime a long running operation takes place on the UI thread, UI execution is paused.

• While paused, your app can’t:– Handle Events– Draw– Layout– Measure

Page 21: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

UI Thread Execution

Handle Touch Events

MeasureLayoutDraw

UI Thread

Page 22: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

UI Thread Execution with HTTP Request

Handle Touch Events

MeasureLayoutDraw

UI Thread

Internet

Page 23: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

ANR (Activity Not Responding) Error

Happens when your UI Thread is paused/blocked too long.

Page 24: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Operations to avoid on UI Thread

• HTTP Request

• Database Querying

• File download/upload

• Image/Video Processing

Page 25: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

How to prevent ANR?

• Let the UI thread do UI logic to allow it to stay responsive and allow interaction with the user.

• Use a separate thread for all other things!

Page 26: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Threading in Android

• Android supports:– Threads– Thread pools– Executors

• If you need to update the user interface, your new thread will need to synchronize with the UI thread.

Page 27: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

2 ways to thread and synchronize

• Handler• AsyncTask

Page 28: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Handler

• A mechanism that allows a worker thread to communicate with the UI Thread in a thread-safe manner.

• Use a Handler to send and process– Messages (a data message)– Runnables (executable code)

Page 29: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask

• Allows you to perform asynchronous work on the UI Thread

• Performs blocking operations on the worker thread

• Working thread then publishes results to UI Thread.

Page 30: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTasks are Easier Than Handlers

• AsyncTasks were designed as a helper class around Thread and Handler

• You don’t have to personally handle– Threads– Handlers– Runnables

Page 31: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask basics

1. Create a class that subclasses AsyncTask

2. Specify code to run on the worker thread

3. Specify code to update your UI

Page 32: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

UI Thread Execution with AsyncTask

Handle Touch Events

MeasureLayoutDraw

UI Thread

Spawn Thread Do Time Consuming Operation

Synchronize with UI Threadwith results

Page 33: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask Examplepublic void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png");}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); }}

Page 34: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

1. Subclass AsyncTaskpublic void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png");}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); }}

1

Page 35: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

2. Specify code for worker threadpublic void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png");}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); }}

2

Page 36: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

3. Specify code to update UI public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png");}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); }}

3

Page 37: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

doInBackground()

• Triggered by calling the AsyncTask’s execute() method.

• Execution takes places on a worker thread

• The result of this method is sent to onPostExecute()

Page 38: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

onPostExecute()

• Invoked on the UI thread

• Takes the result of the operation computed by doInBackground().

• Information passed into this method is mostly used to update the UI.

Page 39: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask Parameters extends AsyncTask<Boolean, Point, MotionEvent>

• The three types used are:1. Params, the type of parameter sent to the task upon execution.

2. Progress, the type of progress units published during the background execution.

3. Result, the type of result of the background computation.

Page 40: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask Parameters

• Each AsyncTask parameters can be any generic type

• Use whichever data type fits your use case.

• Not all parameters need to be used. To mark a parameters as unused, use the type Void.

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Page 41: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

AsyncTask LifeCycle

• When an AsyncTask is executed, it goes through 4 steps:1. onPreExecute()2. doInBackground(Params…)3. onProgressUpdate(Progress…)4. onPostExecute(Result…)

Page 42: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

onPreExecute()

• Invoked on the UI Thread immediately after execute() is called.

• Use this method to setup the task, show a progress bar in the user interface, etc.

Page 43: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

doInBackground(Params…)

• Performs background computation.

• Use this to publishProgress(Progress…) to publish one or more units of progress to the UI Thread.

Page 44: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

onProgressUpdated(Progress…)

• Invoked on the UI thread after a call to publishProgress().

• Used to display any form of progress in the User Interface while background computation is taking place.

• Use this to animate a progress bar or show logs in a text field.

Page 45: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

onPostExecute(Result)

• Invoked on the UI thread after doInBackground() completes.

Page 46: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Use cases for AsyncTasks

• Create an AsyncTask to load an image contained in a list item view.

• Create an AsyncTask to query the Database

• Grabbing JSON from the web

Page 47: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP Request

1. Ask for permission in AndroidManifest!

2. Make use of HttpURLConnection

3. GET, PUT, DELETE, and POST methods supported

4. Use HttpResponse for server response

Page 48: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP GetURL requestURL = new URL(“http://path_to_resource.html”);connection = (HttpURLConnection) requestURL.openConnection();connection.setReadTimeout(10000); //This is configurable to your likingconnection.setConnectTimeout(15000); //This is configurable to your liking

final int statusCode = connection.getResponseCode();

if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {Log.d("JMM", "You're not authorized to access the requested resource. So bail...");

} else if (statusCode != HttpURLConnection.HTTP_OK) {Log.d("JMM", "The request failed with status code: " + statusCode

+ ". Use the status code to debug this problem.");} else {

Log.d("JMM", “The request was successful!!!“);//Add code here to process the request

} 1. Create a URL which points to the resource you want to get.2. Use the URL and open a connection3. Setup the connection’s read and connection timeout

Page 49: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP GetURL requestURL = new URL(“http://path_to_resource.html”);connection = (HttpURLConnection) requestURL.openConnection();connection.setReadTimeout(10000); //This is configurable to your likingconnection.setConnectTimeout(15000); //This is configurable to your liking

final int statusCode = connection.getResponseCode();

if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {Log.d("JMM", "You're not authorized to access the requested resource. So bail...");

} else if (statusCode != HttpURLConnection.HTTP_OK) {Log.d("JMM", "The request failed with status code: " + statusCode

+ ". Use the status code to debug this problem.");} else {

Log.d("JMM", “The request was successful!!!“);//Add code here to process the request

} 1. getResponseCode() returns the response code given by the server:A. HTTP_OK 200 : Request was successfulB. HTTP_NOT_FOUND 404 : The resource was not foundC. Etc.

Page 50: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP GetURL requestURL = new URL(“http://path_to_resource.html”);connection = (HttpURLConnection) requestURL.openConnection();connection.setReadTimeout(10000); //This is configurable to your likingconnection.setConnectTimeout(15000); //This is configurable to your liking

final int statusCode = connection.getResponseCode();

if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {Log.d("JMM", "You're not authorized to access the requested resource. So bail...");

} else if (statusCode != HttpURLConnection.HTTP_OK) {Log.d("JMM", "The request failed with status code: " + statusCode

+ ". Use the status code to debug this problem.");} else {

Log.d("JMM", “The request was successful!!!“);//Add code here to process the request

} 1. Use the statusCode to figure out how to handle the request. HTTP_OK or 200 means it was successful. If we have a successful request we can use the connection to fetch the data we’re interested in.

Page 51: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Extracting the data from the HTTP Request

//This connection variable comes from the previous HTTP Get code.InputStream stream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream));StringBuilder sb = new StringBuilder();String line = reader.readLine();while (line != null) { sb.append(line + "\n"); line = reader.readLine();}String result = sb.toString(); //This holds the response data we want

Page 52: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

HTTP Post

• Similar to HTTP Get

• We just need to do a little more configuration

Page 53: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

Page 54: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

Exactly the same configuration as the GET request.

Page 55: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

We need to specify it’s a POST request.

Page 56: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

Using setRequestProperty() we can specifiy additional HTTP Headers in our request.

Page 57: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

We’re sending JSON, so we need some JSON. Here I’m getting a JSONObject which contains a bunch of JSON data.

Page 58: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

1. Convert the JSON Object to a String2. Convert the String to Bytes so we can write to a

stream for the HTTP Request3. Flush the stream. This means we’ve written

everything and we done.4. Connect to the server and send the data.

Page 59: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

URL url = new URL("http://path_to_where_you_want_to_post_the_json");HttpURLConnection connection;connection = (HttpURLConnection) url.openConnection();connection.setReadTimeout(10000);connection.setConnectTimeout(15000);

//Need to specify we’re sending a POST request. HttpURLConnection is set a GET by default.connection.setRequestMethod("POST");

//We're sending JSON so specify that as the content-type for the HTTP messageconnection.setRequestProperty("Content-Type", "application/json");

//If the server supports JSON, ask for it to return a response in JSON formatconnection.setRequestProperty("Accept", "application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSONJSONObject person = getJSONPerson();//END CREATING OF JSON

//SEND THE JSONfinal String json = person.toString();connection.getOutputStream().write(json.getBytes());connection.getOutputStream().flush();connection.connect();//END SEND

final int statusCode = connection.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) { Log.d("JMM", "The request failed with status code: " + statusCode + ". Use the status code to debug this problem.");} else { InputStream in = new BufferedInputStream(connection.getInputStream()); String result = getResponseText(in); Log.d("JMM", result);}

Sending JSON with HTTP Post

If we care about a response, handle it just like the GET request.

Page 60: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

XML and JSON Parsing

• Not as easy as Javascript.

• Use the following for help:1. JSON in Android Tutorial2. Android JSON Parsing Tutorial3. Android XML Parsing Tutorial4. GSON – Java library to convert JSON to Java

Objects and vice versa.

Page 61: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

JSONObject and JSONArray

• Use these two classes to get and create JSON.

• Think of each class as a HashMap. They hold a collection of name value pairs.

Page 62: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

JSONObject

• A modifiable set of name/value mappings. Names are unique, non-null strings.

• Values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles or NULL.

• Values may not be null, NaNs, infinities, or of any type not listed here.

Page 63: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

How to get with JSONObjectString json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }";

Page 64: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Convert JSON string to JSONObjectString json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }";

JSONObject jsonObj = new JSONObject(json);

Create JSONObject so we can accessThe name/value pairs.

Page 65: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Convert JSON string to JSONObjectString json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }";

JSONObject jsonObj = new JSONObject(json); JSONObject jsonPerson = jsonObj.getJSONObject(“person”);person.name = jsonPerson.getString(“name”);person.age = jsonPerson.getInt(“age”);person.isMarried = jsonPerson.getBoolean(“married”);

Extract json values using the corresponding name pair

Page 66: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

JSONArray

• A dense indexed sequence of values.

• Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL.

• Values may not be NaNs, infinities, or of any type not listed here.

• JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject.

Page 67: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

String json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }";

JSONObject jsonObj = new JSONObject(json); JSONObject jsonPerson = jsonObj.getJSONObject(“person”);person.name = jsonPerson.getString(“name”);person.age = jsonPerson.getInt(“age”);person.isMarried = jsonPerson.getBoolean(“married”);JSONArray jsonProfessions = jsonPerson.getJSONArray(“profession”);

Since we have an array in our json, we need to create a JSONArray object to access the values inside the array.

Page 68: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

String json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }";

JSONObject jsonObj = new JSONObject(json); JSONObject jsonPerson = jsonObj.getJSONObject(“person”);person.name = jsonPerson.getString(“name”);person.age = jsonPerson.getInt(“age”);person.isMarried = jsonPerson.getBoolean(“married”);JSONArray jsonProfessions = jsonPerson.getJSONArray(“profession”);for (int i = 0; i < jsonProfessions.length(); i++) {

person.profession.add(jsonProfessions.getString(i));}

Iterate through the JSONArray like a normal array except you have to explicitly pick a type to get from the JSONArray.

Page 69: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Creating JSON in Android

• JSONObject and JSONArray both have put() methods that allow you to add data into each object.

• Just create a new JSONObject or JSONArray and start putting stuff in it.

Page 70: HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here

Additional Data Loading Techniques

• Android also provides Loaders for asynchronous data loading.

• They take a little more work, but the results are worth it.

• See documentation for details.