Creating An Android Weather Forecast Application in The Android Studio

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

7th International Scientific Conference

Technics and Informatics in Education


Faculty of Technical Sciences, Čačak, Serbia, 25-27th May 2018

Session 3: Engineering Education and Practice UDC: 004.9

Creating an Android Weather Forecast


Application in the Android Studio
Slobodan Aleksandrov1*, Saša Vulović 2
1
College of Applied Mechanical and Technical Engineering Trstenik, Serbia
2
Webelinx, Niš, Srbija
*
[email protected]

Abstract: A large number of requests that can be made on a computer can now be realized on
smartphones or tablets. Because of their high hardware performance, mobility and low cost, smart mobile
devices take on the primacy of classical computers in many spheres of life. The smart mobile software
market is rapidly increasing, and the need for experts in this field is enormous. In this paper an analysis
of operating systems of mobile devices was performed, the most commonly used development
environment for application programming, and the process of development of weather forecast
application on the Android platform is shown.
Keywords: Android; Java; smartphones; application

1. INTRODUCTION officially supported. Within this work, Android


The development and application of information Studio 3.0.1 and Java programming language was
and communication technologies (ICT) brings used. When creating each application, it is
major changes in all segments of the society. necessary to create a new project first. Creating a
Expansion of the development of smart mobile new project takes place in a few simple steps.
devices at the beginning of the 21st century has When launching Android Studio, we should select
opened a new large software market, ranging the "Start a new Android Studio project" option
from the development of operating systems to the and assign the name for project, in this case it will
development of applications for various be "WeatherApp" (Figure 1).
applications. The leader in the mobile operating
system market is the Android platform with
74.23%, followed by the iOS platform with
20.84%, while all other mobile operating systems
have a negligible small market share ([1], March
2018). Various development environments are
used for programming mobile applications:
Figure 1. Development enviroment Android
Firebase, iOS SDK, Visual Studio, OutSystems,
Studio 3.0.1
Xcode, Fabric, Android Studio and others. It is
very important to define basic knowledge and In the next step, we choose for which type of
modern software packages necessary for the devices the application is going to be made:
development of software in the field of mobile mobile smartphones and tablets, smart watches or
devices. As the changes in Information televisions, as well as versions of the android
Technology (IT) are very fast, it is necessary that operating system (Figure 2). In the final step,
the school system at all levels is flexible and there is a possibility that the new project has pre-
modular, so it can quickly respond to the needs of defined dedicated screens, such as the Google
the economy and society. Maps screen, the Login screen, the Settings
screen, and etc.
2. DEVELOPING A MOBILE ANDROID
APPLICATION FOR WEATHER FORECAST
This paper presents the process of developing a
mobile android application for the weather
forecast. To create this application, the
development environment Android Studio, as well
as the Java programming language, was used. In
addition to Java, starting with Android Studio
3.0.0, the Kotlin programming language is Figure 2. Device and android version selection

285
Engineering Education and Practice Aleksandrov and Vulović

If no pre-defined screens are required, we select


"Empty Activity" option and assign name for the
activity, after which the process of creating a new
project is completed. Before the development of
application, it is necessary to get acquainted with
the basic components that are used when creating
android applications. These are "Activity",
"Service", "Broadcast Receiver" and "Content
Provider" [2]. Activity is one screen of the
application. It consists of two part, one is the xml
file, which represents the user interface, a screen
that is visible to the user. The second part is a
java class that responds to events when a user
interacts with the screen. Each multi-screen
application generally has different activity for each
screen. The service is similar to activity, with the
difference that it does not have an xml file and
serves to perform tasks in the background so that
the performance of the application would be
better. The selected service is executed on the
main thread, but with certain classes such as
"Handler" or "AsyncTask" the code executed in the Figure 3. The Activity Lifecycle [3]
service can be transferred to the background
thread. The service can be used to play music in it is restarted, the "onRestart()" method is called
the background, download data from the server, after which the "onStart()" method is immediately
etc. Broadcast receivers are used to reply to invoked. To create a weather app, we need one of
broadcast messages that are sent from other the services that provide information about the
activities or the android system itself. For current weather forecast for a specific location.
example, if an application needs to know if the There are various services that provide this
phone's screen is turned on or off, it can register information, some are free, some are commercial,
and listen to the messages sent by the system, in and there are also those that represent a
this particular case, the messages for combination of these two types, there are parts of
"SCREEN_ON" and "SCREEN_OFF" in order to get the information that are the free, and also the
the appropriate information. Content providers parts that is paid. During the implementation of
serve to obtain certain data and are mainly used this application, the service "Dark Sky" was used,
to communicate with the database. For example, which can be found at
using the content provider, we can get SMS https://darksky.net/forecast/40.7127,-
messages that are stored on the device or missed 74.0059/us12/en. The first step is to create an
calls. account on the site using email addresses and
Another important element in creating android passwords. After creating an account, the key that
applications is knowledge of the life cycle of the is necessary for obtaining information about the
activity. Each activity has its own life cycle and weather is obtained. The site provides details on
phases in that cycle. There are several stages in the information that can be obtained and how this
which an activity can be found and through the service works. Data is obtained as a json file.
predefined methods it informs the programmer in Figure 4 shows the process of obtaining a key.
which phase it is located. Figure 3 shows the life
cycle of the activity.
The "onCreate()" method is called when activity is
first created. In this method, the initialization of
the objects being used is mainly carried out. The
"onStart()" method is called when activity is first
visible to the user. When the "onResume()"
method is invoked, the user can interact with the
application. When the application switches to the Figure 4. Creating account for „Dark Sky“ service
background, the method "onPaused()" is called. When creating a new project, the activity for
The "onStop()" method is called when the application is automatically generated and it is
application is no longer visible to the user after called "Main Activity". As already mentioned, it
which either "onDestoy()" or "onRestart()" is consists of a java class called "Main Activity"
called. If the application is "killed" by the user or which inherits the "Activity" class and the xml file
system, the "onDestoy()" method is called, and if that will represent the user interface called

286
Engineering Education and Practice Aleksandrov and Vulović

"activity_main.xml". The next step in developing important that each component in the xml file has
this application is to create a user interface using its own unique id so the connection would be
the xml file and certain components such as successful. The same principle applies to
"TextView", "ImageView", and components that connecting other components, such as
allow the layout of components on the screen such ImageView. After this step, it is possible to
as "RelativeLayout" and "LinearLayout". These dynamically display text on the screen by simply
components can be added via xml file or via java calling the "setText (String s)" method using the
code in the java class. In this case, the TextView object. The "setImageResource
components are added directly to the xml file. As (Resourse id)" or "setImageBitmap (Bitmap bm)"
the names themselves suggest, "TextView" is can be used to set up images using the
used to display text, and "ImageView" to display ImageView object.
images. Each component serves to display certain In order to display the desired textual and
information on the screen. From the above, it is graphical data on the user interface, it is
necessary to add more "TextView" components necessary to load these data from the service on
that will be used to display the text and also which the user account is created. Information
weather information for the location for which we about current temperature, brief description of
search weather forecasts, the time of the last current weather conditions, pressure, humidity,
update, a brief description of the weather wind speed and direction data are required. To
forecast, the current temperature, as well as the obtain these data, an auxiliary class is created
humidity, pressure, wind speed and UV indexes. under the name "MyWeather". This class will
"ImageView" are used to display graphic elements contain all the information that is needed for
on the interface, such as background images, display on the screen. The object of this class is
graphics that represent the current weather initialized when the application receives a
situation and etc. The size and color of the text as response from server. Before communicating with
well as the size of the images are also defined in the server, it is necessary to determine the
the xml file. After adjusting and positioning the geographical length and width of the place where
components on the screen, we need to connect the user is located. To obtain these data, it is
the elements from the xml file with the java class, necessary to grant the appropriate permissions:
in order to be able to display the data that is "android.permission.ACCESS_FINE_LOCATION"
obtained, and also we need to implement the logic and
for collecting data from the server. It is important "android.permission.ACCESS_COARSE_LOCATION.
to note that each component added to the xml file Also, for the communication with the server, the"
must have its unique "id" so that it can be android.permission.INTERNET" permission is
connected to the java class. Figure 5 shows the required. After the granting this permission, using
created xml file. the "LocationManager" we can detect the current
geographic position of the user. The current
location information is obtained in the pre-defined
method "public void onLocationChanged (Location
location)" that passes the "Location" object. Using
"Location" object, we can get location information
and then the request is sent to the server to get
weather information. The request is sent via the
auxiliary AsyncTaskHelper class that inherits the
AsyncTask class. The reason for using the class
that inherits the AsyncTask class is that in this
way, the request will be sent to the server in a
Figure 5. Creating xml file background thread, so the main thread of the
After creating the interface, it is necessary to application is not affected. This class has its own
connect the xml file with the java class, as well as method "String doInBackground (Void ... voids)"
the components that are used in the xml file. within which the request is defined, and
When creating a new activity, the connection depending on the performance of this method, it
process of java classes and xml files takes place returns the corresponding string as a return
automatically by calling the "setContentView parameter. Sending requests is done by writing
(R.layout.activity_main)" method that is called in the following code:
the "onCreate()" method. The next step is to URL url;
connect a component from an xml file to a java HttpURLConnection urlConnection = null;
class by creating an object of the appropriate type try {
url = new URL(query);
and calling the "findViewById (int id)" method.
urlConnection = (HttpURLConnection)
Connecting a component for displaying text can url.openConnection();
take the following form: TextView txtTemperature
= findViewById (R.id.txtTemperature). It is

287
Engineering Education and Practice Aleksandrov and Vulović

BufferedReader r = new BufferedReader(new order to communicate with the activity, an


InputStreamReader(urlConnection.getInputStream() auxiliary interface has been created, which has
)); two methods, "onResultSuccess (MyWeather
StringBuilder total = new StringBuilder();
myWeather)" which is called if "OK" is received
String line;
while ((line = r.readLine()) != null) {
from the "doInBackground" as a return parameter.
total.append(line); In the event that the string "Error" is returned as
} the return parameter, the "onResultFailed ()"
ParseJSON(total.toString(),myWeather); method is used to inform the main activity that an
return "OK"; error has occurred. In the end, using
} "Populate(MyWeather myWeather)" method main
catch (Exception e) activity displays the data on the user interface.
{
The appearance of the user interface after
return "Error";
}
successful acceptance of data is shown in Figure
6.
Using "HttpURLConnection" and "URL", a request
is sent to a specific address, in this case it is the
address provided by the Dark Sky service, after
which desired data is received. Data is obtained in
the form of an json file and using the method
"ParseJSON(String data, MyWeather myWeather)"
we preform data parsing that is received from
server and at this point we initialize the
"MyWeather" object. The following code is created
for data parsing:
private void ParseJSON(String data,MyWeather
myWeather)
{
try {
JSONObject jsonObject = new
JSONObject(data);
JSONObject currentWeather =
jsonObject.getJSONObject("currently");
myWeather.setLastUpdate(currentWeather.getInt("t
ime"));
myWeather.setDescription(currentWeather.getStrin
g("summary"));
myWeather.setIcon(currentWeather.getString("icon"
));
myWeather.setTemperature(currentWeather.getDou
ble("temperature"));
myWeather.setHumidity(currentWeather.getDouble(
"humidity"));
myWeather.setPressure(currentWeather.getDouble(
"pressure"));
myWeather.setWindSpeed(currentWeather.getDoubl
e("windSpeed")); Figure 6. User interface for weather application
myWeather.setUvIndex(currentWeather.getDouble(" Below is a presentation of the "Populate" method,
uvIndex")); which displays the data:
} catch (Exception e) {
private void Populate(MyWeather myWeather)
e.printStackTrace();
{
}
txtCityName.setText(myWeather.getCityName());
}
txtLasUpdate.setText(myWeather.getLastUpdate());
If there is no error in communicating with the
server or during data parsing, the return txtDescription.setText(myWeather.getDescription())
parameter is string "OK", and if an error has ;
txtTemperature.setText(myWeather.getTemperatur
occurred, "Error" string is returned.
e() );
AsyncTaskHelper has another important method, txtHumidity.setText(myWeather.getHumidity() );
"onPostExecute (String s)" that is called when the txtPressure.setText(myWeather.getPressure());
"doInBackground" method is executed. This txtWindSpeed.setText(myWeather.getWindSpeed())
method is important because it reads the return ;
parameter that is sent from "doInBackground" txtUVIndex.setText(myWeather.getUVIndex());
method. If there were no errors, the main activity imgWeatherIcon.setImageResource(getResources().
is notified that new weather information has been getIdentifier(myWeather.getIcon(),"drawable",getPa
ckageName())); }
received and the user interface is refreshed. In

288
Engineering Education and Practice Aleksandrov and Vulović

3. CONCLUSION REFERENCES
The development of a modern information society [1] http://gs.statcounter.com/os-market-
must be based on the application of new ICT share/mobile/worldwide (15.03.2018.)
technologies. The use of smart mobile devices in [2] https://www.tutorialspoint.com/android/andro
all segments of society requires the development id_application_components.htm (16.03.2018.)
of new mobile applications. The global software [3] https://developer.android.com/guide/compon
ents/activities/activity-lifecycle.html
market in this area is growing at a tremendous
(16.03.2018.)
pace, so the need for education of IT specialists is
very high. This trend of the development of
modern technologies enables the rapid
development of the economy in the IT sector. Of
great importance is the advancement of the
educational system, which must be modular and
dynamic, so that it can quickly implement new
technologies into plans and programs in all of the
levels of education.

289

You might also like