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.
1. Prerequisites
Before you continue, double-check that you have the following set up:
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. This app will only have one Activity and it will be based on the Blank Activity template as shown below. Name the ActivityWeatherActivity. 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.
3. Add the Custom Font
Copy weathericons-regular-webfont.ttfto 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.
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.
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:
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:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
{
"base": "cmc stations",
"clouds": {
"all": 90
},
"cod": 200,
"coord": {
"lat": -35.28,
"lon": 149.13
},
"dt": 1404390600,
"id": 2172517,
"main": {
"humidity": 100,
"pressure": 1023,
"temp": -1,
"temp_max": -1,
"temp_min": -1
},
"name": "Canberra",
"sys": {
"country": "AU",
"message": 0.313,
"sunrise": 1404335563,
"sunset": 1404370965
},
"weather": [
{
"description": "overcast clouds",
"icon": "04n",
"id": 804,
"main": "Clouds"
}
],
"wind": {
"deg": 305.004,
"speed": 1.07
}
}
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:
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:
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.
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.
Log.e("SimpleWeather", "One or more fields not found in the JSON 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.
1
2
3
publicvoidchangeCity(String city){
updateWeatherData(city);
}
Advertisement
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.
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.
IPV6 OSPF Configuration on Gns3: This is the simple IPV6 tutorial for configuring IPV6 and OSPF for IPV6 on Gns3. You must enable IPV6 routing on router by using command “ipv6 unicast-routing”, all other command are same like normal IP configuration but just replace IP with IPV6 in all commands. I use the c7200 IOS for this lab. Configure the topology as below: R1 Configuration: R1(config)# ipv6 unicast-routing R1(config)# ipv6 router ospf 1 R1(config-router)# router-id 1.1.1.1 R1(config-router)# exit R1(config-if)# interface Loopback1 R1(config-if)# ipv6 address 2001:211:10:1::1/64 R1(config-if)# ipv6 ospf 1 area 0 R1(config-if)# interface Serial1/0 R1(config-if)# ipv6 address 2001:210:10:1::2/64 R1(config-if)# ipv6 ospf 1 area 0 R2 Configuration: R2(config)# ipv6 unicast-routing R2(config)# ipv6 router ospf 1 R2(config-router)# router-i...
I'm going to discuss how I like to implement a rope-swinging gameplay mechanic. When I started working on Energy Hook I mostly did everything with my own custom code. I believe it's possible to simply go into Unity and use the Configurable Joint to do some very similar stuff, but at the time it wasn't available. I'm pretty sure this has been the right call, anyway, because it gives me control over everything - and I can share it with you. The fundamentals of doing swinging the way I did - using constraints - are actually quite simple. (Hope you're not disappointed when you see what's under the hood.) It works the same whether you're making a 2D game or 3D game, it's just that the vectors are different, so I'll start off with 2D and then discuss some wrinkles when going to three dimensions. This article also assumes you're using a game engine like Unity that can do a lot of the work for you, like raycasting against geometry and orienting a chara...
In this tutorial, we are going to design a set of icons in Adobe Photoshop. An icon set needs to have the same background and theme. For learning purposes, we are going to design a sun icon, an ice flake icon, and an RSS icon. Let's get started. 1. Preparing the Canvas Step 1 Start by making a new file with size 350 px × 350 px . Click the small box next to the Background Contents option to change the new canvas color. Step 2 In the Color Picker dialog box, select grey ( #e0e0e2 ) for the canvas background color. Step 3 It is always a good idea to keep your work structured from the start. Make a new layer group and name it sun . This is where we will place all layers used in the sun icon. 2. Designing the Icon Base Step 1 Use the Rounded Rectangle Tool to draw a rectangle with size 83 px × 64 px and 8 px radius. To get accurate results, use the Properties panel. In this panel, you can simply enter the exact siz...
Comments
Post a Comment