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: INTERNET 2.Create AsyncTask 3. Create HttpUrlConnection 4. Convert InputStream to String 5. Update UI 6. Start from UI
Step 1: Add permission Open AndroidManifest.xml Add this permission:
Step 2: Create AsynkTask public class HttpTask extends AsyncTask protected String doInBackground(String... params) { return null; 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 = " task.execute(url);
HttpUrlConnection: practice 1.Create new AsyncTask 2. Get content using HttpUrlConnection 3. Convert content InputStream to String 4. Update UI 5. 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 OUR_IP Show latitude Show longitude Show ISP Show country
Homework 1: Forecast.IO developer.forecast.io
Homework 2: 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