Weather Forecasting Android App using OpenWeatherMap API in Android Studio

In this tutorial, we will create a Weather Forecasting application in android using java. We can create an android project either using Android Studio or Eclipse IDE. For using Eclipse IDE we need to add ADT plugin, SDK manager, and Android Version. Therefore we can say that using Eclipse IDE is a lengthy process so instead of using Eclipse IDE most of the developers prefer using Android studio. We can use any version of Android Studio.

In this project, we are using Android Studio 3.6.3.

Create Weather Forecasting app in Android Studio

  1.  Open Android Studio and click on the file option on the upper left corner of the screen.
  2. Click on the new option and select the wizard that you want and click on the next option.
  3. Now enter the details that are the name of the project, name of the package, and android version.
  4. Click on the finish option. (You will get two files MainActivity.java and activity_main.xml)
  5. In the MainActivity.java write java code and in activity_main.xml file write code to design front-end of the app.

VIEW of the screen:

Weather Forecasting Android App using OpenWeatherMap API in Android Studio

 

CODE:

To design the front-end of the application we write code in activity_main.xml and for providing functionality to our application we write java code in MainActivity.java file. We can even create more classes in the same package.

package com.example.weatherforecasting1313;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
String CITY1;
TextView addressT, updated_atT, statusT, tempT, temp_minTxt, temp_maxT, sunriseT,sunsetT, windT, pressureT, humidityT;
    EditText CITY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
findViewById(R.id.presd).setVisibility(View.GONE);
        findViewById(R.id.sund).setVisibility(View.GONE);
        findViewById(R.id.sunsd).setVisibility(View.GONE);
        findViewById(R.id.wnd).setVisibility(View.GONE);
        findViewById(R.id.humd).setVisibility(View.GONE);
        CITY=findViewById(R.id.city);

    }
    public void run(View view){
        CITY1 = CITY.getText().toString();
        new weatherTask().execute();
    }

     class weatherTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            findViewById(R.id.loader).setVisibility(View.VISIBLE);
            findViewById(R.id.mainContainer).setVisibility(View.GONE);
            findViewById(R.id.errorText).setVisibility(View.GONE);
            findViewById(R.id.city).setVisibility(View.GONE);
            findViewById(R.id.button2).setVisibility(View.GONE);


        }

        protected String doInBackground(String args[]) {
            String response = HttpRequest.excuteGet("https://api.openweathermap.org/data/2.5/weatherq="+CITY1+"&units=metric&appid=73cbebdd0322acd49bda6ede059b2b18");
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            addressT = findViewById(R.id.address);
            updated_atT = findViewById(R.id.updated_at);
            statusT = findViewById(R.id.status);
            tempT = findViewById(R.id.temp);
            temp_minTxt = findViewById(R.id.temp_min);
            temp_maxT = findViewById(R.id.temp_max);
            sunriseT = findViewById(R.id.sunrise);
            sunsetT = findViewById(R.id.sunset);
            windT = findViewById(R.id.wind);
            pressureT = findViewById(R.id.pressure);
            humidityT = findViewById(R.id.humidity);

            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONObject main = jsonObj.getJSONObject("main");
                JSONObject sys = jsonObj.getJSONObject("sys");
                JSONObject wind = jsonObj.getJSONObject("wind");
                JSONObject weather = jsonObj.getJSONArray("weather").getJSONObject(0);

                Long updatedAt = jsonObj.getLong("dt");
                String updatedAtText = "Updated at: " + new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.ENGLISH).format(new Date(updatedAt * 1000));
                String temp = main.getString("temp") + "°C";
                String tempMin = "Min Temp: " + main.getString("temp_min") + "°C";
                String tempMax = "Max Temp: " + main.getString("temp_max") + "°C";
                String pressure = main.getString("pressure");
                String humidity = main.getString("humidity");


                Long sunrise = sys.getLong("sunrise");
                Long sunset = sys.getLong("sunset");
                String windSpeed = wind.getString("speed");
                String weatherDescription = weather.getString("description");

                String address = jsonObj.getString("name") + ", " + sys.getString("country");
                addressT.setText(address);
                updated_atT.setText(updatedAtText);
                statusT.setText(weatherDescription.toUpperCase());
                tempT.setText(temp);
                temp_minTxt.setText(tempMin);
                temp_maxT.setText(tempMax);
sunriseT.setText (new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunrise * 1000)));
                sunsetT.setText(new SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(new Date(sunset * 1000)));
                windT.setText(windSpeed);
                pressureT.setText(pressure);
                humidityT.setText(humidity);
                findViewById(R.id.loader).setVisibility(View.GONE);
                findViewById(R.id.mainContainer).setVisibility(View.VISIBLE);
                findViewById(R.id.presd).setVisibility(View.VISIBLE);
                findViewById(R.id.sund).setVisibility(View.VISIBLE);
                findViewById(R.id.sunsd).setVisibility(View.VISIBLE);
                findViewById(R.id.wnd).setVisibility(View.VISIBLE);
                findViewById(R.id.humd).setVisibility(View.VISIBLE);


            } catch (JSONException e) {
                findViewById(R.id.loader).setVisibility(View.GONE);
                findViewById(R.id.errorText).setVisibility(View.VISIBLE);
            }

        }
    }
}
---------------------------------------------------------------------------------------------------------

package com.example.weatherforecasting1313;

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

public class HttpRequest {
    public static String excuteGet(String targetURL) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            InputStream is;
            int status = connection.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK)
                is = connection.getErrorStream();
            else
                is = connection.getInputStream();

            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}


In the above code com.example.weatherforecasting1313 is the name of our package. Further, we are importing all the required classes and interfaces. But we don’t need to worry about these classes as we can directly import these files by pressing “Alt+Enter” after writing the method from that class that we need to import. Further, we created the variables of String, EditText, and TextView. In the onCreate method of our class, we set the visibilities of several text views as per our requirement. View.VISIBLE means that the TextView is visible on the front view and View.GONE means that the TextView is not visible on the front end of our application.

Further, we created the doInBackground method in which we are passing the

String response = HttpRequest.excuteGet(“https://api.openweathermap.org/data/2.5/weatherq=”+CITY1+”&units=metric&appid=73cbebdd0322acd49bda6ede059b2b18”);

Here 73cbebdd0322acd49bda6ede059b2b18 is the key of the API used.

To get the key

create your account

https://home.openweathermap.org/users/sign_up

after creating account Log-In here to get the API https://home.openweathermap.org/users/sign_in

HttpRequest is the name of our class in the same package which we are using to fetch data.

JSONObject is the constructor used to convert external form JSON (Javascript Object Notation) text into an internal form which we can retrieve with getRequest and can convert values into JSON text using the toString method.

The SimpleDateFormat is used to set the format of the data which we want to display on the TextView to be viewed on front end of our application.

Again we are setting data to the TextViews and setting the visibility of the TextViews used.

HttpRequest.java

First of all, we created the parameterized method executeGet in which targetUrl is the URL we passed in our MainActivity class in response variable in which we passed our API key. Then we opened the link and set our RequestMethod as “GET” as we want to fetch data. Further, we are writing our code in the try-catch block so as to handle Exceptions. The finally block is always executed whether an exception occurs or not.

Buffered Reader is class that is used to read text from character input stream buffering characters so as to read characters efficiently.

The method getResponseCode is used to retrieve the response status from the server.

In finally block we are disconnecting the connection as finally block is always executed whether Exception occurs or not.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="25dp"
    android:background="@drawable/bcwf">

    <RelativeLayout android:id="@+id/mainContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible">
        <LinearLayout android:id="@+id/addressContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center"
            >
            <TextView android:id="@+id/address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="30dp"
                android:textColor="#000000"
                android:textStyle="italic"
                />
            <TextView android:id="@+id/updated_at"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="20dp"
                android:textSize="20dp"
                android:textStyle="bold"
                android:textColor="#000000"
               />
        </LinearLayout>


        <LinearLayout android:id="@+id/overviewContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_centerInParent="true">

            <TextView android:id="@+id/status"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18dp"
                android:textStyle="bold"
                android:layout_gravity="center"
                android:textColor="#000000"
           />
            <TextView android:id="@+id/temp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="90dp"
                android:layout_gravity="center"
                android:textColor="#000000"
               />

            <LinearLayout android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center">
                <TextView android:id="@+id/temp_min"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textColor="#000000"
                />
                <Space android:layout_width="50dp"
                    android:layout_height="wrap_content"/>

                <TextView android:id="@+id/temp_max"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textColor="#000000"
                  />
            </LinearLayout>

        </LinearLayout>


        <LinearLayout android:id="@+id/detailsContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentBottom="true">
            <LinearLayout android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="3">
                <LinearLayout android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="8dp"
                    android:background="#3CF1EBF1">

                    <Space android:layout_width="wrap_content"
                        android:layout_height="5dp"/>
                    <TextView android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
android:text="Sunrise"
                        android:id="@+id/sund"
                        android:textStyle="bold"
                        android:textColor="#000000"/>
                    <TextView android:id="@+id/sunrise"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="14dp"
                        android:textStyle="bold"
                        android:textColor="#000000"
                        />
                </LinearLayout>
                <Space android:layout_width="10dp"
                    android:layout_height="wrap_content"/>
                <LinearLayout android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="8dp"
                    android:background="#3CF1EBF1"
                    android:id="@+id/sunsd">

                    <Space android:layout_width="wrap_content"
                        android:layout_height="5dp"/>
                    <TextView android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
                        android:text="Sunset"
                        android:textStyle="bold"
                        android:textColor="#000000"/>
                    <TextView android:id="@+id/sunset"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="14dp"
                        android:textStyle="bold"
                        android:textColor="#000000"
                 />
                </LinearLayout>
                <Space android:layout_width="10dp"
                    android:layout_height="wrap_content"/>
                <LinearLayout android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="8dp"
                    android:background="#3CF1EBF1"
                    android:id="@+id/wnd">

                    <Space android:layout_width="wrap_content"
                        android:layout_height="5dp"/>
                    <TextView android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
                        android:text="Wind"
                        android:textColor="#000000"
                        android:textStyle="bold"/>
                    <TextView android:id="@+id/wind"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="14dp"
                        android:textStyle="bold"
                        android:textColor="#000000"
                     />
                </LinearLayout>
            </LinearLayout>

            <Space android:layout_width="wrap_content"
                android:layout_height="10dp"/>

            <LinearLayout android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="3">
                <LinearLayout android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="8dp"
                    android:background="#3CF1EBF1"
                    android:id="@+id/presd"
                    >

                    <Space android:layout_width="wrap_content"
                        android:layout_height="5dp"/>
                    <TextView android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
                        android:text="Pressure"
                        android:textColor="#000000"

                        android:textStyle="bold"/>
                    <TextView android:id="@+id/pressure"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="14dp"
                        android:textStyle="bold"
                        android:textColor="#000000"
             />
                </LinearLayout>
                <Space android:layout_width="10dp"
                    android:layout_height="wrap_content"/>
                <LinearLayout android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:padding="8dp"
                    android:background="#3CF1EBF1"
                    android:id="@+id/humd">

                    <Space android:layout_width="wrap_content"
                        android:layout_height="5dp"/>
                    <TextView android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
                        android:textStyle="bold"
                        android:text="Humidity"
                        android:textColor="#000000"/>
                    <TextView android:id="@+id/humidity"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="14dp"
                        android:textStyle="bold"
                        android:textColor="#000000"
                     />
                </LinearLayout>

            </LinearLayout>
        </LinearLayout>

        <EditText
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="131dp"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="ENTER NAME OF CITY"
            android:textColor="#000000"/>

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="224dp"
            android:onClick="run"
            android:text="SEARCH TEMPERATURE"
            android:textColor="#000000"/>

    </RelativeLayout>


    <ProgressBar android:id="@+id/loader"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone"/>

    <TextView android:id="@+id/errorText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone"
        android:textColor="#000000"
        android:text="Something went wrong"/>


</RelativeLayout>

For designing the front end of our application we can use two methods.

  1. We can directly drag and drop the required fields.
  2.  We can write the XML code for the required code.

If we will drag the required field our XML code will be generated automatically.

While designing the front end we just need to specify the layout and id of the field rest all are generally for the design purpose. In the textColor option “#000000” is the hashcode for the black color.

Setting the layout is also important as layout determines the view of our front-end.

We can add as many attributes as we want. But in this tutorial, I only added the basic and required attributes.

To add images as background we need to download the image and save it in the drawable folder.

OUTPUT

First of all, we will get the EditText with hint Enter City.

Weather Forecasting Android App using OpenWeatherMap API in Android Studio

Then we will enter the name of the city and click the button Search Temperature.

Weather forecasting android app using android studio

After clicking the button we will get the screen showing the required data.

Weather data in android studio

 

 

Leave a Reply