How to Create Free Live Weather App In Android – Step by step – Part 2

6th March, 2020

Welcome back! This is part-2 of the Free Live Weather App In Android. Let’s get started.

Step 4: Get Live Weather Data

4.1 Create Weather Data Model Class

Create a model class that represents the weather data needed for the application.

package com.codestringz.myweatherapp.model;

public class MyWeather
{
    private String weatherCondition;
    private String weatherDescription;
    private String weatherIconStr;
    private float temperature;

    public String getWeatherCondition()
    {
        return weatherCondition;
    }

    public void setWeatherCondition(String weatherCondition)
    {
        this.weatherCondition = weatherCondition;
    }

    public String getWeatherDescription()
    {
        return weatherDescription;
    }

    public void setWeatherDescription(String weatherDescription)
    {
        this.weatherDescription = weatherDescription;
    }

    public String getWeatherIconStr()
    {
        return weatherIconStr;
    }

    public void setWeatherIconStr(String weatherIconStr)
    {
        this.weatherIconStr = weatherIconStr;
    }

    public float getTemperature()
    {
        return temperature;
    }

    public void setTemperature(float temperature)
    {
        this.temperature = temperature;
    }
}

4.2 Create Helper Util classes

Create a util class that fetches weather data from the provided URL.

package com.codestringz.myweatherapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyWeatherClient
{
    public static String fetchWeather(String jsonURL)
    {
        String jsonStr = null;

        HttpURLConnection urlConnection = null;
        BufferedReader bufferedReader = null;

        try
        {
            //---Loading JSON from the Web URL---//
            URL url = new URL(jsonURL);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();

            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder stringBuilder = new StringBuilder();

            String line;

            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line).append("\n");
            }
            if (stringBuilder.length() != 0)
            {
                jsonStr= stringBuilder.toString();
            }
        } catch (IOException ignored)
        {
        } finally
        {
            if (urlConnection != null)
            {
                urlConnection.disconnect();
            }
            if (bufferedReader != null)
            {
                try
                {
                    bufferedReader.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return jsonStr;
    }
}

Create another util class that parses JSON Data into the weather model class.

package com.codestringz.myweatherapp;
import com.codestringz.myweatherapp.model.MyWeather;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyJSONParser
{
    public static MyWeather getMyWeather(String jsonStr)
    {
        MyWeather myWeather = new MyWeather();

        try
        {
            JSONObject rootJsonObject = new JSONObject(jsonStr);

            //Get Weather condition
            JSONArray weatherJsonArray = rootJsonObject.getJSONArray("weather");
            JSONObject jsonObject1 = weatherJsonArray.getJSONObject(0);
            myWeather.setWeatherCondition(jsonObject1.getString("main"));
            myWeather.setWeatherDescription(jsonObject1.getString("description"));
            myWeather.setWeatherIconStr(jsonObject1.getString("icon"));

            //Get temperature
            JSONObject jsonObject2 = rootJsonObject.getJSONObject("main");
            myWeather.setTemperature((float) jsonObject2.getDouble("temp"));

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

Next, create a class that handles background operations. Also create a background operations listener interface.

package com.codestringz.myweatherapp;

import android.os.AsyncTask;

import com.codestringz.myweatherapp.model.MyWeather;

public class MyWeatherTask extends AsyncTask<String, Void, MyWeather>
{
    private MyWeatherTaskListener mListener;

    MyWeatherTask(MyWeatherTaskListener pListener)
    {
        this.mListener = pListener;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        mListener.onMyWeatherTaskPreExecute();
    }

    @Override
    protected MyWeather doInBackground(String... strings)
    {
        MyWeather myWeather = null;

        //Fetch Weather
        String jsonStr = MyWeatherClient.fetchWeather(strings[0]);

        //Parsing Weather
        if (jsonStr != null)
        {
            myWeather = MyJSONParser.getMyWeather(jsonStr);
        }
        return myWeather;
    }

    @Override
    protected void onPostExecute(MyWeather myWeather)
    {
        super.onPostExecute(myWeather);
        mListener.onMyWeatherTaskPostExecute(myWeather);
    }
}

interface MyWeatherTaskListener
{
    void onMyWeatherTaskPreExecute();
    void onMyWeatherTaskPostExecute(MyWeather myWeather);
}

Step 5: Update Activity

Now open the Activity and add the code given below.

5.1 Load Weather Condition Icon

Let’s display the weather condition icon in the app. To do this, Here I am using the Glide Image Loading Library. Add Glide library dependencies to your app level build.gradle.
Project ⇒ app ⇒ build.gradle

dependencies
{
    implementation 'com.github.bumptech.glide:glide:4.10.0'
}

5.2 Display Weather Data

That’s it. Finally update the Activity.

package com.codestringz.myweatherapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.codestringz.myweatherapp.databinding.ActivityMainBinding;
import com.codestringz.myweatherapp.model.MyWeather;

public class MainActivity extends AppCompatActivity implements MyWeatherTaskListener
{
    private ActivityMainBinding binding;

    //Web URL of the JSON file
    private String mApiKey = "your api key";
    private String mCity = "London";
    private String mCountry = "United Kingdom";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        //http://api.openweathermap.org/data/2.5/weather?q=city,country&APPID={your api key};
        String weatherURL = "http://api.openweathermap.org/data/2.5/weather?q=" + mCity + "," + mCountry + "&APPID=" + mApiKey;
        new MyWeatherTask(this).execute(weatherURL);
    }

    @Override
    public void onMyWeatherTaskPreExecute()
    {
        binding.myLoadingLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onMyWeatherTaskPostExecute(MyWeather myWeather)
    {
        if (myWeather != null)
        {
            binding.cityTextView.setText(mCity);
            binding.countryTextView.setText(mCountry);

            binding.weatherConditionTextView.setText(myWeather.getWeatherCondition());
            binding.weatherDescriptionTextView.setText(myWeather.getWeatherDescription());

            int temp = Math.round(myWeather.getTemperature() - 273.15f);
            String tempStr = String.valueOf(temp);
            binding.temperatureTextView.setText(tempStr);

            String imgUrl = "http://openweathermap.org/img/wn/" + myWeather.getWeatherIconStr() + "@2x.png";

            Glide.with(MainActivity.this)
                    .asBitmap()
                    .load(imgUrl)
                    .placeholder(R.mipmap.ic_launcher)
                    .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
                    .into(binding.weatherIconImageView);
        }
        binding.myLoadingLayout.setVisibility(View.GONE);
    }
}

Happy coding!

References: https://openweathermap.org/api

Attribution: “Weather Data” provide by openweathermap.org is licensed under CC BY-SA 4.0

4 Comments

Leave a Reply