Networking Android Club 2015. Networking AsyncTask HttpUrlConnection JSON Parser.
-
Upload
julianna-carroll -
Category
Documents
-
view
221 -
download
0
Transcript of Networking Android Club 2015. Networking AsyncTask HttpUrlConnection JSON Parser.
Networking
Android Club 2015
Networking
• AsyncTask• HttpUrlConnection• JSON Parser
Thread
• UI thread• Background thread
AsyncTask
• Helps us to manage process of backgroud thread
• Started from UI thread
AsyncTask: 3 parameters
• 1. Params• 2. Progess• 3. Result
AsyncTask: example
• TimeUnit.SECONDS.sleep(10);
AsyncTask: practice
• Create public static ProgressDialog in Activity
• Create AsyncTask• onPreExecute: set message to dialog• onPreExecute: show progress dialog• onPostExecute: dismiss dialog
AsyncTask: pass data
• HttpTask task = new HttpTask();task.execute(3);
• TimeUnit.SECONDS.sleep(params[0]);
Pass data: practice
• Change previous code so that it should wait twice amount of time
• If you pass 3, it should wait 6 seconds• If 10, then 20
Networking: easiest way
1. Add permission: INTERNET2. Create AsyncTask3. Create HttpUrlConnection4. Convert InputStream to String5. Update UI6. Start from UI
Step 1: Add permission
• Open AndroidManifest.xml• Add this permission: <uses-
permission android:name="android.permission.INTERNET"/>
Step 2: Create AsynkTask
public class HttpTask extends AsyncTask<String, String, String> {
@Override protected String doInBackground(String... params) { return null; }
@Override protected void onPostExecute(String s) {
}
}
Step 3: HttpUrlConnection
• URL url = new URL(params[0]);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.connect();
Step 4: InputString to String
• InputStream stream = connection.getInputStream();InputStreamReader isReader = new InputStreamReader(stream );BufferedReader buffer = new BufferedReader(isReader );StringBuilder content = new StringBuilder();String line;while ((line = buffer.readLine()) != null) { content.append(line);}
Step 5: Update UI
• MainActivity.tvData.setText(s);
Step 6: Start from UI
• HttpTask task = new HttpTask();String url = "http://jsonip.com";task.execute(url);
HttpUrlConnection: practice
http://www.telize.com/geoip?callback=YOUR_IP
1. Create new AsyncTask2. Get content using HttpUrlConnection3. Convert content InputStream to String4. Update UI5. Pass that URL to AsyncTask
Parsing JSON: example
• JSONObject object = new JSONObject(s);String ip = object.getString("ip");MainActivity.tvData.setText("My ip address is "+ip);
Parsing JSON: practice
• http://www.telize.com/geoip?callback=YOUR_IP
• Show latitude• Show longitude• Show ISP• Show country
Homework 1: Forecast.IO
• developer.forecast.io
Homework 2: Football-api.com
• http://football-api.com• Demo - EPL• Free• English Premier League• Access limit: 1000 requests per hour• Access from 1 IP address
Homework 3: Your own API
• Create your own API• For example: calculator
for communal services