Mobile Application Development For Android Os

BABEȘ-BOLYAI UNIVERSITY CLUJ-NAPOCA

FACULTY OF MATHEMATICS AND COMPUTER SCIENCE

SPECIALIZATION COMPUTER SCIENCE

DIPLOMA THESIS

Mobile application development for

Android OS

Supervisor

Lecturer, PhD. Adrian Sterca

Author

Nistor Alexandra Denisa

2015

UNIVERSITATEA BABEȘ-BOLYAI CLUJ-NAPOCA

FACULTATEA DE MATEMATICǍ ȘI INFORMATICǍ

SPECIALIZAREA INFORMATICǍ ENGLEZǍ

LUCRARE DE LICENȚĂ

Dezvoltarea aplicațiilor mobile pe

Android OS

Conducător științific

Lector Dr. Adrian Sterca

Absolvent

Nistor Alexandra Denisa

2015

Table of Contents

Introduction 5

1. Introduction to Android Software Development 6

1.1 Application Fundamentals 6

1.1.1 Application Components 7

1.1.2 Storage Options 8

1.1.3 Networking 8

1.1.4 GPS 9

1.1.5 Phone Services 9

1.2 Compatibility 9

2. Android SDK 10 2.1 Android SDK Tools 10

2.1.1 Introduction to Android SDK 10

2.1.2 Virtual Device Tools 10

2.1.3 Development Tools 10

2.1.4 Debugging Tools 11

2.1.5 Build Tools 12

2.1.6 Image Tools 12

2.2 Platform Tools 12

3. Google API 13

3.1 Introduction to Google API 13

3.2 Google Maps API 13

3.2.1 Google Certificate and Google Maps API Key 13

3.2.2 The Map Object 14

3.2.3 Location Data 14

3.2.4 Maps Graphic Elements 15

4. Android and PHP 16

4.1 Introduction to PHP 16

4.2 PHP, MySQL and JSON 16

4.3 JSON requests with HttpUrlConnection 17

5. Cluj Conscious Meal Application 19

5.1 Introduction to the app 19

5.2 Specifications 35

5.3 Architecture and Design 39

5.4 Implementation 41

5.5 Utilization 44

6. Conclusion 45

References 46

Introduction

This work is based on the study and presentation of Android application development, with a focus on localization functionality with the help of Google Maps API.

Over time, Android applications became very popular and now have a massive user base and are available to a large audience, being easy to code and make it publicly available.

The originality of the application presented in this work lies in its functionality and dedication for a specific audience. The application is specially implemented for Cluj vegan or vegetarian citizens offering them the possibility to find the nearest restaurants with vegan/vegetarian meals, making available statistics and information about meals, as well as bringing people together to discuss and share ideas about vegetarian lifestyle.

The paper is divided into five chapters, each of them containing one or more subchapters with suggestive titles.

The first chapter is an introduction to the Android application development that aims to broadly describe the Android application fundamentals and capabilities.

The second chapter, Android SDK, presents the available tools that Android offers for developing rich applications.

The third chapter presents the Google API Services, focusing on the Google Maps API as it made use of in the application.

The forth chapter, Android and PHP, describes the communication between the application and the server component, highlighting the use of PHP, JSON and HttpUrlConnection.

The implemented application is described in the fifth chapter, highlighting its specifications, architecture and design, some important aspects of the implementation and the utilizations. This chapter provides diagrams and screenshots for a better understanding.

And finally we have the conclusion, which briefly illustrates the importance of this work.

1. Introduction to Android Software Development

The application fundamentals

1.1.1 Application components

Android applications are created for the Android operating system and are usually developed in Java programming language, using a rich and adaptive application framework provided by Android. An android application is usually formed of one or more components that can run individually. There are four types of components, each of them having its own specific role: Activity component, services component, the content provider and the broadcast receivers.

The first two mentioned components are used the most.

The building block of the user interface is the activity [1]. Basically, the activity is the equivalent of a desktop application window. They are independent from each other but an application usually has more than one activity that work together to form a well-defined and rich application and they usually provide user interface. An activity can be started from another activity using intents, which are also used to send information between two components.

One of the used activities in the application is declared as “main”, being the activity that it is first displayed when the user runs the app. When another activity is started, it gains user focus and the previous activity is stopped but it is preserved in the “back stack”, so when the back button is pressed, the previous activity restarts. An activity usually has a user interface with one or more views.

A view is a certain rectangle region upon within the screen, such as buttons, lists, text views, that can react to clicks or text inputs and so on. The first view (parent view) contained into any activity is the Layout view which specifies one of the three available layouts: grid layout, relative layout and linear layout.

As mentioned before, intents are elements used to switch from one activity to another. Not only that, but data transfer can also be possible using intents. There are two kinds of Android intents: implicit intents and explicit ones. The explicit intents are used when the activity that is navigate to is clearly defined as the Intent object’s parameter. The implicit intents, on the other hand, do not need to know the activity that needs to be started, but the action to be executed. For instance, if we want to send an e-mail, we set the intent’s action with Intent.SEND_ACTION and the system will automatically recognize the action and decide what activity is best to be used.

Sending data from one activity to another can be done using bundles which can hold all data types to numerous Parcelable types.

The content provider can be used for persistent local data storage in locations such as SQLite, servers, file systems or flat files. The application may query and modify the data, meaning more applications can access the same data, if the content provider allows it, based on URI.

SQLite is an open-source database and it is part of every Android device. SQLite allows operations such as creating and updating and supports text, integer and real data types, but doesn’t check if the columns contain the actual types. For instance you can input text into a column defined as integer.

The service is the component that runs in the background performing operations and does not give a user interface. A service can still run on the background even if one navigates to another application. The actions a service can perform include internet downloads, input and output operations, modifying content providers, playing music and so on.

A service can essentially take two forms: Started and Bounded [2]. A started service means that a component (for example activity) starts the service which does not have an outcome and can still be running after the component has stopped. This kind of service usually stops itself once it’s done.

A service is said to be bound when a component binds to it, meaning that they can interact with each other as server-client, send requests and get results. Unlike the started services, the bound service is stopped once the components unbind.

A broadcast receiver is a component that responds to system-wide broadcast announcements [3].

Basically, one application can initiate broadcast to make other applications aware of a data transfer, for example.

1.1.2 Storage options

Android provides the ability to store data for an application, whether if it is private or accessible to other applications. Static data such as small-sized text files or icons may be packed with the application. Other than that the storage options are vast: shared preferences, internal storage, external storage, and SQLite database and network connection.

Shared preferences storage method permits the user to store data in the form of key-value pairs, for example in an xml file. Once the application is uninstalled or the application data is cleared from the Android device, the data is lost.

Internal storage means storing data private to the application but not accessible to others. Once the application is uninstalled, the data is deleted.

External storage means storing data to a storage media such as an SD card. Data stored using this kind of storage method is accessible to any applications/users.

1.1.3 Networking

Android permits access to the internet (using Wi-Fi or a mobile network connection, for instance). To perform network operations such as sending or receiving data, a big part of Android applications use HTTP connection. The connection states are used to determine if the application is connected to the internet or the stage of which the connection is in. The connection states are the following: Connecting, Disconnecting, Connected, Disconnected, Suspended and Unknown.

There are two clients provided by Android for performing network operations: Apache HTTP client and HttpUrlConnection. The second one is known to be faster and consume less energy

An URLConnection for HTTP is used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is unknown in advance [4].

In order for the Android application to request web services, the INTERNET permission is required in the manifest file from the application.

Network operations can involve unpredictable delays [5]. For this reason, the UI and the network operations should be performed using different threads.

1.1.4 GPS

Android provides GPS service, making it possible to build applications that use maps to display a certain location.

1.1.5 Phone Services

Last but not least, as Android applications are mobile applications, they are able to provide phone services such as calling or text messaging.

1.2 Compatibility

The Android operating system may run on numerous types of devices such as smartphones, tablets and even televisions, providing the application with a grand number of users. In order for an application to actually be compatible with a variety of devices, it must follow certain rules regarding features and screen configurations. Applications can have restrictions regarding device compatibility: some apps are implemented to run only on certain devices; there are others that will only run in certain countries and finally, some applications require a minimum Android version in order to run.

2. Android SDK

2.1 Android SDK Tools

2.1.1 Introduction to Android SDK

The Android Software Development Kit represents a set of tools available for developing rich applications using the latest features available on Android platform. Each version of SDK is released by Google alongside of each new version of Android.

The Android SDK includes a variety of tools that help you develop mobile applications for the Android platform [3]. Some of the most significant tools that Android SDK carries include the Android SDK Manager, the AVD Manager and an emulator.

The Android SDK Manager is a component which contains all the necessary tools for developing Android applications, organized in packages and available for installation.

2.1.2 Virtual Device Tools

The AVD Manager is provided by the Android SDK in order to create and manage Virtual Devices. The Android Virtual Device emulator environment serves for testing the application on a device-like environment, without having to connect to a physical device. An AVD may imitate a number of features that physical devices carry: hardware features such as the presence of a camera, a specific type of keyboard or how much memory it has; design features are also available, including screen dimensions, appearance, etc.

The AVD provides a large number of device templates to test the application but it is important to choose the same or greater API level that the application requires.

The mksdcard is a tool that permits the simulation of an SD card in the emulator.

2.1.3 Development Tools

One of the most important development tools is ‘android’ as it allows the creation, removal and view of the ADV, managing projects and updating the SDK. The uses of android tool features from the command line are not necessary if the application is being developed in Eclipse or Android Studio IDE, since it is integrated.

The Hierarchy Viewer is used for optimizing the user interface as it provides a visual representation of the Layout View, allowing the developer to track hard-to-follow layout issues while building and debugging applications. The hierarchy viewer can be launched from the command line but it is also incorporated as a perspective into Eclipse IDE.

The lint tool’s purpose is to inspect the application and check for possible bugs and/or errors such as absent translations, layout execution, icon and usability issues, unused resources, incompatible array sizes and so on.

The Android SDK Manager is a tool which contains all the necessary components/tools for developing Android applications, organized in packages and available for installation.

The sqlite3 tool is useful for managing databases used by the Android applications and executes SQLite commands.

2.1.4 Debugging tools

As the title suggests, the Android debugging tools are useful for debugging Android applications. One of the most important tools available for this purpose is the ADB, which stands for Android Debug Bridge. The ADB allows the testing of applications on a physical device, as well as on an emulator. In the case of accidental bricking (“bricking” your Android device means that the software is rendered unusable), it allows you to restore the device in an instant, as well as push files to and from the device, reboot it, install and uninstall apps, create backups, and more [6]. The ADB is a 3-component tool: the client which runs on a laptop/computer or other development device; the server as a background process and a daemon running on the emulator or device on which the application is being tested. If the device is connected to the development machine over an USB, the use of ADB will only be successful if the USB debugging is enabled on the connected device.

The DDMS, which stands for Dalvik Debug Monitor Server, is the principal method for debugging Android applications as it provides features such as port-forwarding services, device print screen, logs and so on.

The Monitor Device is a stand-alone debugging and analysis tool which incorporates several other tools, some of them mentioned above: DDMS, Hierarchy Viewer, Systrace and Traceview.

The Systrace captures and presents execution time in order to analyze the performance of the application and Traceview is a debugging tool that graphically presents the execution logs that the application has saved.

2.1.5 Build Tools

The Build Tools is one of the Android SDK components necessary for implementing the application code and it needs to be updated regularly.

Opaque Binary Blob files are useful for providing extra resources for Android applications, resources such as graphics and sounds. The OBB files are obtained by using the JOBB build tool by building APK expansion files in the respective format. In order to use this tool the Android API level should be greater or equal to nine.

Other build tool include ProGuard used for optimizing code as it removes the unused parts and renames elements and zipalign used for aligning .apk files after being signed.

2.1.6 Image Tools

Image tools are used for user interface elements such as creating bitmaps using the Draw 9-patch tool, encoding and decoding PNG images to and from ETC1 compression using etc1tool and capturing frame by frame images with Tracer for OpenGL ES.

2.2 Platform Tools

The Android platform is Google Inc.'s open and free software stack that includes an operating system, middleware and also key applications for the use on mobile devices, including smartphones.[7]

Android SDK Platforms are regularly released and they support a type of processor architecture and contain Google APIs.

3. Google API

3.1 Introduction to Google API

API, an abbreviation of application program interface, is a set of routines, protocols, and tools for building software applications [8].

Google has developed a set of APIs which are used for services such as email, search, translation and maps. It permits communication with Google Services.

3.2 Google Maps API

The Google Maps API allows the use of maps into the Android application using the Google Maps data, meaning that the application may access the servers, download data and display maps. The maps support a large variety of features such as adding markers and polygons.

3.2.1 Google Certificate and Google Maps API Key

A Google Maps API Key is a forty-character string text that needs to be obtained in order to access the Google API Services from Google Developers Console for free.

In order to obtain a Google Maps API Key, a digital certificate needs to be linked to it, but more than one application with the same certificate can use the same key, although it is recommended that each application should have its own certificate , therefor its own API key.

The Maps API key is based on a short form of an application's digital certificate, known as its SHA-1 fingerprint [9]. The fingerprint, like the API key, is a unique text string used by Google API to identify one’s application.

There are two types of certificates: the Debug Certificate and the Release Certificate.

The Debug Certificate is usually generated by the SDK tools when the applications is being debugged/built. This is not the certificate that should be used to obtain an API key, as it is used with applications that are being tested and an application signed with a debug certificate, that has not been exported as released, should not be published.

The Release Certificate is the one generated when a release built has been made. This certificate’s SHA1 fingerprint is the one used to generate the API key.

The API key is passed to the Google API server which confirms registration and access to the Google Maps data, after the key has been placed into the application’s manifest file.

Further settings should be specified in the application’s manifest file besides the API key, such as a reference to the Google Services version and permissions to access Google Maps server.

3.2.2 The Map Object

As mentioned before, one may use Google maps in applications thanks to Google Maps API, which is either represented by a MapFragment or a MapView. The map tiles will automatically download and the displayed the map may be moved around and zoomed in or out.

Both MapFragments and MapViews act as a holder for the map; the difference between the fragments and views is that the fragment may be a portion of the user’s interface and can be combined with other fragments in the same activity, whereas the view takes the form of a rectangle of a part or the whole screen.

There are five types of maps offered by Google Maps API: Normal maps – containing natural elements and roads; Hybrid maps – containing satellite images and roads; Satellite maps – containing only satellite images; Terrain maps – containing topographic data; none – containing no tiles, displaying just an empty grid.

Apart from the map types, other features can be specified including camera position, zoom buttons and user gestures.

3.2.3 Location Data

One of the most outstanding features of Google Maps API is location data. Location data allows the ability to access the current location of the device, as well as the direction and movement method. There are three layers/interfaces that one may work with: My Location Layer, Google Play Services Location API and Location Source interface.

My Location layer can provide the user with the device’s current location. In order to use this layer, two permissions must be added to the manifest file of the application: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

The Google Play services Location API is richer in features. It includes the capability to determine the device’s current location, be aware of a location change and control the transportation method in case of movement.

3.2.4 Maps Graphic Elements

Markers are graphic elements that show locations on the map. Markers are customizable, being possible to change the default color or even replace the default icon, the position, anchor, title, visibility and so on, personalizing the application and defining a richer user experience.

Info Windows are popups attached to the markers making it possible to display a small piece of information about a certain location, once the marker is clicked.

For connection between two or more locations, Google Maps API provides us with map shapes. The shapes include polylines, polygons and circles. The difference between the three shapes is that the polylines are segments connecting two or more location, polygons also connects locations but they are closed-loop (defining an area this way) and circles are similar to polygons but they use a radius from a given center location.

4. Android and PHP

4.1 Introduction to PHP

The PHP language, short for Hypertext Preprocessor, is a simple, secure, efficient and flexible server-side scripting language used with dynamic content, databases and session tracking .It is an open source language, free to download and use and has become very popular in time, as it is a huge component of websites such as WordPress and Facebook.

PHP carries out a large number of functionalities, such as generating dynamic contents, creating, opening, reading, writing, deleting and closing files on a server, add, delete and modify data in a database and so on.

More advantages of using PHP include running it on a large number of platforms, as it is compatible with many servers and databases.

4.2 PHP, MySQL and JSON

As mentioned above, PHP will support any database but one of the most commonly used databases is MySQL.

MySQL is one of the most popular databases as it is free, fast, consistent, of a good quality and easy to operate with.

JSON, short for JavaScript Object Notation, is a format useful for exchanging and storing data.

JSON is formed of name-value pairs and an ordered list and it is more lightweight than XML.

PHP is used for connecting to MySQL database and it uses two functions:

1. mysql_connect which takes five optional parameters (server, user, password, new_link and client_flag) and returns a link identifier if the connection was successful or “false” if the connection failed. This function is used for opening a database connection.

2. mysql_close which returns “true” if the connection was closed successfully or “false” otherwise. This function is used for closing a database connection.

In order to create a MySQL database, having administrator privileges is necessary. The function to execute this functionality is mysql_query and it takes two parameters (the proper SQL query for creating a database and a connection). If the database was successfully created, the function returns “true”, otherwise it returns “false”.

Mysql_query is usually used for any database query such as inserting, deleting, retrieving and updating data.

The function mysql_fetch_array is used for retrieving data from the database and, if successful, returns the queried rows and echos the data into a JSON format.

4.3 JSON requests with HttpUrlConnection

As mentioned before, the UI and the network operations should be performed using different threads. This can be done using AsynkTask, which permits multi-threading, by running operations in the background and sending results to the UI.

For performing operations and retrieving data from the server AsynkHttpTask is used, then we have the doInBackground method which runs on a new thread that uses the HttpClient to retrieve the data. After it receives the response, it checks if it is successful, in which case it retrieves the content that is converted into string. After the doInBackground finishes its task, the onPostExecute method is called.

There are two methods to send requests and respond between a client and a server: the POST method and the GET method.

The GET method sends information appended to the page request [10]. The information is usually encoded using URL encoding. The GET method can be used to send data up to 1024 characters, but cannot be used to send binary data. It is not recommended to send sensitive information such as passwords using this type of method. Requests sent using the GET method are usually saved into the browser’s history, can be cached and bookmarked.

POST uses the message body to send the information.

Unlike GET method, POST method is more flexible in the sense that it can be used to send unlimited amount of information, as well as ASCII and binary data. Sensitive information can be sent using this method but only if Secure HTTP is used.

PHP uses $_GET, respectively $_POST associative array to gather information sent through GET and POST methods.

Other differences between POST and GET methods is when a back button is triggered: this does not affect information when using GET method, but data will be re-submitted if using POST method. Data appears to everyone in the URL when using GET method, and is not visible when using POST method.

JSON data can be handled using four classes provided by Android: JSONArray, JSONObject, JSONStringer and JSONTokenizer. The start of a JSONArray is shown by square bracket and the JSONObject is represented by the curly bracket in a JSON node. This helps decide whether to use getJSONArray or getJSONObject method, based on what bracket the JSON node begins with.

In order to make a service call the URL and the HTTP method are required. A new httpClient object is instantiated, parameters are appended to the URL if they exist and the client makes the request. If the request was successful, a JSON response is sent back from the server, ready to be parsed. A JSON Array, string, integer and other data types values are being retrieved from the JSON Object and looped through if necessary.

5. Cluj Conscious Meal Aplication

5.1 Introduction to the app

The Android application is dedicated to vegans and vegetarians that are living in or planning to travel to Cluj-Napoca. The application provides the user a list of all the vegan restaurants in town, or the restaurants that include vegan/vegetarian dishes on their menu, their address, information and rating. It makes use of Google Maps API so it can offer the ability to access the location of the selected restaurant as well as guidance from the current user’s location.

A user’s profile, diary and statistics are available in order to track meals and make sure he is staying fit and eating consciously.

The user profile contains his basic information needed for the application to track the number of calories and important nutrients in his diary, on a daily basis. The statistics offer graphical information about the nutrients over a selected period of time through interactive charts.

The application provides the user with a list of foods and recipes by default to which the user may add his own.

A discussion forum is also available for users to participate in to ask questions or share ideas.

In order to use the application, one must be registered. Lucky the app provides both a registration and a login screen.

In order for the application to run properly the device should have access to the internet through Wi-Fi or mobile network connection, have Google Services installed and GPS enabled for the map.

5.2 Specifications

A more detailed description will be given about the application’s functionalities. Use cases will be provided in order to view the possible interactions between the user and the application and diagrams to highlight the structure.

The application’s functionalities are:

User authentication and registration

Listing restaurants and finding their location

Updating user information

Creating diary entries

Displaying statistics

Displaying and adding comments in the discussion forum

Displaying food or recipe information

Creating a new food

Creating a new recipe

1. User authentication and registration

When the application is launched, the first screen will be the Login screen. From here the user has two options: he either logs in by entering his username and password and clicking the Login button if he has an account or he registers for one otherwise. The Login screen offers a link towards the Registration window which displays a text input for email, username and password, and a Registration button.

In case of the Login, if the username and password are valid, the user will be redirected to the main menu of the application. If the username doesn’t exist or the username and/or password are not valid, the user will be notified through a message on the same screen.

In case of the Registration, if the email and the username are not already in use, the user will be registered and redirected to the Login screen. Otherwise, the user will be notified through a message.

2. Listing restaurants and viewing their location

On the application’s main menu screen, the user may choose the option to display restaurants with vegan and/or vegetarian dishes available in Cluj-Napoca. He may choose from the list of restaurants to see further information such as a short description, address, phone number, rating and an interactive map. The application uses Google Maps API to display a map which provides a route to the current user’s location to the chosen restaurant. In order to access the map, the device the application is running on should have Google Services installed and also its GPS enabled.

3. Updating user information

The user profile’s information is usually empty by default for a new user. It contains the user’s name (username), age (years), height (cm), weight (kg), gender (female or male) and activity (sedentary, lightly active, moderately active, very active or extra active). The purpose for inputting this data is to calculate the user’s BMR (basal metabolic rate).

The BMR represents the minimum number of calories a human being needs to function properly for 24 hours (including breathing, keeping your heart beating and staying awake for the most part).It is computed with the following formula:

For women: 10 x weight + 6.25 x height – 5 x age + 5

For men: 10 x weight + 6.25 x height– 5 x age – 161

The user may modify his data anytime he wants and will click the Update button in order for the new data to be saved.

4. Create a diary entry

A user may keep a personal daily meals diary. The screen provides a dropdown to select a date (month and day), the default being the current date, a search input text for the user to search available recipes or foods to add to his diary and quantity. On the same screen, a statistic (using progress bars) of the energy and main nutrients is kept for that day. The energy is measured in kcal and the nutrients are carbohydrates, fats and proteins, measured in grams. The progress of the bars represents the number of kcals, respectively grams for nutrients the current user has consumed based on the added food and quantity to his list on that day.

Since the BMR only calculates the minimum number of needed calories when resting, it is necessary to know the number of calories needed to maintain weight based on the user’s activity mentioned in the user’s profile screen. When the progress bars are full, the user has reached the minimum requirements.

5. Displaying statistics

The statistics are represented by bar charts and are based on an interval of time and type of data.

The user chooses a period of time (for instance from 1st of May to 20th of June) and what kind of data to be displayed (energy, carbs, fat, protein or combined). After he has triggered the Update button, the interactive and colorful is chart is displayed, providing a legend and ignoring the dates in which the user’s diary has no data added to it. The chart is horizontally scrollable and can be zoomed in and out.

6. Displaying and adding comments in the discussion forum

The application offers interaction between users through a discussion forum. On the main screen of the forum the user can filter topics and select a topic in order to view the discussion on it. Once he is on a specific topic page, he may read and even post his own comment.

7. Displaying food or recipe information

The user can search for a food or recipe in order to view its nutritional information (in case of the food) and ingredients, quantity and preparation instruction (in case of the recipe).

While the user types in the name of a food or recipe, the application gives him hints, letting him know what foods and recipes are available for him to choose. The application cannot display information about foods or recipes that are not available in the database.

The nutritional facts (the number of carbohydrates, fats and proteins expressed in grams) are displayed using a Pie Chart, which also provides a legend and eventually a description.

8. Creating a new food

If the user is having a hard time searching for a food that doesn’t exist in the database, he may create it himself. He needs to insert the title and the nutritional facts. The food will be saved into the database and available for other users to view its information.

9. Creating a new recipe

The user may also create a new recipe, inserting its title, ingredients (which are the foods existent in the database), the quantity for each ingredient and the preparation instruction. Inserting nutritional information is not necessary as the application will calculate them based on the ingredients and quantities. Like in the case of foods, newly created and saved recipes can be accessed by users other than the creator.

Use Cases

Figure 5.2.1 – Use case diagram

Use case specifications

Use case: Register new account

Brief Description: This user case describes the process of registering a new account

Actors: User

Data: email, password, username

Preconditions: Username or Email should not exist in the database

Post conditions: Username registered

Basic Flows:

B1. Register

The user case begins when the user launches the app

The user presses the “Sign up now” button on the login screen

The system opens a new activity with a username, password and email text field and a “Register” and a “Log me in” button.

The user completes the necessary data for registration and clicks the “Register” button.

The system sends the input information to the server.

The server checks the database and sends back a response to the application system.

The system informs the user of a successful registration.

The use case ends.

Alternate Flows:

A1. Uncompleted text fields

In step 5 of the Register basic flow, the user leaves one or more text fields uncompleted, some information is therefore invalid.

The system informs the user with a brief on screen message.

A2. The username or email are already in use/ not available

In step 6 of the Register basic flow, the username and/or email that the user has entered are already registered.

1. The server sends response to the system.

2. The system informs the user of a failed registration through an on screen massage.

A3. The “Log me in” button is pressed

In step 3 of the Register basic flow, the user presses the “Log me in” button

1. The application redirects the user to the Login screen.

Use case: Login

Brief description: This use case describes the process of authentication.

Actor: User

Data: username and password

Precondition: Username should exist in the database

Post condition: User is logged in.

Basic flows:

B1. Login

The use case begins when the user launched the application

The application displays text fields for username and password, a “Login” and a “Sign me up” button.

The user enters the necessary information and clicks the “Login” button.

The system sends the input information to the server.

The server checks the database and returns a response to the application.

The system redirects the user to the main menu screen.

The use case ends.

Alternate flows:

A1. Uncompleted text fields

In step 4 of the Login basic flow, the user leaves one or more text fields uncompleted, some information is therefore invalid.

The system informs the user with a brief on screen message.

A2. Invalid username and/or password

In step 5 of the Login basic flow, the user input a username may not be registered or the password may be invalid

1. The system informs the user that the input username and/or password are incorrect.

A3. The “Sign me up” button is pressed

In step 3 of the Login basic flow, the user clicks the “Sign me up” button.

1. The application redirects the user to the Registration screen.

Use case: View restaurants’ information and location

Brief description: This use case describes the process of displaying restaurants information, as well as the location and route on the map.

Actor: User

Data: –

Precondition: The user is logged in, the device is connected to the internet and the GPS is enabled

Post condition: If the user chose a restaurant, the information about it is displayed

Basic Flows:

B1. View restaurants list and information

The use case begins after the user has logged in.

The main menu of the application is displayed by the system.

The user presses the “Restaurants” button.

The system sends a request to the server.

The server retrieves from the database and returns a response to the system.

The system displays the list of restaurants.

The user clicks on a restaurant name.

The system redirects the user to the Restaurant’s information activity screen, where the user can view the restaurant’s name, address, telephone, opening and closing hours, rating and a “Take me there” button to view the restaurant’s location.

The user clicks on the “Take me there” button.

The system redirects the user to the Maps activity screen, where a map of Cluj is displayed along with a marker on the restaurant’s location, a marker on the user’s current location and a route between the two.

The use case terminates.

Use case: Update profile information

Brief description: This use case describes the process of inserting/updating information about the user on his profile screen.

Actor: User

Data: CurrentUser, Age, Sex, Height, Weight, Activity

Precondition: The user is logged in

Post condition: The information has been updated, saved into the database and the BMR has been calculated and displayed

Basic flows:

B1. Update profile information

The use case begins after the user has logged in.

The main menu of the application is displayed by the system.

The user clicks on the “Profile” button.

The system redirects the user to the User’s Profile activity screen which contains the current user’s Username and BMR, text fields for age, height, weight, gender, activity and an “Update” button.

The user completes the required information and clicks the “Update” button.

The system sends request to the server.

The database is updated and the server sends response to the system.

The system calculates the BMR, updates it and displays it.

The use case terminates.

Alternate flows:

A1. Uncompleted text fields

In step 5 of the Update profile information basic flow, the user leaves one or more text fields uncompleted.

The system informs the user about the uncompleted text fields with a message.

A2. Incorrect data types

In step 5 of the Update profile information basic flow, the user inserts an incorrect type of data in one or more text fields. (For instance, he inputs a string text in the Weight text field instead of a real number).

The system informs the user about the incorrect inputs and clears the text from the problematic text fields.

Use case: Create diary entry

Brief description: The use case describes the process of creating a new diary entry for a certain day.

Actor: User

Data: Day, Month, Food/Recipe, Quantity

Preconditions: The user is logged in

Post conditions: The diary entry is added and the progress bars for energy, proteins, carbohydrates and fats are updated.

Basic flows:

B1. Create diary entry

The use case begins after the user has logged in.

The main menu is displayed in the application by the system.

The user clicks in the “Diary” button.

The system redirects the user to the Diary activity screen, which contains text fields for date day and month, food and quantity, a list of foods added to the diary on a certain day, progress bars to keep track of the quantity of calories, carbohydrates, protein and fats; it also contains a “Go to date” and an “Add food to diary” button.

The user selects a date and a day if necessary (the default is the current date) and clicks the “Go to date” button.

The system displays the food added for that day if any and updates the progress bars.

The user completes the food and quantity text field and clicks on the “Add food to diary” button.

The system makes a request to the server which creates a new diary entry in the database and sends a response to the system.

The system updates the foods list and the progress bars.

The use case terminates.

Alternate flows:

A1. One or more text fields are incomplete.

In step 7 of the Create diary entry basic flow, the user leaves one or more text fields uncompleted.

The system informs the user with an on screen message.

A2. Incorrect data types

In step 7 of the Create diary entry basic flow, the user inserts incorrect data into one or more text fields (For instance, he inserts a string text into the Quantity field instead of a real number).

The system informs the user with an on screen message and clears the incorrect data from the text fields.

A3. The user inserts food which doesn’t exist in the database.

In step 7 of the Create diary entry basic flow, the user inserts a food or recipe that doesn’t exist in the database (Normally, the food text field gives hints once the user starts typing).

The system informs the user and clears the incorrect data from the foods text field.

Use case: View meals statistics

Brief description: The use case describes the process of displaying statistics with data about energy and/or nutritional information.

Actor: User

Data: Type, Day, Month

Preconditions: The user is logged in

Post conditions: The chart is displayed

Basic flows:

B1. Display statistics

The use case begins after the user logged in.

The system redirects the user to the main menu of the application.

The user clicks on the “Statistics button”.

The system redirects the user to the Statistics activity screen which contains a dropdown for types of information (energy, carbohydrates, protein, fat or combined) , the time interval and an “Update” button.

The user selects a type and an interval and clicks the “Update” button.

The system displays the interactive bar chart (the user can view only the intervals that contain information; for instance it does not show the statistics for empty diary entries).

The use case terminates.

Use case: Display and search discussion forum topics

Brief description: The use case describes the process of displaying and searching topics in the discussion forum page.

Actors: User

Data: Topic Title

Preconditions: The user is logged in

Post conditions: The topics are displayed

Basic flows:

B1. Search and display discussion forum topics

The use case begins after the user has logged in.

The system redirects the user to the main menu activity screen.

The user clicks on the “Discussions” button.

The system redirects the user to the Discussions activity screen which contains a search text field and a list of available topics. By default, all topics are displayed.

The user may filter topics using the search text field and the system automatically updates the list as the user types.

The use case terminates

Use case: Post comment in forum

Brief description: The use case describes the process of posting a comment on a certain topic’s page

Actors: User

Data: CurrentUser, Comment, CurrentDate

Preconditions: The user must be logged in

Post conditions: The comment has been posted

Basic flows:

B1. Post comment in forum

The use case begins after the user has selected a topic title from the Discussion’s activity list of available topics.

The system redirects the user to the Posts activity screen, which contains the topic’s title, a list of comments if there are any, a comment text field and a “Post” button. Each post displays its author, the date and time it has been posted on and the comment.

The user inputs a comment in the text field and clicks the “Post” button.

The system updates the posts list, adding the newly created comment.

The use case terminates.

Alternate flows:

A1. Comment field text is empty

In step 3 in the Post comment in forum basic flow, the user attempts to post an empty comment.

The system alerts the user by displaying a message.

Use case: Display food or recipe information

Brief Description: The use case describes the process of searching and displaying information about food or recipe, using pie chart.

Actors: User

Data: Food/Recipe

Preconditions: The user is logged in

Post conditions: Pie chart is displayed and extra information in case of a recipe

Basic flows:

B1. Display food or recipe information

The use case begins after the user has logged in.

The system displays the main menu of the application.

The user clicks on the “Foods”/”Recipes” button.

The system redirects the user to the Foods/Recipes activity screen.

The user click on the “Search food”/”Search recipe” button.

The system redirects the user to the Search foods/recipes activity screen, which contains a search text field and a “Go” button.

The user searches for a food/recipe by entering name in the search text field and click on the “Go” button.

The system displays a pie chart representing the nutritional information about the selected food/recipe and the values of each one as description under the chart. In case of the recipe, it will also display the ingredients, quantity of each and the preparation instructions.

The use case ends.

Alternate flows:

A1. Search text field was not completed.

In step 7 in the Display food or recipe information basic flow, the user left the search text field empty.

The system informs the user by displaying an on screen message.

A2. No food/recipe found

In step 7 in the Display food or recipe information basic flow, the user attempted to search a food or recipe that is not available in the database.

1. The system informs the user by displaying an on screen message and clears the search field text.

Use case: Create new food

Brief description: The use case describes the process of creating and adding a new food to the database.

Actors: User

Data: FoodName, EnergyValue, CarbValue, FatValue, ProteinValue

Preconditions: The user is logged in

Post conditions: The newly created food is added to the database and available to other users.

Basic flows:

B1.Create new food

The use case begins after the user has clicked the “Create new food” in the Foods activity screen.

The system redirects the user to the Create new food activity screen, which contains text fields for food name, energy, carbs, protein and fat values, and a “Create” button.

The user completes all the necessary information and clicks the “Create” button.

The system sends a request to the server, which updates the database and sends a response to the system.

The system informs the user of the successful creation of the food by displaying an on screen message.

The use case terminates.

Alternate flows:

A1. One or more text fields are empty

In step 3 of the Create new food basic flow the user has left one or more text fields empty.

The system informs the user by displaying an on screen message.

A2. Entering the incorrect data

In step 3 of the Create new food basic flow the user has entered incorrect data in one or more text fields (For instance, he has input a text string into the Energy text field instead of a real number).

The system informs the user by displaying an on screen message and clears the incorrect text fields.

A3. Creating an already existent food

In step 3 of the Create new food basic flow the user attempts to create a food that is already existent in the database.

The system informs the user by displaying an on screen message and clears the food title text field.

Use case: Create new recipe

Brief description: The use case describes the process of creating and adding a new recipe to the database.

Actors: User

Data: RecipeTitle, Ingredient, Quantity, PreparationInstructions

Preconditions: The user is logged in

Post conditions: The newly created recipe is added to the database and available to other users.

Basic flows:

B1. Create new recipe

The use begins after the user has clicked the “Create new recipe” in the Recipes activity screen.

The system redirects the user to the Create recipe activity screen which contains text fields for recipe title, ingredient, quantity and preparation instruction, a list for the ingredients and two buttons: “Add ingredient” and “Create recipe”.

The user types in the ingredient and click the “Add ingredient” button.

The system adds the ingredient to the list.

The user adds another ingredient or adds the other necessary information and click on the “Create recipe” button.

The system calculates the energy and nutritional values based on the input ingredients and send a request to the system, which updates the database and sends a response to the system.

The system informs the user of a successful creation and clears all text fields.

The use case terminates.

Alternate flows:

A1. The ingredient or quantity text field is empty

In step 3 of the Create new recipe basic flow, the user leaves the ingredient text field empty.

The system informs the user by displaying an on screen message.

A2. The input ingredient does not exist in the database

In step 3 of the Create new recipe basic flow, the user inputs an ingredient which does not exist in the database (normally, the text field gives hints, letting the user know what is available while he is typing).

The system informs the user by displaying an on screen message and clears the ingredient text field.

A3. One or more text fields are empty (not including the ingredient and quantity text field)

In step 5 of the Create new recipe basic flow, the user leaves one or more text fields empty.

The system informs the user with an on screen message.

A4. Inputting incorrect data

In step 3 and 5 of the Create new recipe basic flow, the user inputs wrong data type in one or more text fields (For instance, he inputs a text string in the quantity text field instead of a real number).

The system informs the user with an on screen message and clears the incorrect data from the text fields.

5.3 Architecture and Design

“Cluj Conscious Meal” is a client-server available, which uses Apache server, MySQL database and PHP language to open and close the database, as well as insert, delete, update and retrieve data from the database.

In order to represent the application’s architecture and design, the following diagrams shall be illustrated along with explanations: package diagram, class diagram, deployment diagram and database diagram.

Package diagram

The package diagram represents the application’s packages. The application consists of three packages: com.ccm.activity, com.ccm.networking, com.ccm.model and com.ccm.maps.

The activity package contains all Android application activities use, each of them providing user interface. The maps package contains classes to perform tasks like gathering information to provide the user with a map and a route. Since the application is using client-server communication, the networking package is used to connect to the server, retrieve data and parse it using JSON. And finally, the model package contains entity classes.

Class diagram

The following class diagram describes the application’s classes regarding attributes, operations and relationships between them.

Due to a rich class diagram regarding the number of classes and relationships, some associations have been omitted for clarity purposes.

Deployment diagram

Figure 5.3.3 – Deployment diagram

The Android device holds the Android application the user uses and the Apache server, which provides a database and PHP support, is located on a Windows operating PC.

Database diagram

The database diagram’s purpose is to describe the structure of the tables and the relationship between them.

The relationship between foods and recipes is a many-to-many one therefor an intermediate table is needed. The relationship between topics and posts is one-to-many because one topic can have one or more posts (comments) and there is a one-to-many relationship between users and topics table because a user can open one or more topics on the discussion forum.

5.4 Implementation

The chapter will focus on describing the functionalities that application provides by showing and explaining important parts of the code: adding information to one’s profile, keeping a meal diary, searching for restaurants and finding their location, viewing information about foods and recipes and creating new ones for all the users to access, making use of statistics to keep track of consumed nutrients over a period of time and participating in forum discussions.

After the user has launched the app and logged in, he is redirected to the MainMenuActivity. This is the “root” of the “activities tree” as it starts all other activities by triggering buttons.

This activity also loads all the objects of type Food to be saved into an ArrayList and all the objects of type Recipe to be saved into a Hashmap.

The system retrieves the necessary data using a background thread. For example the retrieving of data about the foods is implemented in a class:

class LoadAllFoods extends AsyncTask<String, String, String>

In the Asynk method onPreExecute() we show a progress dialog and then the doInBackground methos is called and starts the thread. We get JSON string from the url.

If successful we get the array of foods and loop through it and store each JSON in a variable.

After completing the background task, the dialog is dismissed in Asynk’s onPostExecute method. The same goes for loading the recipes.

Managing user profile information

Adding and/or updating user information is done in the UsersProfileActivity class. After the Update button has been clicked, the data is saved into the database after the BMR (basal metabolic rate) has been computed in the calculateBMR method.

Managing and adding diary entries

Adding new diary entries on a day and viewing entries from a chosen day is done in the DiaryActivity class.

Not only that, but the caloric need is also computed in the calculateCaloricNeed method.

Searching and displaying food or recipe nutritional information

The representation of data through charts is done using the open source library MPAndroidChart. It offers a variety of diagrams including bar and pie chart (which has been made use of in the application), bubble, circle diagrams and so on.

The pie chart is used in the SearchFoodActivity as well as the SearchRecipeActivity to represent nutritional information about a certain food or recipe. The method used to implement and set data to the chart is setData that takes as argument an object of type Food.

Using statistics to represent nutritional intake over a period of time

Since MPAndroidChart library offer interactive and numerous types of chart, we make use of the bar chart to represent the quantity of energy/protein/carbohydrates/fat or a combination of all nutrients. The chart is initialized and “populated” with data in the StatisticsActivity class. We use two methods to set data: getDataSetForAll to represent all nutrients in a single chart or getDataSetForSpecific for a single type of nutrient.

Accesing the map and displaying restaurants location

For this functionality PathJSONParser, GetUserLocation and PathGoogleMapActivity. The code for the parse has been provided by Jeffrey Sambells and it is used for decoding polylines with Google Maps Direction API [9]. Putting this briefly, it helps construct the routes between two points (locations) on the map.

GetUserLocation class uses the getLocation method to provide the device’s current location. It checks if there exists a network connection and that the GPS is enabled. It requests location upates using and then gets the last known location of the device using the getLastKnownLocation method of the LocationManager.

The PathGoogleMapActivity retrieves longitude and latitude values from the database of a certain restaurant and provides a user interface with the map.

5.5 Utilization

The usage of the application will be provided in this chapter, together with screenshots for a better understanding.

When the application is launched, the login screen is displayed first and if the user doesn’t have an account and chooses to register, he clicks on the “Not a member? Register now” button.

Figure 5.5.1 – Login Figure 5.5.2 – Register

After the user has logged in, he is redirected to the main menu, which contains menu items in the form of buttons. The first item is “Profile” which opens the user’s profile page.

Figure 5.5.3 – Main Menu Figure 5.5.4 – User Profile

The user inputs his age, sex, height and how active he is and when he clicks the Update button, the application will calculate and automatically display the BMR value.

The second option in the main menu is “Diary”, which takes the user to his diary page where he may add new foods in a certain day or view a history of entries by choosing the date.

Figure 5.5.5 – Adding to diary Figure 5.5.6 – Added to diary list

After the user chooses a date, he clicks “Got to date” button; he then enters a food and quantity. .After he clicks the “Add food to diary” button, the list is updated and progress bars are updated (Figure 5.5.6).

The foods are recipes options are implemented the same. The user just types in the title and information about them will be displayed through a pie chart (Figure 5.5.7).

The statistics page also displays a bar chart (Figure 5.5.8) in order to represent meals nutritional information over a period of time. The user may select and interval and what type of nutrient he wants the chart to display the information for.

Figure 5.5.7 – Pie Chart Figure 5.5.8 – Bar Chart

In the Restaurants page, the user searches for a restaurant and chooses the “Take me there” button. The application will then display a map of two locations: the user’s current location and the restaurant’s location he has searched for.

Figure 5.5.9 – Map: route between two locations

In the Topics page, the user can filter the topics and then enter it and post a comment if he wishes. For this he clicks on a topic in the topics list and will be redirected to the Posts page where he can add a comment by typing in the comment text field and click the “Post” button.

Figure 5.5.10 – Before comment Figure 5.5.11 – After comment

After the user’s posted a comment, the list of posts will be automatically updated with the comment alongside with the user that has posted it and the date.

6. Conclusion

Living a healthy vegan or vegetarian style is not always easy and sometimes requires hard work to commit to it.

This paper has presented how this application tries to ease the user from Cluj into this kind of lifestyle. It offers both recipes to be cooked at home along with nutritional information for each ingredient, as well as locations to restaurants, which is especially useful for travellers.

Some people find it hard to commence eating animal-free meals; therefor the application also offered the ability to embark on this journey together with other consumers.

As with any application, improvements and updates are expected. Although our application reaches its goal, aspects such as functionalities, structure and user interface can be optimized.

The structure of the code can be improved as to make it clearer and easier to understand by other developers.

Further functionalities may be implemented such as registration confirmation through e-mail and/or phone texting, which offers more security, as well as the possibility to recover a forgotten username or password. Other possible functionalities can be the ability to view other user’s profile and add him as a friend, Facebook or other social websites integration and so on

Managing the UI can provide a richer user experience by adding images for example.

Another important aspect would be to provide accessibility for visually impaired people.

References

[1] Mark Murphy, Beginning Android 3, APress, 2011

[2]Android Developers, App Components, Services, http://developer.android.com/guide/components/services.html

[3] Android Developers, App Fundamentals, http://developer.android.com/guide/components/fundamentals.html

[4][5] Android Developers, HTTP Connection, http://developer.android.com/reference/java/net/HttpURLConnection.html

[6] Make Use Of, New To Android Debug Bridge? How To Make The Process Simple And Easy, http://www.makeuseof.com/tag/new-adb-make-process-simple-easy

[7] WeboPedia, Android Platform, http://www.webopedia.com/TERM/A/Android_platform.html

[8] WeboPedia, API – Application Programming Interface, http://www.webopedia.com/TERM/A/API.html

[9] Google Developers, Getting Started, https://developers.google.com/maps/documentation/android/start

[10] Tutorials Point, Get and Post Methods, http://www.tutorialspoint.com/php/php_get_post.htm

Similar Posts