Http and threads
This presentation is the property of its rightful owner.
Sponsored Links
1 / 85

HTTP and Threads PowerPoint PPT Presentation


  • 39 Views
  • Uploaded on
  • Presentation posted in: General

HTTP and Threads. Download some code. I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here . Getting Data from the Web. Believe it or not, Android apps are able to pull data from the web.

Download Presentation

HTTP and Threads

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Http and threads

HTTP and Threads


Download some code

Download some code

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

  • Download code here.


Getting data from the web

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.


How to use http with android

How to use HTTP with Android

  • Ask for permission

  • Make a connection

  • Use the data


Step 1 ask for permission

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.


Step 1 ask for permission1

Step 1: Ask for Permission

  • Open your project’s AndroidManifeset.xml

    Add the following xml:

    <uses-permission android:name="android.permission.INTERNET"/>


Step 1 ask for permission2

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>


Permission

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.


Don t forget to ask

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.


Step 2 make a connection

Step 2: Make a connection

public 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("CRR", "URL is bad");

e.printStackTrace();

}catch(IOException e){

Log.e("CRR", "Failed to decode Bitmap");

e.printStackTrace();

}

return img;

}


Using a url to create a bitmap

Using a URL to create a Bitmap

url=newURL(imgUrl);

//Opens an HTTPUrlConnection and downloads the input stream into a //Bitmap

img=BitmapFactory.decodeStream(url.openStream());


Step 3 use the data

Step 3: Use the data

public 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("CRR", "URL is bad");

e.printStackTrace();

}catch(IOException e){

Log.e("CRR", "Failed to decode Bitmap");

e.printStackTrace();

}

return img;

}


Full code for making a connection

Full Code for Making a Connection

public Bitmap loadImageFromNetwork(String imgUrl) {

Bitmap img=null;

URL url;

try{

//A uniform resource locator aka the place where the data is

//located

url=newURL(imgUrl);

//Opens an HTTPUrlConnection and downloads the input stream into a

//Bitmap

img=BitmapFactory.decodeStream(url.openStream());

}catch(MalformedURLException e){

Log.e("CRR","URL is bad");

e.printStackTrace();

}catch(IOException e){

Log.e("CRR","Failed to decode Bitmap");

e.printStackTrace();

}

return img;

}


Convert bitmap to drawable

Convert Bitmap to Drawable

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

//Convert bitmap to drawable

Drawable d = newBitmapDrawable(getResources(), img);


Decode bitmap from stream

Decode Bitmap from stream

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


Your turn

Your Turn!

  • Create a method that uses a URL to create a Bitmap and place that Bitmap as the background of the CanvasView in your PaintApp.

    //Convert bitmap to drawable

    Drawable d = newBitmapDrawable(getResources(), img);

    //Set drawable to a View’s background (deprecated)

    mCanvas.setBackgroundDrawable(d);

    //Set drawable to a View’s background. Use with newer API versions

    mCanvas.setBackground(d);


Networkonmainthreadexception

NetworkOnMainThreadException

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


Single threaded

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.


Ui thread

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


Why ui thread

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


Blocking the ui thread

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


Ui thread execution

UI Thread Execution

Handle Touch Events

Measure

Layout

Draw

UI Thread


Ui thread execution with http request

UI Thread Execution with HTTP Request

Handle Touch Events

Internet

Measure

Layout

Draw

UI Thread


Anr activity not responding error

ANR (Activity Not Responding) Error

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


Operations to avoid on ui thread

Operations to avoid on UI Thread

  • HTTP Request

  • Database Querying

  • File download/upload

  • Image/Video Processing


How to prevent anr

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!


Threading in android

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.


2 ways to thread and synchronize

2 ways to thread and synchronize

  • Handler

  • AsyncTask


Handler

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)


Asynctask

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.


Asynctasks are easier than handlers

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


Asynctask basics

AsyncTask basics

  • Create a class that subclasses AsyncTask

  • Specify code to run on the worker thread

  • Specify code to update your UI


Ui thread execution with asynctask

UI Thread Execution with AsyncTask

Spawn Thread

Do Time Consuming Operation

Handle Touch Events

Synchronize with UI Thread

with results

Measure

Layout

Draw

UI Thread


Asynctask example

AsyncTask Example

publicvoidonClick(View v){

newDownloadImageTask().execute("http://example.com/image.png");

}

privateclassDownloadImageTaskextendsAsyncTask<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){

returnloadImageFromNetwork(urls[0]);

}

/** The system calls this to perform work in the UI thread and delivers

* the result from doInBackground() */

protectedvoidonPostExecute(Bitmap result){

mImageView.setImageBitmap(result);

}

}


1 subclass asynctask

1. Subclass AsyncTask

publicvoidonClick(View v){

newDownloadImageTask().execute("http://example.com/image.png");

}

privateclassDownloadImageTaskextendsAsyncTask<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){

returnloadImageFromNetwork(urls[0]);

}

/** The system calls this to perform work in the UI thread and delivers

* the result from doInBackground() */

protectedvoidonPostExecute(Bitmap result){

mImageView.setImageBitmap(result);

}

}

1


2 specify code for worker thread

2. Specify code for worker thread

publicvoidonClick(View v){

newDownloadImageTask().execute("http://example.com/image.png");

}

privateclassDownloadImageTaskextendsAsyncTask<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){

returnloadImageFromNetwork(urls[0]);

}

/** The system calls this to perform work in the UI thread and delivers

* the result from doInBackground() */

protectedvoidonPostExecute(Bitmap result){

mImageView.setImageBitmap(result);

}

}

2


3 specify code to update ui

3. Specify code to update UI

publicvoidonClick(View v){

newDownloadImageTask().execute("http://example.com/image.png");

}

privateclassDownloadImageTaskextendsAsyncTask<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){

returnloadImageFromNetwork(urls[0]);

}

/** The system calls this to perform work in the UI thread and delivers

* the result from doInBackground() */

protectedvoidonPostExecute(Bitmap result){

mImageView.setImageBitmap(result);

}

}

3


Doinbackground

doInBackground()

  • Triggered by calling the AsyncTask’sexecute() method.

  • Execution takes places on a worker thread

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


Onpostexecute

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.


Asynctask parameters

AsyncTask Parameters

extendsAsyncTask<Boolean, Point,MotionEvent>

  • The three types used are:

    • Params, the type of parameter sent to the task upon execution.

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

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


Asynctask parameters1

AsyncTask Parameters

  • Each AysncTask 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.

    privateclassMyTaskextendsAsyncTask<Void, Void, Void>{...}


Your turn with asynctask

Your turn with AsyncTask

  • Create a AsyncTask that uses a String to download an image from the internet and then uses the downloaded image for an ImageView located in the UI.

    URL url = new URL(url_path);

    BitmapFactory.decodeStream(url.openStream());


Asynctask lifecycle

AsyncTaskLifeCycle

  • When an AsyncTask is executed, it goes through 4 steps:

    • onPreExecute()

    • doInBackground(Params…)

    • onProgressUpdate(Progress…)

    • onPostExecute(Result…)


Onpreexecute

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.


Doinbackground params

doInBackground(Params…)

  • Performs background computation.

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


Onprogressupdated progress

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.


Onpostexecute result

onPostExecute(Result)

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


Use cases for asynctasks

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


Http request

HTTP Request

  • Ask for permission in AndroidManifest!

  • Make use of HttpURLConnection

  • GET, PUT, DELETE, and POST methods supported

  • Use HttpResponse for server response


Http get

HTTP Get

URL requestURL = new URL(“http://path_to_resource.html”);

connection = (HttpURLConnection) requestURL.openConnection();

connection.setReadTimeout(10000); //This is configurable to your liking

connection.setConnectTimeout(15000); //This is configurable to your liking

finalintstatusCode = connection.getResponseCode();

if(statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {

Log.d("CRR", "You're not authorized to access the requested resource. So bail...");

} elseif (statusCode != HttpURLConnection.HTTP_OK) {

Log.d("CRR", "The request failed with status code: " + statusCode

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

} else {

Log.d("CRR", “The request was successful!!!“);

//Add code here to process the request

}

Create a URL which points to the resource you want to get.

Use the URL and open a connection

Setup the connection’s read and connection timeout


Http get1

HTTP Get

URL requestURL = new URL(“http://path_to_resource.html”);

connection = (HttpURLConnection) requestURL.openConnection();

connection.setReadTimeout(10000); //This is configurable to your liking

connection.setConnectTimeout(15000); //This is configurable to your liking

finalintstatusCode = connection.getResponseCode();

if(statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {

Log.d("CRR", "You're not authorized to access the requested resource. So bail...");

} elseif (statusCode != HttpURLConnection.HTTP_OK) {

Log.d("CRR", "The request failed with status code: " + statusCode

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

} else {

Log.d("CRR", “The request was successful!!!“);

//Add code here to process the request

}

  • getResponseCode() returns the response code given by the server:

    • HTTP_OK  200 : Request was successful

    • HTTP_NOT_FOUND  404 : The resource was not found

    • Etc.


Http get2

HTTP Get

URL requestURL = new URL(“http://path_to_resource.html”);

connection = (HttpURLConnection) requestURL.openConnection();

connection.setReadTimeout(10000); //This is configurable to your liking

connection.setConnectTimeout(15000); //This is configurable to your liking

finalintstatusCode = connection.getResponseCode();

if(statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {

Log.d("CRR", "You're not authorized to access the requested resource. So bail...");

} elseif (statusCode != HttpURLConnection.HTTP_OK) {

Log.d("CRR", "The request failed with status code: " + statusCode

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

} else {

Log.d("CRR", “The request was successful!!!“);

//Add code here to process the request

}

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.


Extracting the data from the http request

Extracting the data from the HTTP Request

  • There are 2 approaches

    • The traditional approach

    • A new approach that I just found and haven’t tested thoroughly


Traditional approach

Traditional Approach

//This connection variable comes from the previous HTTP Get code.

InputStream stream = connection.getInputStream();

BufferedReaderreader = newBufferedReader(newInputStreamReader(stream));

StringBuildersb = newStringBuilder();

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


New not well tested approach

New “not well tested” Approach

//This connection variable comes from the previous HTTP Get code.

InputStream stream = connection.getInputStream();

Scanner scanner = new Scanner(stream);

//The variable resultholds the response data we want

final String result = scanner.useDelimiter("\\A").next();

scanner.close();


Http post

HTTP Post

  • Similar to HTTP Get

  • We just need to do a little more configuration


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

Exactly the same configuration as the GET request.


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

We need to specify it’s a POST request.


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

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


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

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


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

Convert the JSON Object to a String

Convert the String to Bytes so we can write to a stream for the HTTP Request

Flush the stream. This means we’ve written everything and we done.

Connect to the server and send the data.


Http and threads

Sending JSON with HTTP Post

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 message

connection.setRequestProperty("Content-Type","application/json");

//If the server supports JSON, ask for it to return a response in JSON format

connection.setRequestProperty("Accept","application/json");

//CREATE A JSON OBJECT TO SEND: This is code that generate JSON

JSONObject person =getJSONPerson();

//END CREATING OF JSON

//SEND THE JSON

final String json=person.toString();

connection.getOutputStream().write(json.getBytes());

connection.getOutputStream().flush();

connection.connect();

//END SEND

finalintstatusCode=connection.getResponseCode();

if(statusCode!=HttpURLConnection.HTTP_OK){

Log.d("CRR","The request failed with status code: "+statusCode+". Use the status code to debug this problem.");

}else{

InputStream in =newBufferedInputStream(connection.getInputStream());

String result =getResponseText(in);

Log.d("CRR", result);

}

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


Xml and json parsing

XML and JSON Parsing

  • Not as easy as Javascript.

  • Use the following for help:

    • JSON in Android Tutorial

    • Android JSON Parsing Tutorial

    • Android XML Parsing Tutorial

    • GSON – Java library to convert JSON to Java Objects and vice versa.


Json quick facts

JSON Quick facts

  • JSON – javascript object notation

  • JSON is a collection of name value pairs

  • Is a data-exchange format.

  • Closely resembles Javascript syntax.

  • Can parse JSON into a JS object.

CSE 3345


Hello world json example

Hello World JSON Example

{ “fname" : “bruce" }

Object

All JSON data starts and ends with a curly brace

The curly brace is what encapsulates the data into an Object.

After all, JSON stands for Javascript ObjectNotation.

CSE 3345


Hello world json example1

Hello World JSON Example

{ “fname" : “bruce" }

name

value

pair

CSE 3345


Hello world json example2

Hello World JSON Example

{ “fname" : “bruce" }

name

value

pair

The name portion of the pairmust ALWAYS be a String.

CSE 3345


Hello world json example3

Hello World JSON Example

{ “fname" : “bruce" }

name

value

pair

The value portion of the paircan be several different types.

CSE 3345


Value types

Value types

  • numbers

  • booleans

  • Strings

  • null

  • arrays (ordered sequences of values)

  • objects (string-value mappings) composed of these values (or of other arrays and objects).

CSE 3345


Json example

JSON Example

{

"age": 21,

"name": "Sandra Dee",

"alive": false

}

  • It is necessary to separate each pair with a comma. Your JSON will be invalid if you don’t.

CSE 3345


Json array example

JSON Array Example

{

"scores": [ 100, 89, 99, 75]

}

  • An array is an ordered collection of values.

  • An array begins with a [(left bracket) and ends with ](right bracket).

  • Values are separated by a ,(comma).

CSE 3345


Object in json

Object in JSON

  • Just like typical Object-Oriented Programming, you can have objects inside of objects

    {

    “pizza” : {

    “name” : “The Heart Attack”,

    “id” : 20121,

    “toppings” : [ “Pepperoni”, “Cheese”, “Chili” ],

    “price” : 19.99

    }

    }

CSE 3345


Json example1

JSON Example

{

"type":"document",

"students":[

"tom",

"sally",

"joe"

],

"class room":112,

"teach":"Hank McCoy“,

“fulltime” : false

}

CSE 3345


Dissect the json data

Dissect the JSON Data

{

"type":"document",

"students":[

{

"name":"tom",

"age":18

},

{

"name":"sally",

"age":18

},

{

"name":"joe",

"age":17

}

],

"class room":112,

"teacher":"Hank McCoy",

"fulltime":false

}

CSE 3345


Jsonobject and jsonarray

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.


Jsonobject

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.


How to get with jsonobject

How to get with JSONObject

String json= "{

"person":{

"name":"Ted Mosby",

"age":32,

"profession":["Architect","Professor"],

"married":false}

}";


Convert json string to jsonobject

Convert JSON string to JSONObject

String json= "{

"person":{

"name":"Ted Mosby",

"age":32,

"profession":["Architect","Professor"],

"married":false}

}";

JSONObjectjsonObj=newJSONObject(json);

Create JSONObject so we can access

The name/value pairs.


Convert json string to jsonobject1

Convert JSON string to JSONObject

String json= "{

"person":{

"name":"Ted Mosby",

"age":32,

"profession":["Architect","Professor"],

"married":false}

}";

JSONObjectjsonObj=newJSONObject(json);

JSONObjectjsonPerson = 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


Jsonarray

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.


Http and threads

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

String json= "{

"person":{

"name":"Ted Mosby",

"age":32,

"profession":["Architect","Professor"],

"married":false}

}";

JSONObjectjsonObj=newJSONObject(json);

JSONObjectjsonPerson = jsonObj.getJSONObject(“person”);

person.name = jsonPerson.getString(“name”);

person.age = jsonPerson.getInt(“age”);

person.isMarried = jsonPerson.getBoolean(“married”);

JSONArrayjsonProfessions = jsonPerson.getJSONArray(“profession”);


Http and threads

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

String json= "{

"person":{

"name":"Ted Mosby",

"age":32,

"profession":["Architect","Professor"],

"married":false}

}";

JSONObjectjsonObj=newJSONObject(json);

JSONObjectjsonPerson = jsonObj.getJSONObject(“person”);

person.name = jsonPerson.getString(“name”);

person.age = jsonPerson.getInt(“age”);

person.isMarried = jsonPerson.getBoolean(“married”);

JSONArrayjsonProfessions = jsonPerson.getJSONArray(“profession”);

for (inti = 0; i < jsonProfessions.length(); i++) {

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

}


Creating json in android

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 puttingstuff in it.


Additional data loading techniques

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.


  • Login