Create a weather app on android – Android Stdio

Create a weather app on android – Android Studio

Creating a weather app on Android is easy and a damn cool thing you can use by yourself. Oh, don’t worry, you don’t need to setup a weather station in each city on each country to get weather information in your app. You can get those information including Temperature, Pressure, Humidity, Weather status by using weather Api.

There are many websites you can get by searching on the Google which supply free weather Api, but In this tutorial we are going to use a Api provided by OpenWeatherMap. So let’s start to create a weather app.

Android Weather App – Android Studio

Download project files of Android weather app with all custom images & font.

Size: 0.18 MB

Steps to Create a Weather App on Android


 1. First of all create a Weather API from OpenWeatherMap.

 2. Create a new project in Android Studio in a normal way.

3. Copy weathericons-regular-webfont.ttf to your project’s src/main/assets/fonts directory. You can download the font from here.

Or you can download from our website and extract the zip file.

Download weathericons-regular-webfont.ttf

Download the font file for weather icons.

 4. Open your AndroidManifest.xml file and add internet connect permission. Your manifest file will look like this-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androstock.myweatherapp">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

5. Open your activity_main.xml file. Use a RelativeLayout to arrange the text views. You can adjust the textSize to suit various devices.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3F51B5"
    android:padding="20dp">

    <TextView
        android:id="@+id/city_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/updated_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/city_field"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="13sp" />
    <TextView
        android:id="@+id/selectCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change City"
        android:textStyle="italic"
        android:textSize="11dp"
        android:textColor="@color/colorAccent"
        android:layout_below="@+id/updated_field"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@+id/weather_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="90sp"
        />

    <TextView
        android:id="@+id/current_temperature_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="50sp" />

    <TextView
        android:id="@+id/details_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/weather_icon"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />
    <TextView
        android:id="@+id/humidity_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/details_field"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />
    <TextView
        android:id="@+id/pressure_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/humidity_field"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />

    <ProgressBar
        android:id="@+id/loader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Finally we are heading towards the Java coding.

6. Now we are going to create a Java class file named Function.java. Here we will write all our functions so that we can use them easily from MainActiviy.java letter.

We use the HttpURLConnection class to make the remote request. We use a BufferedReader to read the API’s response into a StringBuffer. When we have the complete response, we convert it to a JSONObject object.

package com.androstock.myweatherapp;

import android.content.Context;
import android.net.ConnectivityManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Function {

    // Project Created by Ferdousur Rahman Shajib
    // www.androstock.com

    public static boolean isNetworkAvailable(Context context)
    {
        return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }



    public static String excuteGet(String targetURL)
    {
        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestProperty("content-type", "application/json;  charset=utf-8");
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(false);

            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) {
            return null;
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
        }
    }


    public static String setWeatherIcon(int actualId, long sunrise, long sunset){
        int id = actualId / 100;
        String icon = "";
        if(actualId == 800){
            long currentTime = new Date().getTime();
            if(currentTime>=sunrise && currentTime<sunset) {
                icon = "&#xf00d;";
            } else {
                icon = "&#xf02e;";
            }
        } else {
            switch(id) {
                case 2 : icon = "&#xf01e;";
                    break;
                case 3 : icon = "&#xf01c;";
                    break;
                case 7 : icon = "&#xf014;";
                    break;
                case 8 : icon = "&#xf013;";
                    break;
                case 6 : icon = "&#xf01b;";
                    break;
                case 5 : icon = "&#xf019;";
                    break;
            }
        }
        return icon;
    }


}

 

7. Now time to move towards the MainActivity.java class. We are going to make the activity fullscreen. So add the following line before your setContentView().

getSupportActionBar().hide();

Your MainActivity.java will look like-

package com.androstock.myweatherapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    // Project Created by Ferdousur Rahman Shajib
    // www.androstock.com
    
    TextView selectCity, cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
    ProgressBar loader;
    Typeface weatherFont;
    String city = "Dhaka, BD";
    /* Please Put your API KEY here */
    String OPEN_WEATHER_MAP_API = "cbfdb21fa1793c10b14b6b6d00fbef03";
    /* Please Put your API KEY here */


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);

        loader = (ProgressBar) findViewById(R.id.loader);
        selectCity = (TextView) findViewById(R.id.selectCity);
        cityField = (TextView) findViewById(R.id.city_field);
        updatedField = (TextView) findViewById(R.id.updated_field);
        detailsField = (TextView) findViewById(R.id.details_field);
        currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
        humidity_field = (TextView) findViewById(R.id.humidity_field);
        pressure_field = (TextView) findViewById(R.id.pressure_field);
        weatherIcon = (TextView) findViewById(R.id.weather_icon);
        weatherFont = Typeface.createFromAsset(getAssets(), "fonts/weathericons-regular-webfont.ttf");
        weatherIcon.setTypeface(weatherFont);

        taskLoadUp(city);

        selectCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
                alertDialog.setTitle("Change City");
                final EditText input = new EditText(MainActivity.this);
                input.setText(city);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
                input.setLayoutParams(lp);
                alertDialog.setView(input);

                alertDialog.setPositiveButton("Change",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                city = input.getText().toString();
                                taskLoadUp(city);
                            }
                        });
                alertDialog.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                alertDialog.show();
            }
        });

    }


    public void taskLoadUp(String query) {
        if (Function.isNetworkAvailable(getApplicationContext())) {
            DownloadWeather task = new DownloadWeather();
            task.execute(query);
        } else {
            Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
        }
    }



    class DownloadWeather extends AsyncTask < String, Void, String > {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loader.setVisibility(View.VISIBLE);

        }
        protected String doInBackground(String...args) {
            String xml = Function.excuteGet("http://api.openweathermap.org/data/2.5/weather?q=" + args[0] +
                    "&units=metric&appid=" + OPEN_WEATHER_MAP_API);
            return xml;
        }
        @Override
        protected void onPostExecute(String xml) {

            try {
                JSONObject json = new JSONObject(xml);
                if (json != null) {
                    JSONObject details = json.getJSONArray("weather").getJSONObject(0);
                    JSONObject main = json.getJSONObject("main");
                    DateFormat df = DateFormat.getDateTimeInstance();

                    cityField.setText(json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country"));
                    detailsField.setText(details.getString("description").toUpperCase(Locale.US));
                    currentTemperatureField.setText(String.format("%.2f", main.getDouble("temp")) + "°");
                    humidity_field.setText("Humidity: " + main.getString("humidity") + "%");
                    pressure_field.setText("Pressure: " + main.getString("pressure") + " hPa");
                    updatedField.setText(df.format(new Date(json.getLong("dt") * 1000)));
                    weatherIcon.setText(Html.fromHtml(Function.setWeatherIcon(details.getInt("id"),
                            json.getJSONObject("sys").getLong("sunrise") * 1000,
                            json.getJSONObject("sys").getLong("sunset") * 1000)));

                    loader.setVisibility(View.GONE);

                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "Error, Check City", Toast.LENGTH_SHORT).show();
            }


        }



    }



}

Don’t forget to use your own API Key in the following line. Replace our key (Orange Colored) with yours.

String OPEN_WEATHER_MAP_API = "cbfdb21fa1793c10b14b6b6d00fbef03";

It’s done folks. Lets run it.

Next

22 Comments

  • Shoukat Khan (#)
    July 6th, 2017

    it worked perfectly.
    but what should i do if want the app to get the latitude and longitude values based on my GPS location rather than manually enter it?
    i’m Newbie so i’ll be glad for the help thanks

  • Umesh (#)
    July 29th, 2017

    I am newbie to android programming, trying few examples.

    What needs to be added further as you mentioned
    private static final String OPEN_WEATHER_MAP_API = “====== YOUR OPEN WEATHER MAP API ======”;

    • kristof verbeeck (#)
      September 30th, 2017

      you need to get an API key from the website you are using to pull data from (in this case openweathermap.org)

    • Ferdousur Rahman Sarker (#)
      October 24th, 2017

      private static final String OPEN_WEATHER_MAP_API = “====== YOUR OPEN WEATHER MAP API ======“;

      create a Weather API from OpenWeatherMap.

      See the attached video for understanding in a better way.

  • faizal (#)
    August 15th, 2017

    your api key

  • AiswaryaRaj (#)
    August 22nd, 2017

    how can get the weather details while searching the city

  • Aiswarya Raj (#)
    September 9th, 2017

    How to create project to display weather details by searching a particular city

  • Memoona (#)
    October 3rd, 2017

    nothing display…when i run it it just blink shows error msg unfortunately,your app is not working….what should i do now??

    • Ferdousur Rahman Sarker (#)
      October 24th, 2017

      Please cheack again if you have placed your weather api here or not.
      private static final String OPEN_WEATHER_MAP_API = “====== YOUR OPEN WEATHER MAP API ======“;

  • Raj (#)
    October 4th, 2017

    Why have you multiplied the sunrise and sunset time by 1000?

    • Ferdousur Rahman Sarker (#)
      October 24th, 2017

      By multiplying 1000 with sunrise & sunset we’r converting the time into milliseconds. Because late we were comparing those times with new Date().getTime() which also returns time in milliseconds.

  • Raj (#)
    October 5th, 2017

    case 2 : icon = “”;
    break;
    case 3 : icon = “”;
    break;
    case 7 : icon = “”;
    break;
    case 8 : icon = “”;
    break;
    case 6 : icon = “”;
    break;
    case 5 : icon = “”;
    break;

    In this code, I don’t understand the place from where you have taken up the icons?

    Thanks

    • Ferdousur Rahman Sarker (#)
      October 24th, 2017

      Those icons are into the font we used named weathericons-regular-webfont.ttf
      Copy weathericons-regular-webfont.ttf to your project’s src/main/assets/fonts directory. You can download the font from here.

  • Mlondi (#)
    October 10th, 2017

    Hi, How can we get the weather by searching the city/place using search on the action bar

  • Ryan (#)
    July 19th, 2018

    How can I change the location? It’s giving me a city I don’t know of. How do I change it. I’ve tried going to MainActivity and changing the coordinates at the bottom but it takes me to a completely different place I didn’t expect.

  • vidhi (#)
    August 17th, 2018

    its working perfectly fine…thnx

Leave a comment

Your email address will not be published. Required fields are marked *