Create a Weather App on Android

Final product image
What You'll Be Creating

A lot of the popular weather apps on Google Play are either full of ads, require too many permissions, or include features that most of us never use. Wouldn't it be great if you could build your own weather app from scratch?

In this tutorial, I'm going to show you how. Our app will have a simple and minimalist user interface, showing the user exactly what they need to know about the current weather conditions. Let's get started.

Looking for a Shortcut?

This tutorial will teach you to build a weather app from scratch, but one alternative is to use one of the Android weather app templates on Envato Market.

For example, Weminder provides a simple, clean user interface and all the essential features of a weather app, so that you can then customize it for your own purposes.

Weminder weather app template on Envato Market
Weminder weather app template on Envato Market

Or, if you want something unique and custom-built, head over to Envato Studio to check out the selection of mobile and app development services on offer there.

1. Prerequisites

Before you continue, double-check that you have the following set up:

  • Eclipse ADT Bundle: You can download it at the Android Developer website.
  • OpenWeatherMap API Key : This isn't required to complete the tutorial, but it's free. You can obtain one by signing up at the OpenWeatherMap website.
  • Icons: I recommend you download the weather icons font created by Erik Flowers. You need to download the TTF file, because we'll be using it in a native app. We'll use the font to render various icons depending on the weather conditions.

2. Create a New Project

I'm going to call this app SimpleWeather, but feel free to give it any name you like. Enter a unique package name, set the minimum required SDK to Android 2.2, and set the target SDK to Android 4.4. You can leave the theme at Holo Dark.

Create a new Android Application

This app will only have one Activity and it will be based on the Blank Activity template as shown below.

Create a new activity

Name the Activity WeatherActivity. We'll be using a Fragment inside this Activity. The layout associated with the Activity is activity_weather.xml. The layout associated with the Fragment is fragment_weather.xml.

The Activity details screen

3. Add the Custom Font

Copy weathericons-regular-webfont.ttf to your project's assets/fonts directory and rename it to weather.ttf.

4. Edit the Manifest

The only permission this app needs is android.permission.INTERNET.


To keep this tutorial simple, we're only going to support portrait mode. The activity node of the manifest should look like this:

5. Edit the Activity's Layout

There isn't much to change in activity_weather.xml. It should already have a FrameLayout. Add an extra property to change the color of the background to #FF0099CC.

6. Edit the Fragment's Layout

Edit fragment_weather.xml by adding five TextView tags to show the following information:

  • city and country
  • current temperature
  • an icon showing the current weather condition
  • a timestamp telling the user when the weather information was last updated
  • more detailed information about the current weather, such as description and humidity

Use a RelativeLayout to arrange the text views. You can adjust the textSize to suit various devices.

7. Edit strings.xml

This file contains the strings used in our app as well as the Unicode character codes that we'll use to render the weather icons. The application will be able to display eight different types of weather conditions. If you want to handle more, then refer to this cheat sheet. Add the following to values/strings.xml:

8. Add a Menu Item

The user should be able to choose the city whose weather they want to see. Edit menu/weather.xml and add an item for this option.

Now that all the XML files are ready to use, let's move on and query the OpenWeatherMap API to fetch weather data.

9. Fetch Data From OpenWeatherMap

We can get the current weather details of any city formatted as JSON using the OpenWeatherMap API. In the query string, we pass the city's name and the metric system the results should be in.

For example, to get the current weather information for Canberra, using the metric system, we send a request to http://api.openweathermap.org/data/2.5/weather?q=Canberra&units=metric

The response we get back from the API looks like this:

Create a new Java class and name it RemoteFetch.java. This class is responsible for fetching the weather data from the OpenWeatherMap API.

We use the HttpURLConnection class to make the remote request. The OpenWeatherMap API expects the API key in an HTTP header named x-api-key. This is specified in our request using the setRequestProperty method.

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.

As you can see in the above response, the JSON data contains a field named cod. Its value is 200 if the request was successful. We use this value to check whether the JSON response has the current weather information or not.

The RemoteFetch.java class should look like this:

10. Store the City as a Preference

The user shouldn't have to specify the name of the city every time they want to use the app. The app should remember the last city the user was interested in. We do this by making use of SharedPreferences. However, instead of directly accessing these preferences from our Activity class, it is better to create a separate class for this purpose.

Create a new Java class and name it CityPreference.java. To store and retrieve the name of the city, create two methods setCity and getCity. The SharedPreferences object is initialized in the constructor. The CityPreference.java class should look like this:

11. Create the Fragment

Create a new Java class and name it WeatherFragment.java. This fragment uses fragment_weather.xml as its layout. Declare the five TextView objects and initialize them in the onCreateView method. Declare a new Typeface object named weatherFont. The TypeFace object will point to the web font you downloaded and stored in the assets/fonts folder.

We will be making use of a separate Thread to asynchronously fetch data from the OpenWeatherMap API. We cannot update the user interface from such a background thread. We therefore need a Handler object, which we initialize in the constructor of the WeatherFragment class.

Initialize the weatherFont object by calling createFromAsset on the Typeface class. We also invoke the updateWeatherData method in onCreate.

In updateWeatherData, we start a new thread and call getJSON on the RemoteFetch class. If the value returned by getJSON is null, we display an error message to the user. If it isn't, we invoke the renderWeather method.

Only the main Thread is allowed to update the user interface of an Android app. Calling Toast or renderWeather directly from the background thread would lead to a runtime error. That is why we call these methods using the handler's post method.

The renderWeather method uses the JSON data to update the TextView objects. The weather node of the JSON response is an array of data. In this tutorial, we will only be using the first element of the array of weather data.

At the end of the renderWeather method,  we invoke setWeatherIcon with the id of the current weather as well as the times of sunrise and sunset. Setting the weather icon is a bit tricky, because the OpenWeatherMap API supports more weather conditions than we can support with the web font we're using. Fortunately, the weather ids follow a pattern, which you can read more about on the OpenWeatherMap website.

This is how we map a weather id to an icon:

  • the weather codes in the 200 range are related to thunderstorms, which means we can use R.string.weather_thunder for these
  • the weather codes in the 300 range are related to drizzles and we use R.string.weather_drizzle for these
  • the weather codes in the 500 range signify rain and we use R.string.weather_rain for them
  • and so on ...

We use the sunrise and sunset times to display the sun or the moon, depending on the current time of the day and only if the weather is clear.

Of course, you can handle more weather conditions by adding more case statements to the switch statement of the setWeatherIcon method.

Finally, add a changeCity method to the fragment to let the user update the current city. The changeCity method will only be called from the main Activity class.

12. Edit the Activity

During the project's setup, Eclipse populated WeatherActivity.java with some boilerplate code. Replace the default implementation of the onCreate method with the one below in which we use the WeatherFragment. The onCreate method should look like this:

Next, edit the onOptionsItemSelected method and handle the only menu option we have. All you have to do here is invoke the showInputDialog method.

In the showInputDialog method, we use AlertDialog.Builder to create a Dialog object that prompts the user to enter the name of a city. This information is passed on to the changeCity method, which stores the name of the city using the CityPreference class and calls the Fragment's changeCity method.

Your weather app is now ready. Build the project and deploy it to an Android device for testing.

The app running on a tablet

Conclusion

You now have a fully functional weather application. Feel free to explore the OpenWeatherMap API to further enhance your application. You may also want to make use of more weather icons, because we are currently using only a small subset of them.

Tags:

Comments

Related Articles