HTTP and Threads. 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.

Slides:



Advertisements
Similar presentations
Programming with Android: Network Operations
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
USING ANDROID WITH THE INTERNET. Slide 2 Network Prerequisites The following must be included so as to allow the device to connect to the network The.
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
Road Map Introduction to object oriented programming. Classes
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Programming with Android: Network Operations Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
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.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
JavaScript & jQuery the missing manual Chapter 11
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CS378 - Mobile Computing Web - WebView and Web Services.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Networking Android Club Networking AsyncTask HttpUrlConnection JSON Parser.
CS378 - Mobile Computing Web - WebView and Web Services.
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.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Chapter 8 Cookies And Security JavaScript, Third Edition.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Serialization. Serialization is the process of converting an object into an intermediate format that can be stored (e.g. in a file or transmitted across.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
MAKANI ANDROID APPLICATION Prepared by: Asma’ Hamayel Alaa Shaheen.
CS378 - Mobile Computing Responsiveness. An App Idea From Nifty Assignments Draw a picture use randomness Pick an equation at random Operators in the.
Android networking 1. Network programming with Android If your Android is connected to a WIFI, you can connect to servers using the usual Java API, like.
UNIT 30 네트워크 전송 2 로봇 SW 콘텐츠 교육원 조용수.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Server - Client Communication Getting data from server.
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
RESTful Web Services What is RESTful?
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming –TextField Action Listeners, JEditorPane action listeners, HTML in a JEditorPane,
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
David Sutton MOBILE INTERNET. OUTLINE  This week’s app – an RSS feed reader  Mobile internet considerations  Threads (recap)  RSS feeds  Using AsyncTask.
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Tools of the trade J SON, M AVEN, A PACHE COMMON Photo from
JQuery form submission CIS 136 Building Mobile Apps 1.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
HUJI Post PC Workshop 5 Files, Threading, and Web Services Sasha Goldshtein
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Small talk with the UI thread
WebView and Web Services
CS240: Advanced Programming Concepts
Lecture 6: Process, Thread, Task
CSE 154 Lecture 22: AJAX.
CS371m - Mobile Computing Responsiveness.
HTML5 AJAX & JSON APIs
Android Topics Asynchronous Callsbacks
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
Using threads for long running tasks.
Lecture 6: Process, Thread, Task
Android Threads Dimitar Ivanov Mobile Applications with Android
Presentation transcript:

HTTP and Threads

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 1.Ask for permission 2.Make a connection 3.Use the data

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 Permission Open your project’s AndroidManifeset.xml Add the following xml:

Step 1: Ask for Permission <manifest xmlns:android=" package="com.example.androidhttp" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" > <activity android:name="com.example.androidhttp.MainActivity" >

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 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 Bitmap img = null; URL url; try { //A uniform resource locator aka the place where the data is //located url = new URL(" content/uploads/2011/04/deadpool-team-up-887-cover-art.jpg"); //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(); } mImage.setImageBitmap(img);

Using a URL to create a Bitmap url = new URL(" content/uploads/2011/04/deadpool-team-up-887-cover-art.jpg"); //Opens an HTTPUrlConnection and downloads the input stream into a //Bitmap img = BitmapFactory.decodeStream(url.openStream());

Step 3: Use the data Bitmap img = null; URL url; try { //A uniform resource locator aka the place where the data is //located url = new URL(" content/uploads/2011/04/deadpool-team-up-887-cover-art.jpg"); //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(); } mImage.setImageBitmap(img);

Full Code for Making a Connection Bitmap img = null; URL url; try { //A uniform resource locator aka the place where the data is //located url = new URL(" content/uploads/2011/04/deadpool-team-up-887-cover-art.jpg"); //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(); } mImage.setImageBitmap(img);

Convert Bitmap to Drawable img = BitmapFactory.decodeStream(url.openStream()); Drawable d = new BitmapDrawable(img);

Decode Bitmap from stream

Your Turn! Create an Android application that uses a URL to create a Bitmap and place that Bitmap as the source of an ImageView.

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

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 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 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 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 Handle Touch Events Measure Layout Draw UI Thread

UI Thread Execution with HTTP Request Handle Touch Events Measure Layout Draw UI Thread Internet

ANR (Activity Not Responding) Error Happens when your UI Thread is paused/blocked too long.

Operations to avoid on UI Thread HTTP Request Database Querying File download/upload Image/Video Processing

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 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 Handler AsyncTask

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 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 were designed as a helper class around Thread and Handler You don’t have to personally handle – Threads – Handlers – Runnables

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

UI Thread Execution with AsyncTask Handle Touch Events Measure Layout Draw UI Thread Spawn Thread Do Time Consuming Operation Synchronize with UI Thread with results

AsyncTask Example public void onClick(View v) { new DownloadImageTask().execute(" } private class DownloadImageTask extends AsyncTask { /** 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. Subclass AsyncTask public void onClick(View v) { new DownloadImageTask().execute(" } private class DownloadImageTask extends AsyncTask { /** 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

2. Specify code for worker thread public void onClick(View v) { new DownloadImageTask().execute(" } private class DownloadImageTask extends AsyncTask { /** 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

3. Specify code to update UI public void onClick(View v) { new DownloadImageTask().execute(" } private class DownloadImageTask extends AsyncTask { /** 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

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()

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 extends AsyncTask 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.

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. private class MyTask extends 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 When an AsyncTask is executed, it goes through 4 steps: 1.onPreExecute() 2.doInBackground(Params…) 3.onProgressUpdate(Progress…) 4.onPostExecute(Result…)

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…) Performs background computation. Use this to publishProgress(Progress…) to publish one or more units of progress to the UI Thread.

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) Invoked on the UI thread after doInBackground() completes.

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 1.Ask for permission in AndroidManifest! 2.Make use of HttpClient 3.GET, PUT, DELETE, and POST methods supported 4.Use HttpResponse for server response

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpClient object is required for all HTTP Methods.

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Pass the url of the resource you want to GET into the HttpGet Object constructor.

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Execute the HTTP request and receive a response.

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Returns the message entity of the response.

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } If the Entity isn’t null then the response is valid. Get the String representation of the response.

HTTP Get HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (null != entity) { String result = EntityUtils.toString(entity); Log.d("CRR", result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Do whatever you want with the response.

Another way to HTTP Get try { URL url = new URL(" HttpURLConnection con = (HttpURLConnection) url.openConnection(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line + "\n"); line = reader.readLine(); } } catch (Exception e) { e.printStackTrace(); }

HTTP Put Similar to HTTP Get Need to create a list of name value pairs for parameters to send to server.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpClient object is required for all HTTP Methods. Same as GET example.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Create a HTTP Post and pass in the resource we’re posting to.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Create a List of NameValuePair objects to hold each parameter we’re sending as a part of our POST request.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Creating a BasicNameValuePair object to hold a name/value pair. Insert the BasicNameValuePair object into the NameValuePair list.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } UrlEncodedFormEntity is an entity composed of a list of url- encoded pairs. Useful for POST requests.

HTTP Put HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(“ List request = new ArrayList (); request.add(new BasicNameValuePair("fname", "Chris")); request.add(new BasicNameValuePair("lname", "Raley")); request.add(new BasicNameValuePair("id", " ")); Person person = new Person("Chris Raley", 17, false, new String[] {"Ice Cream Salesman" }); request.add(new BasicNameValuePair("json", person.toJSONString())); try { post.setEntity(new UrlEncodedFormEntity(request)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { String text = EntityUtils.toString(entity); Log.d("CRR", text); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Same as GET request.

XML and JSON Parsing Not as easy as Javascript. Use the following for help: 1.JSON in Android TutorialJSON in Android Tutorial 2.Android JSON Parsing TutorialAndroid JSON Parsing Tutorial 3.Android XML Parsing TutorialAndroid XML Parsing Tutorial 4.GSON – Java library to convert JSON to Java Objects and vice versa.GSON

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

Hello World JSON Example { “fname" : “bruce" } CSE All JSON data starts and ends with a curly brace 2.The curly brace is what encapsulates the data into an Object. 3.After all, JSON stands for Javascript Object Notation. Object

Hello World JSON Example { “fname" : “bruce" } CSE namevalue pair

Hello World JSON Example { “fname" : “bruce" } CSE namevalue pair The name portion of the pair must ALWAYS be a String.

Hello World JSON Example { “fname" : “bruce" } CSE valuename pair The value portion of the pair can be several different types.

Value types 1.numbers 2.booleans 3.Strings 4.null 5.arrays (ordered sequences of values) 6.objects (string-value mappings) composed of these values (or of other arrays and objects). CSE

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

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

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” : } CSE

JSON Example { "type": "document", "students": [ "tom", "sally", "joe" ], "class room": 112, "teach": "Hank McCoy“, “fulltime” : false } CSE

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

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 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.JSONObjectsJSONArraysNULL Values may not be null, NaNs, infinities, or of any type not listed here.NaNsinfinities

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

Convert JSON string to JSONObject String json = "{ "person": { "name": "Ted Mosby", "age": 32, "profession": [ "Architect", "Professor" ], "married": false } }"; JSONObject jsonObj = new JSONObject(json); Create JSONObject so we can access The name/value pairs.

Convert JSON string to JSONObject 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”); Extract json values using the corresponding name pair

JSONArray A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL.JSONObjectsJSONArraysNULL Values may not be NaNs, infinities, or of any type not listed here.NaNsinfinities JSONArray has the same type coercion behavior and optional/mandatory accessors as JSONObject.JSONObject

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.

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.

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.

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.documentation