JSON Api

We ll demonstrate with open weather map API

If you are using an API, the download URL will be of specific structure, including an API key

String apicall = "http://api.openweathermap.org/data/2.5/weather?q=" + cityStr + "&appid=KEY";

To get weather data for city LONDON, we request the URL with API key,

https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22

{"coord":{"lon":-0.13,"lat":51.51},
"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],
"base":"stations",
"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},
"visibility":10000,
"wind":{"speed":4.1,"deg":80},
"clouds":{"all":90},
"dt":1485789600,
"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},
"id":2643743,
"name":"London",
"cod":200}

After downloading this data (just as we did from HTML source) and storing it in variable result, we can process it with JSONObject and perform the looping operations with JSON Array

//processing JSON data from json string
            try {
                JSONObject jsonObject = new JSONObject(result);

                //Getting a specific key: use the required key value from API
                String weatherInfo = jsonObject.getString("weather"); 
                Log.i("Content ",weatherInfo); // this is a string representing an array
                // "[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"},]"

                //looping through an array (not necessaily JSON items) represented as a string
                 //"[1,2,3]" can also be looped with JSON array
                JSONArray arr = new JSONArray(weatherInfo);

                for(int i=0; i< arr.length();i++){
                    JSONObject jsonPart = arr.getJSONObject(i);
                    Log.i("main",jsonPart.getString("main"));
                    Log.i("description",jsonPart.getString("description"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

JSON Array is useful when an array is represented as a string. Ie, to get the individual elements of "[1,2,3]",

JSONArray arr = new JSONArray(string);
    for(int i=0; i< arr.length();i++)
        arr.getInt(i); //use the get method corresponding to datatype needed

Hiding android keyboard

//the input that caused keyboard to pop
        EditText city = (EditText) findViewById(R.id.editText);
        //hide keyboard with input manager
        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(city.getWindowToken(),0);

Encoding URLS

When we join strings to API URL, we have to be careful with spaces by encoding it properly

//encode city name to deal with spaces (eg san francisco)
        try {
            cityStr = URLEncoder.encode(cityStr,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

Example project:

Weather