Saturday, November 15, 2014

12a. Android: JSON OpenWeatherMap

In this tutorial we will implement basic weather OpenWeatherMap API using JSON (JavaScript Object Notation).
links:

API information:
http://openweathermap.org/api

JSON:
http://api.openweathermap.org/data/2.5/weather?q=Mundelein,IL

Image URL:
http://openweathermap.org/img/w/10d.png

JSON (pretty) formatter in TextWrangler editor (Mac)
http://ukitech.blogspot.com/2012/08/format-json-in-free-textwrangler.html

Example JSON data:

http://api.openweathermap.org/data/2.5/weather?q=Mundelein,IL
http://openweathermap.org/img/w/10d.png

{
  "base": "cmc stations",
  "clouds": {
    "all": 1
  },
  "cod": 200,
  "coord": {
    "lat": 42.27,
    "lon": -88
  },
  "dt": 1416040500,
  "id": 4903184,
  "main": {
    "humidity": 92,
    "pressure": 1027,
    "temp": 265.36,
    "temp_max": 268.15,
    "temp_min": 261.15
  },
  "name": "Mundelein",
  "sys": {
    "country": "United States of America",
    "id": 2981,
    "message": 0.0294,
    "sunrise": 1416055401,
    "sunset": 1416090602,
    "type": 1
  },
  "weather": [
    {
      "description": "sky is clear",
      "icon": "01n",
      "id": 800,
      "main": "Clear"
    }
  ],
  "wind": {
    "deg": 274.501,
    "speed": 4.54
  }
}

Step: Create a new Android module

  • File > New Module...
  • Android Application
  • Application Name: Weather Station
  • Module Name: appWeatherStationJson
  • Package Name: com.yourname.android.app.json.weather
  • Min SDK: 8
  • Target SDK: 19 (KitKat 4.4)
  • Compile with: 21
  • Java Lang: 6.0
  • Theme: Holo Light
  • Create Activity
  • Suport mode: Fragments
  • Suport mode: Action Bar


Next
  • Blank Activity
Next
  • MainActivity
  • activity_main
Finish


Step: add INTERNET permission

We need to add INTERNET permission since we will be accessing JSON over HTTP

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.chicagoandroid.android.app.json.weather">
    <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
        <activity
                android:name=".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>
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>