How To Create Weather App Using Retrofit 2 In Android

Introduction

 
In this article, we will learn how to create our own weather app using Retrofit 2. There are a lot of providers available to provide weather data. In this tutorial we will use the famous provider “OpenWeatherMap” Api to build our own weather app.
 
Coding Part
 
I have arranged the article as follows.
  • Step 1 - Creating New Project with Empty Activity.
  • Step 2 - Setting up the Retrofit HTTP Library and Manifest.
  • Step 3 - Getting App ID from Open Weather API.
  • Step 4 - Implementation of consumption of Weather API using Retrofit.

Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.
  2. Name the project as per your wish and select your activity template.
     
    How To Create Weather App Using Retrofit 2 In Android
     
  3. Click finish button to create a new project in Android Studio.

Setting up the Retrofit Http Library and Manifest

 
In this part, we will see how to set up the library for the project.
  1. Then add the following lines in app level build.gradle file to apply Google services to your project.
    1. dependencies {  
    2.     ...  
    3.     implementation 'com.squareup.retrofit2:retrofit:2.0.0'  
    4.     implementation 'com.squareup.retrofit2:converter-gson:2.0.0'   
    5. }  
  1. Then click Sync Now to set up your project.
  2. Don't forget to add the following permission in your manifest file
    1. <uses-permission android:name="android.permission.INTERNET"/>  

Getting App Id from Open Weather Map

  1. Open OpenWeatherMap Site and sign up for free to get your app id.
     
    How To Create Weather App Using Retrofit 2 In Android
     
  2. You can find or create your app id in API Keys tab of the site after logged in. Find the screenshot for your reference.
     
    How To Create Weather App Using Retrofit 2 In Android

Implementation of consumption of Weather API using Retrofit

 
The following API link is used to get the current weather report respective to the geo-coordinates. The Sample API link is here.
 
We will see, how to use the link to access the weather data.
  1. Create an interface file named as “WeatherService.java” and add the following lines
    1. public interface WeatherService {  
    2.     @GET("data/2.5/weather?")  
    3.     Call<WeatherResponse> getCurrentWeatherData(@Query("lat") String lat, @Query("lon") String lon, @Query("APPID") String app_id);  
    4. }  
  1. Create a class file named as “WeatherResponse.java” and add the following lines. We will get the response as json as in the following.
    1. {  
    2.   "coord": {  
    3.     "lon": 139,  
    4.     "lat": 35  
    5.   },  
    6.   "sys": {  
    7.     "country""JP",  
    8.     "sunrise": 1369769524,  
    9.     "sunset": 1369821049  
    10.   },  
    11.   "weather": [  
    12.     {  
    13.       "id": 804,  
    14.       "main""clouds",  
    15.       "description""overcast clouds",  
    16.       "icon""04n"  
    17.     }  
    18.   ],  
    19.   "main": {  
    20.     "temp": 289.5,  
    21.     "humidity": 89,  
    22.     "pressure": 1013,  
    23.     "temp_min": 287.04,  
    24.     "temp_max": 292.04  
    25.   },  
    26.   "wind": {  
    27.     "speed": 7.31,  
    28.     "deg": 187.002  
    29.   },  
    30.   "rain": {  
    31.     "3h": 0  
    32.   },  
    33.   "clouds": {  
    34.     "all": 92  
    35.   },  
    36.   "dt": 1369824698,  
    37.   "id": 1851632,  
    38.   "name""Shuzenji",  
    39.   "cod": 200  
    40. }  
  1. I have used json to java converter online to generate the Response class and the equivalent java class should be  shown below.
    1. public class WeatherResponse {  
    2.   
    3.     @SerializedName("coord")  
    4.     public Coord coord;  
    5.     @SerializedName("sys")  
    6.     public Sys sys;  
    7.     @SerializedName("weather")  
    8.     public ArrayList<Weather> weather = new ArrayList<Weather>();  
    9.     @SerializedName("main")  
    10.     public Main main;  
    11.     @SerializedName("wind")  
    12.     public Wind wind;  
    13.     @SerializedName("rain")  
    14.     public Rain rain;  
    15.     @SerializedName("clouds")  
    16.     public Clouds clouds;  
    17.     @SerializedName("dt")  
    18.     public float dt;  
    19.     @SerializedName("id")  
    20.     public int id;  
    21.     @SerializedName("name")  
    22.     public String name;  
    23.     @SerializedName("cod")  
    24.     public float cod;  
    25. }  
    26.   
    27. class Weather {  
    28.     @SerializedName("id")  
    29.     public int id;  
    30.     @SerializedName("main")  
    31.     public String main;  
    32.     @SerializedName("description")  
    33.     public String description;  
    34.     @SerializedName("icon")  
    35.     public String icon;  
    36. }  
    37.   
    38. class Clouds {  
    39.     @SerializedName("all")  
    40.     public float all;  
    41. }  
    42.   
    43. class Rain {  
    44.     @SerializedName("3h")  
    45.     public float h3;  
    46. }  
    47.   
    48. class Wind {  
    49.     @SerializedName("speed")  
    50.     public float speed;  
    51.     @SerializedName("deg")  
    52.     public float deg;  
    53. }  
    54.   
    55. class Main {  
    56.     @SerializedName("temp")  
    57.     public float temp;  
    58.     @SerializedName("humidity")  
    59.     public float humidity;  
    60.     @SerializedName("pressure")  
    61.     public float pressure;  
    62.     @SerializedName("temp_min")  
    63.     public float temp_min;  
    64.     @SerializedName("temp_max")  
    65.     public float temp_max;  
    66. }  
    67.   
    68. class Sys {  
    69.     @SerializedName("country")  
    70.     public String country;  
    71.     @SerializedName("sunrise")  
    72.     public long sunrise;  
    73.     @SerializedName("sunset")  
    74.     public long sunset;  
    75. }  
    76.   
    77. class Coord {  
    78.     @SerializedName("lon")  
    79.     public float lon;  
    80.     @SerializedName("lat")  
    81.     public float lat;  
    82. }  
  1. The SerializedName annotation is used to parse the server response and their name & type should be the same as the Json Response received from the server.
     
  2. Then initialize Retrofit to call the weather service. The following code snippet will help us to call the service.
    1. void getCurrentData() {  
    2.     Retrofit retrofit = new Retrofit.Builder()  
    3.             .baseUrl(BaseUrl)  
    4.             .addConverterFactory(GsonConverterFactory.create())  
    5.             .build();  
    6.     WeatherService service = retrofit.create(WeatherService.class);  
    7.     Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);  
    8.     call.enqueue(new Callback<WeatherResponse>() {  
    9.         @Override  
    10.         public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {  
    11.             if (response.code() == 200) {  
    12.                 WeatherResponse weatherResponse = response.body();  
    13.                 assert weatherResponse != null;  
    14.   
    15.                 String stringBuilder = "Country: " +  
    16.                         weatherResponse.sys.country +  
    17.                         "\n" +  
    18.                         "Temperature: " +  
    19.                         weatherResponse.main.temp +  
    20.                         "\n" +  
    21.                         "Temperature(Min): " +  
    22.                         weatherResponse.main.temp_min +  
    23.                         "\n" +  
    24.                         "Temperature(Max): " +  
    25.                         weatherResponse.main.temp_max +  
    26.                         "\n" +  
    27.                         "Humidity: " +  
    28.                         weatherResponse.main.humidity +  
    29.                         "\n" +  
    30.                         "Pressure: " +  
    31.                         weatherResponse.main.pressure;  
    32.   
    33.                 weatherData.setText(stringBuilder);  
    34.             }  
    35.         }  
    36.   
    37.         @Override  
    38.         public void onFailure(@NonNull Call<WeatherResponse> call, @NonNull Throwable t) {  
    39.             weatherData.setText(t.getMessage());  
    40.         }  
    41.     });  
    42. }  
    Here we used Json Converter and so the json response automatically converted to the respective and the converter will compare the response tree with the serialized name.
  1. Our own developed weather app is ready.
Full Code
 
You can find the full code implementation of the app here.
  1. public class MainActivity extends AppCompatActivity {  
  2.     public static String BaseUrl = "http://api.openweathermap.org/";  
  3.     public static String AppId = "2e65127e909e178d0af311a81f39948c";  
  4.     public static String lat = "35";  
  5.     public static String lon = "139";  
  6.     private TextView weatherData;  
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.activity_main);  
  11.   
  12.         weatherData = findViewById(R.id.textView);  
  13.   
  14.         Typeface typeface = Typeface.createFromAsset(getAssets(), "Lato-Bold.ttf");  
  15.         FontUtils fontUtils = new FontUtils();  
  16.         fontUtils.applyFontToView(weatherData, typeface);  
  17.   
  18.         findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {  
  19.             @Override  
  20.             public void onClick(View v) {  
  21.                 getCurrentData();  
  22.             }  
  23.         });  
  24.     }  
  25.   
  26.     void getCurrentData() {  
  27.         Retrofit retrofit = new Retrofit.Builder()  
  28.                 .baseUrl(BaseUrl)  
  29.                 .addConverterFactory(GsonConverterFactory.create())  
  30.                 .build();  
  31.         WeatherService service = retrofit.create(WeatherService.class);  
  32.         Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);  
  33.         call.enqueue(new Callback<WeatherResponse>() {  
  34.             @Override  
  35.             public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {  
  36.                 if (response.code() == 200) {  
  37.                     WeatherResponse weatherResponse = response.body();  
  38.                     assert weatherResponse != null;  
  39.   
  40.                     String stringBuilder = "Country: " +  
  41.                             weatherResponse.sys.country +  
  42.                             "\n" +  
  43.                             "Temperature: " +  
  44.                             weatherResponse.main.temp +  
  45.                             "\n" +  
  46.                             "Temperature(Min): " +  
  47.                             weatherResponse.main.temp_min +  
  48.                             "\n" +  
  49.                             "Temperature(Max): " +  
  50.                             weatherResponse.main.temp_max +  
  51.                             "\n" +  
  52.                             "Humidity: " +  
  53.                             weatherResponse.main.humidity +  
  54.                             "\n" +  
  55.                             "Pressure: " +  
  56.                             weatherResponse.main.pressure;  
  57.   
  58.                     weatherData.setText(stringBuilder);  
  59.                 }  
  60.             }  
  61.   
  62.             @Override  
  63.             public void onFailure(@NonNull Call<WeatherResponse> call, @NonNull Throwable t) {  
  64.                 weatherData.setText(t.getMessage());  
  65.             }  
  66.         });  
  67.     }  
  68.   
  69. }  
To know more about Retrofit and Open Weather API
  1. https://openweathermap.org/api
  2. https://square.github.io/retrofit/
If you have any doubts or need any help, contact me.
 
Download Code
 
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.


Similar Articles