Skip to main content

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.
Open Weather Map API Example
Open Weather Map API Example

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.

Open Weather Map API Example
Open Weather Map API Example

Software / Files used:

  • Android Studio (Version 3.x)

Files Edited / Created:

  1. activity_main.xml
  2. MainActivity.Java
  3. Weather.Java
  4. AndroidManifest.xml

Steps Involved in Open Weather Map API Example:

Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.

Open Weather Map API Example
Open Weather Map API Example


4. Open AndroidManifest.xml and request for Internet permission. this can be done by adding following line of code:

<uses-permission android:name="android.permission.INTERNET"/>
 
5. The complete code for AndroidManifest.xml can be found here:

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.faultinmycode.fimcweatherapp">

    <uses-permission android:name="android.permission.INTERNET"/>

    <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>
 
6. Go to activity_main.xml and create 6 textviews in order as shown below:
  • Name of the City [Parent Top]
  • Time of Data Update
  • Weather Detail
  • Humidity
  • Pressure
  • Current temperature [Parent Bottom]
7. The complete code for activity_main.xml can be found here:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="@color/colorPrimary"
    tools:context="com.faultinmycode.fimcweatherapp.MainActivity">

    <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="15sp" />

    <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_centerHorizontal="true"
        android:layout_centerInParent="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"/>

</RelativeLayout>
 
8. Create a new Java file named Weather.Java. This is where all background data will be processed.

Weather.Java
package com.faultinmycode.fimcweatherapp;

import android.os.AsyncTask;
import android.util.Log;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by faultinmycode team on 24-02-2018.
 */

public class weather {

    private static final String OPEN_WEATHER_MAP_URL =
            "http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";

    private static final String OPEN_WEATHER_MAP_API = "e0dd3d1782xxxxxxxxxxx32b2d796";
    // Insert your Weather API Here

    public interface AsyncResponse {

        void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
    }


    public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {

        public AsyncResponse delegate = null;
        //Call back interface

        public placeIdTask(AsyncResponse asyncResponse) {
            delegate = asyncResponse;
            //Assigning call back interface through constructor
        }

        @Override
        protected JSONObject doInBackground(String... params) {

            JSONObject jsonWeather = null;
            try {
                jsonWeather = getWeatherJSON(params[0], params[1]);
            } catch (Exception e) {
                Log.d("Error", "Cannot process JSON results", e);
            }


            return jsonWeather;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            try {
                if(json != null){
                    JSONObject details = json.getJSONArray("weather").getJSONObject(0);
                    JSONObject main = json.getJSONObject("main");
                    DateFormat df = DateFormat.getDateTimeInstance();


                    String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
                    String description = details.getString("description").toUpperCase(Locale.US);
                    String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
                    String humidity = main.getString("humidity") + "%";
                    String pressure = main.getString("pressure") + " hPa";
                    String updatedOn = df.format(new Date(json.getLong("dt")*1000));

                    delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);

                }
            } catch (JSONException e) {

            }



        }
    }

    public static JSONObject getWeatherJSON(String lat, String lon){
        try {
            URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
            HttpURLConnection connection =
                    (HttpURLConnection)url.openConnection();

            connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));

            StringBuffer json = new StringBuffer(1024);
            String tmp="";
            while((tmp=reader.readLine())!=null)
                json.append(tmp).append("\n");
            reader.close();

            JSONObject data = new JSONObject(json.toString());

            // This value will be 404 if the request was not successful
            if(data.getInt("cod") != 200){
                return null;
            }

            return data;
        }catch(Exception e){
            return null;
        }
    }




}
 
9. Don’t forget to add your API Key in line 26th as shown in the code above.

private static final String OPEN_WEATHER_MAP_API = "d17822xxxxxxxxxxxxxxx796";
// Insert your Weather API Here
 
10. Go to MainActivity.Java and hide Action Bar using following line of code in onCreate() method:
getSupportActionBar().hide();
 
11. Create TextView variables and link them with respective ids in activity_main.xml files.

12. Create an AsyncTask that’ll fetch data for particular location and provide the desired location longitude and latitude in following line of code:

asyncTask.execute("28.613900", "77.209000"); // Location New Delhi Paharganj
 
13. Complete code for MainActivity.Java can be found here:

MainActivity.Java
package com.faultinmycode.fimcweatherapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, updatedField;

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

        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);


        weather.placeIdTask asyncTask =new weather.placeIdTask(new weather.AsyncResponse() {
            public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {

                cityField.setText(weather_city);
                updatedField.setText(weather_updatedOn);
                detailsField.setText(weather_description);
                currentTemperatureField.setText(weather_temperature);
                humidity_field.setText("Humidity: "+weather_humidity);
                pressure_field.setText("Pressure: "+weather_pressure);
            }
        });
        asyncTask.execute("28.613900", "77.209000"); //  asyncTask.execute("Latitude", "Longitude")



    }
}
 
14. Run your App and let us know if you liked this tutorial in comment section below!


Comments

  1. You can get affordable task from regarding in all categories. Thank you!

    ReplyDelete
  2. Thank You! - Quick question, how do you get updates with this AsyncTask, I have tried but the TexTView's does not update, they only update when I close the application and re-open it again? - Thank You

    ReplyDelete
    Replies
    1. i hope you're updating Textviews using onPostExecute method in AsyncTask and not with doInBackground()

      Delete
    2. This comment has been removed by the author.

      Delete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Could you help me parse the information for all 5 days ?

    ReplyDelete
    Replies
    1. You need to change in the Weather.java the following

      http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric

      to

      http://api.openweathermap.org/data/2.5/forecast?lat=%s&lon=%s&units=metric

      You will then get the forecast of the weather for the next few days broken up in 3 hour intervals - Note, that these are forecasts and not actual.

      If you want to see how I used all available information and some modified information, check this link out https://imgur.com/V4kPTsH , I can share my coding with you if you need it.

      Delete
    2. Thanks for your comment! (Y)

      Delete
    3. Rishabh Jain, if you want, I can email my full code to you of what I have done with this project, I used the wind degrees to also indicate the wind direction and I have used the icon's to indicate if it is clear sky etc :)

      Delete

Post a Comment

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I've used bitcoin.pdf file, you can use any of your choices.
Software F…

Python Turtle Example: Flappy Bird Development in under 10 mins!

Python Turtle Example | Develop Flappy Bird Clone in 10 mins In the following tutorial, we have used following Python libraries:
1. random: To generate obstacles at random position. 2. turtle: To help provide directions to the player. 3. vector from freegames: To 2-dimensional vectors.
Before developing the game, here is a screenshot of what you'll be developing in 10 mins.
Steps to create Python Flappy Bird Game:
1. Open Pycharm and install 'freegames' package by going to Files > Settings > Project Interpreter. 2. Click on '+' sign on right and search for 'freegames' package. 3. Import packages in your project by writing following lines of code:
from random import * from turtle import * from freegames import vector 4. There are two variables required in the game, one for Bird object and another for an array of obstacles:
bird = vector(0, 0) balls = []
5. Create function for the player response on screen tap:
def tap(x, y): "Move bird up in res…