Network Presentation

Agenda

  • Asynchronous operations
  • Retrieve data over HTTP
  • Parsing HTML and JSON

Android Network APIs

Network Communication

  • Requires permission
  • AndroidManifest.xml
    <uses-permission android:name="android.permission.INTERNET" />
    
  • Never execute network requests on the main thread

Asynchronous operations

  • All event handlers are called on one single thread
    • User interface is non-responsive while executing
  • Asynchronous calls
    • Executed in the backround on its own thread
    • User interface is responsive
    • Event handlers can be called in parallell
    • Not allowed to access/update views from background thread

AsyncTask helper class

  • Usage
    • Create object with types defining
      • Input type
      • Progress type
      • Result type
    • Implement methods
      • doInBackground - main code, on background thread
      • onPreExecute - before doInBackground, on UI thread
      • onPostExecute - after doInBackground, on UI thread
      • onProgressUpdate - when publishProgess called from doInBackground

AsyncTask Example

  • Usage - only necessary to define the methods you need
    new AsyncTask<Void, Void, String>() {
      @Override
      protected String doInBackground(Void... voids) {
          // This runs on a background thread
          return "Some result of the async operation";
      }
    
      @Override
      protected void onPostExecute(String result) {
        // This runs on UI thread
        // result is whatever was returned from doInBackground above
        // Can update View objects
      }
    }.execute();
    

Fetch contents of a web page

  • Create URL object and read contents into StringBuilder
    URL src = new URL("http://www.mobileapplab.se");
    HttpURLConnection conn = (HttpURLConnection)src.openConnection();
    InputStreamReader input = new InputStreamReader(conn.getInputStream(), 
        "utf-8");
    StringBuilder output = new StringBuilder();
    char[] buffer = new char[4096];
    int len;
    while ((len = input.read(buffer, 0, buffer.length)) > 0) {
        output.append(buffer, 0, len);
    }
    input.close();
    conn.disconnect();
    String result = output.toString();
    

Parsing HTML

  • Jsoup library
    • Slow to parse, but can select elements using jQuery selector syntax
  • String handling
    • Very fast, but fragile and difficult to parse using only string matching
  • Regular expressions
    • Can help with the string handling if source is difficult to match exactly

Java string methods

  • indexOf
    • Searches for a substring within a string
    • Optional argument where to start the search
    • Returns found position, or -1 if not found
  • substring
    • Returns part of a string
    • First position of substring to return
    • First position of substring NOT to return

Parsing HTML with string methods

  • Assume HTML has been fetched, extract multiple occurences
    int found = html.indexOf("currencyRow"); // Find row with CSS class
    while (found >= 0) {
      found = html.indexOf("<span", found); // Find inner SPAN tag
      found = html.indexOf(">", found); // Find end of SPAN tag
      int foundEnd = html.indexOf("<", found); // Find beginning of next tag
      String part = html.substring(found + 1, foundEnd); // Extract relevant text
      found = html.indexOf("currencyRow", found); // Next row
    }
    

Call a web API

  • Structured data using an API
  • No need to parse HTML
  • Documented ways of retrieving and manipulating data
  • REST
    • Definition of how the URL maps to data objects
    • HTTP methods (verbs) for different operations
  • Data formats
    • XML
    • JSON

JSON

  • Great support in JavaScript
  • Contains
    • Arrays
    • Objects with properties
    • Values
      • Strings
      • Numbers
      • Booleans
  • JSON in text
    [
      { "name": "Adam", "age": 55 }, 
      { "name": "Betty", "age": 28 }
    ]
    

Parsing JSON in Java

  • Parse retrieved text as JSON and convert to objects
    JSONArray items = new JSONArray(data);
    for (int i = 0; i < items.size(); i++) {
      JSONObject item = items.getJSONObject(i);
      String name = item.getString("name");
      int age = item.getInt("age");
    }
    

Some open APIs

Downloading image to Drawable

  • Decode downloaded data as image
    URL url = new URL("http://site.com/image.png");
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.connect();
    InputStream input = conn.getInputStream();
    Bitmap image = BitmapFactory.decodeStream(input);
    input.close();
    BitmapDrawable drawable = new BitmapDrawable(image);