This tutorial describe how developing an android app. This app is a weather app using openweathermap API. Topics covered:JSON, HTTP connection, AsyncTask
1. Android developer blog. Tutorial for android development that helps you to become an android developerAndroid developer blog. Tutorial for android development that helps you to become an android developer
Surviving W/ AndroidSurviving W/ Android
byJFrankie,
Android App Development :Weather App With Forecast
August 29, 2013
18 Like 6
Topics coveredTopics coveredThis tutorial will describe how to develop an android application. In this
tutorial we will explore what we need to create an android application
and what are the bricks we can use to create our app. As example we will
create a weather app. We talked about it some months ago, we will
develop the weather app with weather current condition and weather
forecast. To develop an android application we need at least:
An activity
a Layout
These are the basic component we can use. Of course we want to create some more complex because we
have to retrieve information from a remote server (in our case the openweathermap), and we have to parse
the result data. So we need to add to the basic components:
HTTP connection
AsyncTask (to not have ANR problems)
JSON parsing
Data model (that holds the JSON data)
At the end we will obtain:
The first step is creating the layout. As you can see from the image below our layout is divided in two
sections: one that holds the current weather condition and the other that holds the weather forecast. In the
weather forecast we have to move among different days so we can use a ViewPager. We can use in this
case a LinearLayout:
How to develop an android app
HTTP connection
JSON Parsing
Viewpager and fragment
APP LAYOUT
Follow SwA
123
MyApponGoogle Play
Android app development
:weather app with forecast
Android Detect Face
Android HTTP Client : Network
error and ConnectivityManager
Android UML : Design an App –
Part 2
Android UML: Design an App –
Part 1
Recent Posts Widget by
Helplogger
Recent Posts
Android ListView– Tutorial and basic
example
Android ListView: Custom Adapter
and Layout
Android ListView: Custom Filter and
Filterable interface
Add a sliding menu with animation to
an Activity
Android HTTP Client: GET, POST,
Download, Upload, Multipart
Request
Popular Posts
converted by Web2PDFConvert.com
2. Now we have our layout we can start working on each sections. In the first section (current weather) we can
use a RelativeLayout to place every widget at the right place:
In the second section, as we said we have to show several day forecast. In this case we can use a
ViewPager that helps us to swipe between pages, so we have:
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
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
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:layout_weight="1" >
<TextView
android:id="@+id/cityText"
style="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true">
</TextView>
<TextView
android:id="@+id/temp"
style="@style/tempStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cityText"
android:layout_centerHorizontal="true">
</TextView>
<TextView
android:id="@+id/unittemp"
android:layout_width="wrap_content"
style="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"
android:layout_below="@id/cityText"
android:layout_toRightOf="@id/temp"
android:layout_alignBaseline="@id/temp">
</TextView>
<TextView
android:id="@+id/skydesc"
android:layout_width="wrap_content"
style="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content"
android:layout_below="@id/temp"
android:layout_alignStart="@id/temp"
android:layout_toRightOf="@id/temp">
</TextView>
<!-- Image weather condition -->
<ImageView android:id="@+id/condIcon"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignTop="@id/temp"
android:layout_toRightOf="@id/temp"/>
</RelativeLayout>
1 <android.support.v4.view.ViewPager
?
?
converted by Web2PDFConvert.com
3. This is our layout. We have now to fill it we the weather data.
The next step is retrieve data using HTTP connection with an asynctask to avoid a ANR problem. Once we
have our data we will parse it using JSON parser. Let’s ask we our browser the weather forecast using this
link:
http://api.openweathermap.org/data/2.5/forecast/daily?q=Rome,IT&mode=json&units=metric&cnt=3
where cnt is the number of the days we want to have the weather condition. The result is shown below:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="6" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#E6E6E6"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
HTTP,ASYNCTASKAND JSON DATAPARSING
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
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
68
69
{
"cod": "200",
"message": 0.0192,
"city": {
"id": "3169070",
"name": "Rome",
"coord": {
"lon": 12.4958,
"lat": 41.903
},
"country": "Italy",
"population": 0
},
"cnt": 7,
"list": [
{
"dt": 1377774000,
"temp": {
"day": 26.83,
"min": 16.41,
"max": 29.12,
"night": 16.41,
"eve": 24.81,
"morn": 26.83
},
"pressure": 1007.2,
"humidity": 72,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "01d"
}
],
"speed": 0.71,
"deg": 146,
"clouds": 0
},
{
"dt": 1377860400,
"temp": {
"day": 29.84,
"min": 16.8,
"max": 29.84,
"night": 16.8,
"eve": 24.81,
"morn": 17.93
},
"pressure": 1006.68,
"humidity": 50,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "02d"
}
],
"speed": 2.2,
"deg": 235,
"clouds": 8
},
{
"dt": 1377946800,
"temp": {
"day": 29.14,
"min": 14.11,
"max": 29.14,
?
converted by Web2PDFConvert.com
5. Analyzing the result we find out that the information we are looking for are inside the list tag and this an
array. To hold this information we can create two classes on that hold the daily forecast and the other that
hold the daily forecast classes:
and the other one:
Now we have our data model and we have simply parse the JSON data using a simple class like the one
used in the previous post (JSONWeatherParser).
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"eve": 24.78,
"morn": 20.13
},
"pressure": 1017.2,
"humidity": 0,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "01d"
}
],
"speed": 1.91,
"deg": 252,
"clouds": 0
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class DayForecast {
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public Weather weather = new Weather();
public ForecastTemp forecastTemp = new ForecastTemp();
public long timestamp;
public class ForecastTemp {
public float day;
public float min;
public float max;
public float night;
public float eve;
public float morning;
}
public String getStringDate() {
return sdf.format(new Date(timestamp));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class WeatherForecast {
private List<DayForecast> daysForecast = new ArrayList<DayForecast>();
public void addForecast(DayForecast forecast) {
daysForecast.add(forecast);
System.out.println("Add forecast ["+forecast+"]");
}
public DayForecast getForecast(int dayNum) {
return daysForecast.get(dayNum);
}
}
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
28
29
30
31
32
33
public static WeatherForecast getForecastWeather(String data) throws JSONException {
WeatherForecast forecast = new WeatherForecast();
// We create out JSONObject from the data
JSONObject jObj = new JSONObject(data);
JSONArray jArr = jObj.getJSONArray("list"); // Here we have the forecast for every day
// We traverse all the array and parse the data
for (int i=0; i < jArr.length(); i++) {
JSONObject jDayForecast = jArr.getJSONObject(i);
// Now we have the json object so we can extract the data
DayForecast df = new DayForecast();
// We retrieve the timestamp (dt)
df.timestamp = jDayForecast.getLong("dt");
// Temp is an object
JSONObject jTempObj = jDayForecast.getJSONObject("temp");
df.forecastTemp.day = (float) jTempObj.getDouble("day");
df.forecastTemp.min = (float) jTempObj.getDouble("min");
df.forecastTemp.max = (float) jTempObj.getDouble("max");
df.forecastTemp.night = (float) jTempObj.getDouble("night");
df.forecastTemp.eve = (float) jTempObj.getDouble("eve");
df.forecastTemp.morning = (float) jTempObj.getDouble("morn");
// Pressure & Humidity
df.weather.currentCondition.setPressure((float) jDayForecast.getDouble("pressure"));
df.weather.currentCondition.setHumidity((float) jDayForecast.getDouble("humidity"));
?
?
?
converted by Web2PDFConvert.com
6. Well done! What do we need more?…Well we have to handle the ViewPager and create the adapter to hold
every day forecast.
The first thing we have to create our adapter that handles each fragment that shows the weather daily
details. In this case to create our adapter we have to extend FragmentPagerAdapter:
Two methods are important: one that “create” the fragment and another one that “create” the page title. The
first one instantiate a fragment that shows the daily forecat passing the dayForecast data and the other one
create the page tile using GregorianCalendar.
The last step is coding the fragment:
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// ...and now the weather
JSONArray jWeatherArr = jDayForecast.getJSONArray("weather");
JSONObject jWeatherObj = jWeatherArr.getJSONObject(0);
df.weather.currentCondition.setWeatherId(getInt("id", jWeatherObj));
df.weather.currentCondition.setDescr(getString("description", jWeatherObj));
df.weather.currentCondition.setCondition(getString("main", jWeatherObj));
df.weather.currentCondition.setIcon(getString("icon", jWeatherObj));
forecast.addForecast(df);
}
return forecast;
}
VIEWPAGER, FRAGMENTSAND THEADAPTER
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class DailyForecastPageAdapter extends FragmentPagerAdapter {
private int numDays;
private FragmentManager fm;
private WeatherForecast forecast;
private final static SimpleDateFormat sdf = new SimpleDateFormat("E, dd-MM");
public DailyForecastPageAdapter(int numDays, FragmentManager fm, WeatherForecast forecast) {
super(fm);
this.numDays = numDays;
this.fm = fm;
this.forecast = forecast;
}
// Page title
@Override
public CharSequence getPageTitle(int position) {
// We calculate the next days adding position to the current date
Date d = new Date();
Calendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(GregorianCalendar.DAY_OF_MONTH, position);
return sdf.format(gc.getTime());
}
@Override
public Fragment getItem(int num) {
DayForecast dayForecast = (DayForecast) forecast.getForecast(num);
DayForecastFragment f = new DayForecastFragment();
f.setForecast(dayForecast);
return f;
}
/*
* Number of the days we have the forecast
*/
@Override
public int getCount() {
return numDays;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class DayForecastFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dayforecast_fragment, container, false);
TextView tempView = (TextView) v.findViewById(R.id.tempForecast);
TextView descView = (TextView) v.findViewById(R.id.skydescForecast);
tempView.setText( (int) (dayForecast.forecastTemp.min - 275.15) + "-" + (int) (dayForecast.forecastTemp.max -
descView.setText(dayForecast.weather.currentCondition.getDescr());
iconWeather = (ImageView) v.findViewById(R.id.forCondIcon);
// Now we retrieve the weather icon
JSONIconWeatherTask task = new JSONIconWeatherTask();
task.execute(new String[]{dayForecast.weather.currentCondition.getIcon()});
return v;
}
...
}
?
?
converted by Web2PDFConvert.com
8. All Rights Reserved. Reproduction without explicit permission is prohibited.
Android Blog
Contact me
About Me
▼▼ 2013(25)
▼▼ August (3)
Android app development :weather app with forecast...
Android Detect Face
Android HTTP Client : Network error and Connectivi...
►► July (4)
►► June(4)
►► May (2)
►► April (4)
►► March(2)
►► February (3)
►► January (3)
►► 2012(19)
BlogArchive
Search
SearchThis Blog
Follow SwA
Follow SwAbyEmail
Email address... Submit
Android ListView – Tutorial and basic example
One of the UI component we use often is ListView, for
example when we need to show items in a vertical scrolling
list. One interesting asp...
Android ListView : CustomAdapter and Layout
Topics covered Android ListView Array Adapter Custom
layout Optimization: View holder pattern In the last post , we
talked about how ...
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...
Add a sliding menu with animation to anActivity
I was playing around with animation, layers and so on and i
have coded this simple sliding menu. The idea is very simple
when user touches t...
Android HTTP Client: GET, POST, Download, Upload,
Multipart Request
Topics covered HTTP connection Post request Download
data Upload data Multipart request OftenAndroid apps have
to exchange informati...
Android weather app: JSON, HTTP and Openweathermap
Topics covered How to develop weather app HTTP connection
JSON Parsing OpenweathermapAPI In this post I want to
describe how to creat...
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...
Android ExpandableListView with CustomAdapter:
BaseExpandableListAdapter
Topics covered Android ExpandableListView
BaseExpandableListAdapter Custom adapter In the previous
post we talked about ListView and ho...
Multi touch inAndroid : onTouchEvent example
In this post i want to analyse howAndroid handles the multitouch. Reading
some posts around the net i found that are a bit confusing and no...
Fragment inAndroid: 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 inAndroid...
Popular Posts
converted by Web2PDFConvert.com