SlideShare a Scribd company logo
1 of 8
Download to read offline
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
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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"night": 14.11,
"eve": 24.08,
"morn": 18.32
},
"pressure": 1005.17,
"humidity": 45,
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"speed": 1.56,
"deg": 320,
"clouds": 20
},
{
"dt": 1378033200,
"temp": {
"day": 28.43,
"min": 12.11,
"max": 28.95,
"night": 14.28,
"eve": 23.89,
"morn": 12.11
},
"pressure": 1005.23,
"humidity": 39,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "01d"
}
],
"speed": 1.55,
"deg": 289,
"clouds": 0
},
{
"dt": 1378119600,
"temp": {
"day": 29.83,
"min": 16.02,
"max": 29.83,
"night": 18.86,
"eve": 25.35,
"morn": 16.02
},
"pressure": 1006.57,
"humidity": 32,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "01d"
}
],
"speed": 3.3,
"deg": 292,
"clouds": 0
},
{
"dt": 1378206000,
"temp": {
"day": 27.76,
"min": 19.68,
"max": 27.76,
"night": 19.68,
"eve": 25,
"morn": 20.25
},
"pressure": 1014.89,
"humidity": 0,
"weather": [
{
"id": 800,
"main": "Clear",
"description": "sky is clear",
"icon": "01d"
}
],
"speed": 4.05,
"deg": 298,
"clouds": 0
},
{
"dt": 1378292400,
"temp": {
"day": 27.85,
"min": 19.91,
"max": 27.85,
"night": 19.91,
"eve": 24.78,
converted by Web2PDFConvert.com
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
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
Older
Post
Home
Subscribe to: Post Comments (Atom)
Etichette: android, app, http, json, viewpager, weather
In the onCreateView we inflate our layout and retrieve with (AsyncTask) the weather icon.
Source code available @github
1 comment
ALSO ONSURVIVING W/ ANDROID
Android Face Detect
1 comment • 13 days ago
Gabriel Pozoz — It's a topic on which there is not much written,
thanks!
Android Async ListView–JEE and RestFul
7 comments • 5 months ago
survivingwithandroid
Android ListView context menu: ActionMode.CallBack
1 comment • 5 months ago
pavan — very nice tutorial you can also check this …
Android HTTP Client: GET, POST, Download, Upload,
Multipart Request
4 comments • 4 months ago
Rajul Bhatnagar — It would be a lot more efficient to googles netwo
library Volley for these tasks.Its very easy to use to.
Leave a message...
BestBest CommunityCommunity
Reply
AndroidDev101
• 3 days
ago
Thank you so much, this is amazing!
Comment feedr Subscribe via email✉
Share ›
© 2012-2013 Survivingwithandroid.com Sitemap
312 57Google + 2 1 94DZone 128Reddit
converted by Web2PDFConvert.com
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

More Related Content

Recently uploaded

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Featured

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Featured (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

Developing android app tutorial: Weather app

  • 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
  • 4. 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 "night": 14.11, "eve": 24.08, "morn": 18.32 }, "pressure": 1005.17, "humidity": 45, "weather": [ { "id": 801, "main": "Clouds", "description": "few clouds", "icon": "02d" } ], "speed": 1.56, "deg": 320, "clouds": 20 }, { "dt": 1378033200, "temp": { "day": 28.43, "min": 12.11, "max": 28.95, "night": 14.28, "eve": 23.89, "morn": 12.11 }, "pressure": 1005.23, "humidity": 39, "weather": [ { "id": 800, "main": "Clear", "description": "sky is clear", "icon": "01d" } ], "speed": 1.55, "deg": 289, "clouds": 0 }, { "dt": 1378119600, "temp": { "day": 29.83, "min": 16.02, "max": 29.83, "night": 18.86, "eve": 25.35, "morn": 16.02 }, "pressure": 1006.57, "humidity": 32, "weather": [ { "id": 800, "main": "Clear", "description": "sky is clear", "icon": "01d" } ], "speed": 3.3, "deg": 292, "clouds": 0 }, { "dt": 1378206000, "temp": { "day": 27.76, "min": 19.68, "max": 27.76, "night": 19.68, "eve": 25, "morn": 20.25 }, "pressure": 1014.89, "humidity": 0, "weather": [ { "id": 800, "main": "Clear", "description": "sky is clear", "icon": "01d" } ], "speed": 4.05, "deg": 298, "clouds": 0 }, { "dt": 1378292400, "temp": { "day": 27.85, "min": 19.91, "max": 27.85, "night": 19.91, "eve": 24.78, 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
  • 7. Older Post Home Subscribe to: Post Comments (Atom) Etichette: android, app, http, json, viewpager, weather In the onCreateView we inflate our layout and retrieve with (AsyncTask) the weather icon. Source code available @github 1 comment ALSO ONSURVIVING W/ ANDROID Android Face Detect 1 comment • 13 days ago Gabriel Pozoz — It's a topic on which there is not much written, thanks! Android Async ListView–JEE and RestFul 7 comments • 5 months ago survivingwithandroid Android ListView context menu: ActionMode.CallBack 1 comment • 5 months ago pavan — very nice tutorial you can also check this … Android HTTP Client: GET, POST, Download, Upload, Multipart Request 4 comments • 4 months ago Rajul Bhatnagar — It would be a lot more efficient to googles netwo library Volley for these tasks.Its very easy to use to. Leave a message... BestBest CommunityCommunity Reply AndroidDev101 • 3 days ago Thank you so much, this is amazing! Comment feedr Subscribe via email✉ Share › © 2012-2013 Survivingwithandroid.com Sitemap 312 57Google + 2 1 94DZone 128Reddit 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