1. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 1/19
Android developer blog
Android development tutorial that helps you to become an android developer
Surviving W/ Android
by Francesco Azzola,
Android Weather App Tutorial: Step By Step Guide (Part 2)
February 24, 2014
41 3Like
Topics covered
The app is available at google play. Download it and have fun. If you like my work
you can donate to me using the app.
In this post you will find a complete tutorial explaining how to build an Android app.
The goal of this post is creating a Weather App that will use Yahoo! Weather as
data provider. This post covers the most important aspects, we should consider
when building an app. It will explain how to use Yahoo! Weather API to retrieve
XML weather data and how to parse it to extract the information.
In the last post, we discovered how we can retrieve the woeid from the city name.
This information is very important because we can use it to get weather data. At
the end of this post you will create a full working app that looks like:
Android Weather App
Yahoo! Weather Client tutorial
XML Parser
Volley
Android app tuturial
Android Wear SDK: Set
up "Hello world"
Consume Webservice in
Android using
intentService
Android App tutorial:Peg
board game
Android Weather app
Tutorial: Step by Step
guide (Part 2)
Android Weather app
using Yahoo weather
provider and
AutoCompleteTextView
(Part 1)
Recent Posts Widget
by Helplogger
Recent Posts
My App on Google
Play
Follow SwA
Don't forget to +1
this blog, if you find
it useful!
216
SwA Repository
Android ListView – Tutorial and
Popular Posts
2. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 2/19
AUTO SWITCH
3 PORTE VIE
AUTOMATICO
HDMI HUB
FULL HD
1080P
VULTECH …
(23)
€13,99
basic example
Android ListView : Custom
Filter and Filterable interf ace
Android weather app: JSON,
HTTP and Openweathermap
Android HTTP Client: GET,
POST, Download, Upload,
Multipart Request
Android ListView : Custom
Adapter and Lay out
Android ListView with
SectionIndexer and f ast scroll
Professional Android 4
Application D...
Reto Meier
Best Price $19.98
or Buy New $26.09
Privacy Information
3. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 3/19
and is published on the market so that you can download it and play with it.
We want to create an app with two different areas:
Weather information
App Settings
The first area is where the app shows the current weather information retrieved using Yahoo! Weather API, while
the second area, called App Settings, is where we can configure our app, find the city woeid and the system
measure unit. The pictures below show how the settings area should be:
App Structure
4. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 4/19
As first step, we will create a preference activity, where an user can configure the weather app. In this case we can
create a class, called WeatherPreferenceActivitythat extends PreferenceActivity, and set preference layout:
To create the preference layout, we can use an XML file under /res/xmland we call it weather_prefs.xml. It looks
like the XML shown below:
You can notice we dived the setting screen in two different sections (there are two PreferenceScreen tag). At the line
2 to 7 we start another Activity as the user select this option because we have to give to the user the chance to
select the city name and resolve it in the woeid that we will use later. To start another activity inside a
PreferenceCategory we use an Intent, passing the package name and class name. The second section is used to
select the measure unit system, if the user uses °C that the system will be the metric system. It is a good practice to
show to the user the current values, so that in the onCreatemethod of WeatherPreferenceActivity we add these
lines of code:
1
2
3
4
5
6
7
8
9
10
publicclassWeatherPreferenceActivityextendsPreferenceActivity {
@Override
publicvoidonCreate(BundleBundle){
super.onCreate(Bundle);
getActionBar().setDisplayHomeAsUpEnabled(true);
Stringaction=getIntent().getAction();
addPreferencesFromResource(R.xml.weather_prefs);
...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategoryandroid:title="@string/loc_title">
<Preferenceandroid:title="@string/pref_location_title"
android:key="swa_loc">
<intentandroid:targetPackage="com.survivingwithandroid.weather"
android:targetClass="com.survivingwithandroid.weather.settings.CityFinderActivity"
/>
</Preference>
</PreferenceCategory>
<PreferenceCategoryandroid:title="@string/pref_unit_title">
<ListPreferenceandroid:key="swa_temp_unit"
android:title="@string/temp_title"
android:entryValues="@array/unit_values"
android:entries="@array/unit_names"
android:defaultValue="c"/>
</PreferenceCategory>
</PreferenceScreen>
1
2
3
4
5
SharedPreferencesprefs=PreferenceManager.getDefaultSharedPreferences(this);
//Wesetthecurrentvaluesinthedescription
PreferenceprefLocation=getPreferenceScreen().findPreference("swa_loc");
PreferenceprefTemp=getPreferenceScreen().findPreference("swa_temp_unit");
?
?
?
5. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 5/19
We used at line 1 the SharedPreference class to hold the app settings.
Now we have built the activity that enables users to configure the app, we can focus our attention on how to build the
client that retrieve the weather information using Yahoo! Weather client. We create a new class called YahooClient
where we will implement the logic to connect the remote server and retrieve the data.
The first step is creating the class structure that will hold the information we retrieve from XML received from the
remote server. This class structure maps somehow the XML received from the server, so we can suppose we have
something like the pic shown below:
The Weatherclass, is the class that will be returned and passed back to activity to display the information. We can
create a static method called getWeather that uses Volley lib to connect to the remote server. We have to create the
url that will be called:
Now we have the url we can implement the client:
6
7
8
9
prefLocation.setSummary(getResources().getText(R.string.summary_loc)+""+prefs.getString(
Stringunit= prefs.getString("swa_temp_unit",null)!=null?"°"+prefs.getString("swa_temp_unit"
prefTemp.setSummary(getResources().getText(R.string.summary_temp)+""+unit);
Yahoo! Weather Client
1 http://weather.yahooapis.com/forecastrss?w=woeid&u=unit
1
2
3
4
5
6
7
8
9
publicstaticvoidgetWeather(Stringwoeid,Stringunit,RequestQueuerq,finalWeatherClientListenerlistener){
Stringurl2Call=makeWeatherURL(woeid,unit);
Log.d("SwA","WeatherURL["+url2Call+"]");
finalWeatherresult=newWeather();
StringRequestreq=newStringRequest(Request.Method.GET,url2Call,newResponse.Listener<String>(){
@Override
publicvoidonResponse(Strings){
parseResponse(s,result);
listener.onWeatherResponse(result);
?
?
6. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 6/19
At line 5 we create the HTTP request, using GET method, and wait for response. As you already know (if not look at
this post explaining how to use Volley) we have two listener to implement one that handles the incoming response
and another one that handles errors that may occur. At the moment we want just to handle the response (see line
8,9), where first we parse the XML and then we notify the result the caller (line 9). We define our listener:
Finally, at line 18 we add the request to the queue.
Parsing XML is very simple, we have in input a String, that holds the XML, and we look for the tag we are interested
on, and create the our pojo (Weather) . The parser is shown below:
10
11
12
13
14
15
16
17
18
19
}
},newResponse.ErrorListener(){
@Override
publicvoidonErrorResponse(VolleyErrorvolleyError){
}
});
rq.add(req);
}
1
2
3
publicstaticinterfaceWeatherClientListener{
publicvoidonWeatherResponse(Weatherweather);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
privatestaticWeatherparseResponse(Stringresp,Weatherresult){
Log.d("SwA","Response["+resp+"]");
try{
XmlPullParserparser=XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(newStringReader(resp));
StringtagName=null;
StringcurrentTag=null;
intevent=parser.getEventType();
booleanisFirstDayForecast=true;
while(event!=XmlPullParser.END_DOCUMENT){
tagName=parser.getName();
if(event==XmlPullParser.START_TAG){
if(tagName.equals("yweather:wind")){
...
}
elseif(tagName.equals("yweather:atmosphere")){
...
}
elseif(tagName.equals("yweather:forecast")){
...
}
elseif(tagName.equals("yweather:condition")){
...
}
?
?
7. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 7/19
The next step is building the app navigation structure. We already know we have two activities: one that shows
current weather condition and another one used for app settings. We can use the well-know actionbar pattern to
handle navigation between these activities. We can create (if not exist) under /res/menu a file called main.xml. This
file will contain all the menu item we want to show to the user:
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
elseif(tagName.equals("yweather:units")){
...
}
elseif(tagName.equals("yweather:location")){
...
}
elseif(tagName.equals("image"))
currentTag="image";
elseif(tagName.equals("url")){
if(currentTag==null){
result.imageUrl=parser.getAttributeValue(null,"src");
}
}
elseif(tagName.equals("lastBuildDate")){
currentTag="update";
}
elseif(tagName.equals("yweather:astronomy")){
...
}
}
elseif(event==XmlPullParser.END_TAG){
if("image".equals(currentTag)){
currentTag=null;
}
}
elseif(event==XmlPullParser.TEXT){
if("update".equals(currentTag))
result.lastUpdate=parser.getText();
}
event=parser.next();
}
}
catch(Throwablet){
t.printStackTrace();
}
returnresult;
}
App Navigation And ActionBar
1
2
<menuxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
?
9. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 9/19
To provide Up Navigation, we add this line of code to onCreate method of WeatherPreferenceActivity:
At the same time, we want that when user selects a city in CityFinderActivity we come back to the preference screens
so we add :
The last step is setting up the layout of the MainActivity showing all the information we retrieved from remote server.
In this case we can define a simple layout that looks like the one shown below:
6
7
8
9
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
}
@Override
publicbooleanonOptionsItemSelected(MenuItemitem){
intid=item.getItemId();
if(id==R.id.action_settings){
Intenti=newIntent();
i.setClass(this,WeatherPreferenceActivity.class);
startActivity(i);
}
elseif(id==R.id.action_refresh){
refreshItem=item;
refreshData();
}
elseif(id==R.id.action_share){
StringplayStoreLink="https://play.google.com/store/apps/details?id="+
getPackageName();
Stringmsg=getResources().getString(R.string.share_msg)+playStoreLink;
IntentsendIntent=newIntent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,msg);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
elseif(id==R.id.action_donate){
SwABillingUtil.showDonateDialog(this,mHelper,this);
}
returnsuper.onOptionsItemSelected(item);
}
1 getActionBar().setDisplayHomeAsUpEnabled(true);
1 NavUtils.navigateUpFromSameTask(CityFinderActivity.this);
MainActivity And App Layout
?
?
14. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 14/19
This layout will be filled, at runtime, with the data extracted from XML.
Now in the MainActivity we simply call the YahooClient to retrieve data and coordinate the activities:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protectedvoidonCreate(BundlesavedInstanceState){
...
refreshData();
}
privatevoidrefreshData(){
if(prefs==null)
return;
Stringwoeid=prefs.getString("woeid",null);
if(woeid!=null){
Stringloc=prefs.getString("cityName",null)+","+prefs.getString("country",null);
Stringunit=prefs.getString("swa_temp_unit",null);
?
15. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 15/19
Etichette: android, android volley, android weather, app tutorial, xml, xml parser
In refreshData method we simply retrieve the app setting stored in SharedPreferences (see line 11,14,15) and at line
18 we invoke the YahooClient method getWeather to retrieve the data. We have to remember that we call the HTTP
URL in a background thread to avoid ANR problem, so we wait for the response using a listener (see line 20). When
we get the response we update the view. Finally at line 25, we retrieve the image related to the weather condition.
Source code available @ github
You might be interested on:
Android weather app: JSON, HTTP and Openweathermap
Android app development :weather app with forecast
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
handleProgressBar(true);
YahooClient.getWeather(woeid,unit,requestQueue,newYahooClient.WeatherClientListener(){
@Override
publicvoidonWeatherResponse(Weatherweather){
//Weupdatetheview
..
//Weretrievetheimage
IWeatherImageProviderprovider=newWeatherImageProvider();
provider.getImage(code,requestQueue,newIWeatherImageProvider.WeatherImageListener(){
@Override
publicvoidonImageReady(Bitmapimage){
weatherImage.setImageBitmap(image);
}
});
handleProgressBar(false);
}
});
}
}
1150 92Google + 2 0 362DZone 514Reddit
16. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 16/19
Android UML: Design an App – Part 1
2 comments • 8 months ago
survivingwithandroid — I agree with you. But in my
opinion storyboard models just a part not the
whole system. It is focused on the User …
Navigation drawer with account picker -
Google Drive SDK
3 comments • 10 months ago
Haider — Thanks for the reply. No worries, got it
resolved. I think it was a problem with my
dependencies and Google Play Service. Btw, …
Android Fragment transaction:
FragmentManager and Backstack
4 comments • a year ago
Sharon — What happens to the back stack on
rotate? Is it set to null?
Android Studio with android alternative
emulator:Genymotion
3 comments • 9 months ago
Maurice Parties — Android Studio doesn't "see"
any GenyMotion device when I try to run my
application (even if I have one running in VB)...
ALSO ON SURVIVING W/ ANDROID
2 Comments Surviving w/ Android Login
Sort by Best Share
Join the discussion…
• Reply •
walmyrcarvalho • a month ago
Great tutorial, thanks for sharing it!
1
• Reply •
James Baldwin • a month ago
Nice tutorial! Looking forward to building my own weather app
WHAT'S THIS?
Subscribe Add Disqus to your site
Favorite
Share ›
Share ›
18. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 18/19
Android Weather app Tutorial: Step by Step guide (...
Android Weather app using Yahoo weather provider a...
Repository organization and Surviving with Android...
► January (3)
► 2013 (32)
► 2012 (19)
Follow SwA by Email
Email address... Submit
Android ListView – Tutorial and basic example
Topics covered Android ListView SimpleAdapter ListView onClickListener
ListView menu context:ContextMenuInfo and AdpaterContextMen...
Android ListView : Custom Filter and Filterable interface
In the previous post we showed the way we can programming a custom adapter
and a custom layout. One aspect we didn’t cover by now, is how w...
Android weather app: JSON, HTTP and Openweathermap
Topics covered How to develop weather app HTTP connection JSON Parsing
Openweathermap API Check out my weather app on the play s...
Android HTTP Client: GET, POST, Download, Upload, Multipart Request
Topics covered HTTP connection Post request Download data Upload data
Multipart request Often Android apps have to exchange informati...
Android ListView : Custom Adapter and Layout
Topics covered Android ListView Array Adapter Custom layout Optimization:
View holder pattern In the last post , we talked about how ...
Android ListView with SectionIndexer and fast scroll
In this post i want to analyze how to use ListView with SectionIndexer enabling
the fast search. ListView has a method that enables the fa...
Add a sliding menu with animation to an Activity
Topics covered Android sliding menu Menu open close animation Activity with
sliding menu I was playing around with animation, layers an...
Popular Posts
19. 26/3/2014 Android Weather app Tutorial: Step byStep guide (Part 2) | Surviving w/ Android
http://www.survivingwithandroid.com/2014/02/android-weather-app-tutorial-step-by.html#more 19/19
Android SlidingPaneLayout: Tutorial
Topics covered Android SlidingPaneLayout SlidingPaneLayout and Fragments
Action bar In this post, we want to show how to use Slidi...
Fragment in Android: Tutorial with Example using WebView
In this post we want to explain how to use fragment in Android with a real
example . In the last post we talked about Fragment in Android...
Android ExpandableListView with Custom Adapter:
BaseExpandableListAdapter
Topics covered Android ExpandableListView BaseExpandableListAdapter
Custom adapter In the previous post we talked about ListView a...