VIDEO OpenWeatherMap s weather API is simple, clear and free. This Android example show how access current weather data using OpenWeatherMaps weather API; for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations. Data is available in JSON, XML, or HTML format. This example use JSON.
To access the API you need to sign up for an API key, this example use the demo API Key (appid in the query)
MainActivity.java
package com.blogspot.android_er.androidopenweathermap; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class MainActivity extends AppCompatActivity { EditText editTextCityName; Button btnByCityName; TextView textViewResult, textViewInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextCityName = (EditText)findViewById(R.id.cityname); btnByCityName = (Button)findViewById(R.id.bycityname); textViewResult = (TextView)findViewById(R.id.result); textViewInfo = (TextView)findViewById(R.id.info); btnByCityName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new OpenWeatherMapTask( editTextCityName.getText().toString(), textViewResult).execute(); } }); } private class OpenWeatherMapTask extends AsyncTask<Void, Void, String> { String cityName; TextView tvResult; String dummyAppid = "bd82977b86bf27fb59a04b61b657fb6f"; String queryWeather = "http://api.openweathermap.org/data/2.5/weather?q="; String queryDummyKey = "&appid=" + dummyAppid; OpenWeatherMapTask(String cityName, TextView tvResult){ this.cityName = cityName; this.tvResult = tvResult; } @Override protected String doInBackground(Void... params) { String result = ""; String queryReturn; String query = null; try { query = queryWeather + URLEncoder.encode(cityName, "UTF-8") + queryDummyKey; queryReturn = sendQuery(query); result += ParseJSON(queryReturn); } catch (UnsupportedEncodingException e) { e.printStackTrace(); queryReturn = e.getMessage(); } catch (IOException e) { e.printStackTrace(); queryReturn = e.getMessage(); } final String finalQueryReturn = query + " " + queryReturn; runOnUiThread(new Runnable() { @Override public void run() { textViewInfo.setText(finalQueryReturn); } }); return result; } @Override protected void onPostExecute(String s) { tvResult.setText(s); } private String sendQuery(String query) throws IOException { String result = ""; URL searchURL = new URL(query); HttpURLConnection httpURLConnection = (HttpURLConnection)searchURL.openConnection(); if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){ InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream()); BufferedReader bufferedReader = new BufferedReader( inputStreamReader, 8192); String line = null; while((line = bufferedReader.readLine()) != null){ result += line; } bufferedReader.close(); } return result; } private String ParseJSON(String json){ String jsonResult = ""; try { JSONObject JsonObject = new JSONObject(json); String cod = jsonHelperGetString(JsonObject, "cod"); if(cod != null){ if(cod.equals("200")){ jsonResult += jsonHelperGetString(JsonObject, "name") + " "; JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys"); if(sys != null){ jsonResult += jsonHelperGetString(sys, "country") + " "; } jsonResult += " "; JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord"); if(coord != null){ String lon = jsonHelperGetString(coord, "lon"); String lat = jsonHelperGetString(coord, "lat"); jsonResult += "lon: " + lon + " "; jsonResult += "lat: " + lat + " "; } jsonResult += " "; JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather"); if(weather != null){ for(int i=0; i<weather.length(); i++){ JSONObject thisWeather = weather.getJSONObject(i); jsonResult += "weather " + i + ": "; jsonResult += "id: " + jsonHelperGetString(thisWeather, "id") + " "; jsonResult += jsonHelperGetString(thisWeather, "main") + " "; jsonResult += jsonHelperGetString(thisWeather, "description") + " "; jsonResult += " "; } } JSONObject main = jsonHelperGetJSONObject(JsonObject, "main"); if(main != null){ jsonResult += "temp: " + jsonHelperGetString(main, "temp") + " "; jsonResult += "pressure: " + jsonHelperGetString(main, "pressure") + " "; jsonResult += "humidity: " + jsonHelperGetString(main, "humidity") + " "; jsonResult += "temp_min: " + jsonHelperGetString(main, "temp_min") + " "; jsonResult += "temp_max: " + jsonHelperGetString(main, "temp_max") + " "; jsonResult += "sea_level: " + jsonHelperGetString(main, "sea_level") + " "; jsonResult += "grnd_level: " + jsonHelperGetString(main, "grnd_level") + " "; jsonResult += " "; } jsonResult += "visibility: " + jsonHelperGetString(JsonObject, "visibility") + " "; jsonResult += " "; JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind"); if(wind != null){ jsonResult += "wind: "; jsonResult += "speed: " + jsonHelperGetString(wind, "speed") + " "; jsonResult += "deg: " + jsonHelperGetString(wind, "deg") + " "; jsonResult += " "; } //...incompleted }else if(cod.equals("404")){ String message = jsonHelperGetString(JsonObject, "message"); jsonResult += "cod 404: " + message; } }else{ jsonResult += "cod == null "; } } catch (JSONException e) { e.printStackTrace(); jsonResult += e.getMessage(); } return jsonResult; } private String jsonHelperGetString(JSONObject obj, String k){ String v = null; try { v = obj.getString(k); } catch (JSONException e) { e.printStackTrace(); } return v; } private JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){ JSONObject o = null; try { o = obj.getJSONObject(k); } catch (JSONException e) { e.printStackTrace(); } return o; } private JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){ JSONArray a = null; try { a = obj.getJSONArray(k); } catch (JSONException e) { e.printStackTrace(); } return a; } } } layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android_layout_width="match_parent" android_layout_height="match_parent" android_padding="16dp" android_orientation="vertical" tools_context=".MainActivity"> <TextView android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_gravity="center_horizontal" android_autoLink="web" android_text="http://android-er.blogspot.com/" android_textStyle="bold" /> <EditText android_id="@+id/cityname" android_layout_width="match_parent" android_layout_height="wrap_content" android_hint="City name"/> <Button android_id="@+id/bycityname" android_layout_width="match_parent" android_layout_height="wrap_content" android_text="Call current weather by city name"/> <LinearLayout android_layout_width="match_parent" android_layout_height="match_parent" android_orientation="horizontal"> <ScrollView android_layout_width="0dp" android_layout_height="match_parent" android_layout_weight="1"> <TextView android_id="@+id/result" android_layout_width="match_parent" android_layout_height="wrap_content" android_textSize="20dp" android_textStyle="bold"/> </ScrollView> <ScrollView android_layout_width="0dp" android_layout_height="match_parent" android_layout_weight="1"> <TextView android_id="@+id/info" android_layout_width="match_parent" android_layout_height="wrap_content" android_textSize="18dp" android_textStyle="italic"/> </ScrollView> </LinearLayout> </LinearLayout> Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.
<uses-permission android_name="android.permission.INTERNET"/> Download the files (Android Studio Format) .