You are on page 1of 55

TRIBHUVAN UNIVERSITY

Prime College
Nayabazar, Kathmandu, Nepal

A Project Report
On
“ROADBUDDY” – ANDRIOD APPLICATION

Submitted By
ADITYA SHRESTHA (5-2-0410-0175-2015)
ANUBHAV MAN SHAKYA (5-2-0410-0180-2015)
BIKESH SHRESTHA (5-2-0410-0191-2015)

A Project Report Submitted in partial fulfillment of the requirement of Bachelor of


Science in Computer Science & Information Technology (BSc.CSIT) 7th Semester of
Tribhuvan University, Nepal

August 9, 2019
ROADBUDDY
[CSC 404]

A project report submitted for the partial fulfillment of the requirement for the degree of
Bachelor of Science in Computer science & Information Technology awarded by
Tribhuvan University.

Submitted By

Aditya Shrestha (5-2-0410-0175-2015)


Anubhav man Shakya (5-2-0410-0180-2015)
Bikesh Shrestha (5-2-0410-0191-2015)

Submitted To

Prime College
Department of Computer science
Affiliated to Tribhuvan University
Khusibun, Nayabazar, Kathmandu

August, 2019

ii
Date: …………………….

SUPERVISOR’S RECOMMENDATION

It is my pleasure to recommend that a report on “ROADBUDDY” has been prepared under


my supervision by Aditya Shrestha, Anubhav Man Shakya and Bikesh Shrestha in
partial fulfillment of the requirement of the degree of Bachelor of Science in Computer
Science and Information Technology (BSc.CSIT). Their report is satisfactory to process
for the future evaluation.

…………………………………
Mr. Hiranya Pd. Bastakoti
Supervisor
Department of Computer Science & IT
Prime College

iii
CERTIFICATE OF APPROVAL

The undersigned certify that he has read and recommended to the Department of Computer
Science and Information Technology for acceptance of report entitled “ROADBUDDY”
submitted by Aditya Shrestha, Anubhav Man Shakya, Bikesh Shrestha in partial
fulfillment for the degree of Bachelor of Science in Computer Science and Information
Technology (BSc.CSIT), Institute of Science and Technology, Tribhuvan University.

………………………………. ……………………………
Mr. Bikram Acharya, PhD Ms. Dikshya Singh

Head of Department Program Coordinator

……………………… ………………………

Mr. …………………… Mr./Ms.…………….......

External Examiner Internal Supervisor

iv
ACKNOWLEDGEMENT

We would like to express our deepest appreciation to all those who provided us the
possibility to complete this report. A special gratitude we give to our final year project
Supervisor, Mr. Hiranya Pd. Bastakoti, in whose contribution stimulating suggestions
and encouragement, helped us to coordinate our project especially in writing this report.
Furthermore, we would also like to acknowledge with much appreciation the crucial role
of the staff of Prime College, who gave the permission to use all required equipment and
the necessary materials to complete the task. We are thankful and fortunate enough to get
constant support from our seniors and every teaching staff of B.Sc. CSIT department which
helped us successfully complete our project. We would also like to extend our regards to
all the non-teaching staff of B.Sc. CSIT department for their timely support. We have to
appreciate the guidance given by other supervisor as well as the panels especially in our
project presentation that has improved our presentation skills thanks to their comment and
advices. Our thanks and appreciations also go to each and every one of our colleagues for
their encouragement and support in developing the project.

With respect,

Aditya Shrestha (5-2-0410-0175-2015)


Anubhav Man Shakya (5-2-0410-0180-2015)
Bikesh Shrestha (5-2-0410-0191-2015)

v
ABSTRACT

Traffic has always been a huge problem in the lives of the residents of Kathmandu valley.
People often find themselves being caught amidst congested traffic conditions worsened
by the road structures and to be able to use an application, to help them outsmart those
problems would be of great help. RoadBuddy is a map-based, real-time, traffic navigation
application designed to outsmart traffic, not to control it. Developed to run on the android
platform, this application operates in real time and updates the map, which is connected to
s database, which is also maintained in real time. The updates to the map are simply sent
by the user, regarding road conditions, which can be referred to by other users of the
application. Crowdsourcing is used for the purpose of collecting the data from the users,
which is in the form of geospatial data i.e. data that identifies the geographic location of
features and boundaries of the Earth, which may be either natural or constructed. Apart
from supporting these features, RoadBuddy also provides the user with turn-by-turn
navigation of a user’s route to the destination, which can also be narrated by the inbuilt
voiceover instructions. RoadBuddy is considered a community-based navigation app
because it promotes the idea of social navigation and it is based upon the power of the
people, meaning that it completely depends upon how users pass information within the
app.

KEYWORDS: traffic, real-time, navigation, crowdsourcing, geospatial data

vi
TABLE OF CONTENTS

COVER PAGE ................................................................................................................................ i


TITLE PAGE ................................................................................................................................. ii
SUPERVISOR’S RECOMMENDATION.................................................................................. iii
CERTIFICATE OF APPROVAL ............................................................................................... iv
ACKNOWLEDGEMENT ............................................................................................................. v
ABSTRACT ................................................................................................................................... vi
TABLE OF CONTENTS.............................................................................................................vii
LIST OF FIGURES .......................................................................................................................ix
LIST OF TABLES ......................................................................................................................... x
LIST OF ABBREVIATIONS .......................................................................................................xi
CHAPTER 1. INTRODUCTION.............................................................................................. 1
1.1. Background .................................................................................................................... 1
1.2. Problem Definition ......................................................................................................... 2
1.3. Objectives........................................................................................................................ 3
1.4. Scope ............................................................................................................................... 3
1.5. Limitations ...................................................................................................................... 4
CHAPTER 2. REQUIREMENT ANALYSIS AND FEASIBILITY ANALYSIS ................ 5
2.1. Literature Review .......................................................................................................... 5
2.1.1. Study of Previous Literature (Previous academic literature) ...................................... 5
2.1.2. Study of Existing system .................................................................................................. 6
2.2. Requirement Collection Methods ................................................................................. 7
2.2.1 Sources of Data ....................................................................................................... 7
2.3. Requirement Specification ............................................................................................ 7
2.3.1 Functional Requirement ........................................................................................ 7
2.3.2 Non-Functional Requirement ............................................................................. 10
2.4. Feasibility study ........................................................................................................... 10
2.4.1. Technical feasibility ............................................................................................. 10
2.4.2. Operational feasibility ......................................................................................... 11
2.4.3. Economic feasibility ............................................................................................. 11
2.4.4. Schedule Feasibility ............................................................................................. 12
2.5. Structuring System Requirements ............................................................................. 13
2.5.1. Process Modeling (DFD Level-0 and Level-1) ................................................... 13

vii
CHAPTER 3. SYSTEM DESIGN ........................................................................................... 15
3.1. System Architecture and Overview ............................................................................ 15
3.1.1. Database Schema ................................................................................................. 16
3.2. Algorithms Used ........................................................................................................... 17
3.2.1. Multi-Parameter Dijkstra’s Algorithm .............................................................. 17
3.3. UML Diagrams............................................................................................................. 18
3.3.1. Class Diagram ...................................................................................................... 18
3.3.2. Sequence Diagram ............................................................................................... 19
3.3.3. Activity Diagram .................................................................................................. 21
CHAPTER 4. SYSTEM IMPLEMENTATION AND TESTING ........................................ 23
4.1. Implementation Overview ........................................................................................... 23
4.2. Tools Used ..................................................................................................................... 23
4.2.1. Front End Tools ................................................................................................... 23
4.2.2. Back End Tool ...................................................................................................... 24
4.3. Modules Description .................................................................................................... 24
4.4. Testing ........................................................................................................................... 26
4.4.1. Unit Testing .......................................................................................................... 26
4.4.2. System Testing ...................................................................................................... 28
CHAPTER 5. CONCLUSION ................................................................................................ 29
5.1. Conclusion .................................................................................................................... 29
5.2. Recommendation.......................................................................................................... 29
BIBILOGRAPHY ........................................................................................................................ 31
APPENDIX-1 ............................................................................................................................... 32
(Screenshots)............................................................................................................................. 32
Appendix-2 ............................................................................................................................... 35
(Codes) ...................................................................................................................................... 35

viii
LIST OF FIGURES

Figure: 1 Use case for user registration .............................................................................. 8


Figure: 2 Use case for user login ........................................................................................ 8
Figure: 3 Use case for updating traffic data ........................................................................ 9
Figure: 4 Use case for navigation ....................................................................................... 9
Figure: 5 Context level diagram ....................................................................................... 13
Figure: 6 DFD level-1 diagram ......................................................................................... 14
Figure: 7 System architecture ........................................................................................... 15
Figure: 8 Database schema ............................................................................................... 16
Figure: 9 Class Diagram ................................................................................................... 18
Figure: 10 Sequence diagram for updating data ............................................................... 19
Figure: 11 Sequence diagram for navigation .................................................................... 20
Figure: 12 Activity diagram .............................................................................................. 21

ix
LIST OF TABLES

Table 1: Gantt chart .................................................................................................... 12


Table 2: Test case for installation ............................................................................... 26
Table 3: Test case for Application Login ................................................................... 26
Table 4: Test case for Navigation ............................................................................... 27
Table 5: Test case for Traffic report ........................................................................... 27
Table 6: System Testing.............................................................................................. 28

x
LIST OF ABBREVIATIONS

API - Application Programming Interface

BAAS - Backend as a Service

DFD - Data Flow Diagram

iOS - iPhone Operating System

JSON - JavaScript Object Notation

MPD - Multi-Parameter Dijkstra’s Algorithm

NoSQL - Not Only SQL

SDK – Software Development Kit

SQL - Structured Query Language

UI - User Interface

UML - Unified Modelling Language

UX - User Experience

xi
CHAPTER 1. INTRODUCTION

1.1. Background

Traffic congestion, colloquially referred to as traffic jam, is a common problem to all major
cities of the world. Kathmandu city, the largest urban agglomeration within the valley, and
its residents, are no stranger to traffic congestion and the problems brought forward by it.
From the time the first car was introduced to Kathmandu, the city has witnessed a rapid
increase in the number of vehicles, with the numbers progressing as the years pass by.

Such is the capacity of the road networks inside the city that they simply do not support
the pressure of the traffic, especially during rush hours, which results to a state of
unmanageable chaos, which only worsens as the vehicles keep adding. Although it may
seem as if increasing the capacity of the road networks might straightforwardly solve the
problem, this solution would take a considerable amount of time and financial resources,
backed up by ecological and political aspects concerned to it. On the contrary, a viable
solution would be to optimize the use of available technology in such a way that the public
is able to decide for themselves the best route for getting to their destination.

The project RoadBuddy is a community-based traffic navigation application for the android
platform that enables users to get to their destinations referring to updates made by other
users travelling on the same route. The aim of this application is not to control or regulate
traffic, but to provide a modern approach to outsmarting it, that is made possible via
geolocation, which is the estimation of the geographic location of a real-world object like
a mobile phone or an internet-connected terminal, using digital information.

The application features two types of users, namely commuters and contributors.
Commuters are the users who login to the application in order to select a route to get to
their destination. Contributors are the users who update specific points in a route. The
changes in a route, marked by the contributors can be for a traffic jam, road construction
or any other traffic related problem. Commuters refer to the map routes updated by the

1
Contributors, based on the number of contributors who have updated a certain part of a
route. Contributors are awarded points for making updates to a route. Commuters can be
contributors when they update a certain route in the map and in the same way, contributors
can be commuters when they have to reach their destination and refer to the map on their
personal devices. Other than the above-mentioned features, the application suggests a user
with the best route to reach a destination, considering the distance and other traffic related
parameters. The application majorly depends upon community-based navigation with the
sole belief that traffic problems are not personal to an individual, but a problem of the
masses and cannot be controlled, but outsmarted.

1.2. Problem Definition

Traffic congestion is a condition on transport networks that occurs as use increases, and is
characterized by slower speeds, longer trip times, and increased vehicular queueing. When
traffic demand is great enough that the interaction between vehicles slows the speed of the
traffic stream, this results in some congestion. As demand approaches the capacity of
extreme traffic congestion sets in. When vehicles are fully stopped for periods of time, this
is colloquially known as a traffic jam. Traffic congestion can lead to drivers becoming
frustrated and engaging in road rage.

Traffic jams due to congestion happen anytime and anywhere, without the permission or
knowing of anyone. This inevitable nature of traffic jam makes things complicated for
commuters who want to travel small distances or routes within the city.

The residents of Kathmandu are no stranger to traffic related problems. Be it a traffic jam
from congestion, accidents or the never-ending road construction projects, traffic problems
occur in all and every major street of Kathmandu valley. Also, a problem that has recently
surfaced the streets of Kathmandu is the arrival of VIP personnel, which has been bothering
commuters on the daily.

Another issue regarding traffic are the road construction projects that are being conducted
in random fashion inside the valley. People are unaware of the roads which are under

2
construction and try to reach their destination through such roads. In such cases, those roads
are not fit to be traveled upon and people either get stuck in another traffic jam or have to
travel through the ill-managed polluted road.

Going through all of these problems the project RoadBuddy is an application that gives an
idea to commuters about the ongoing traffic conditions of the route through which they
have to travel and help them find an alternate route to their destination.

1.3. Objectives

This project aims to meet the following objectives:

 To provide commuters with a system that uses geolocation for estimation of the
geographic location of a real-world object/entity/event
 To provide commuters with the shortest route to their destination
 To provide beforehand information to the commuters so that they are updated about
the ongoing road conditions in their route
 To suggest an alternative route to the commuters in case of any traffic problem

1.4. Scope

The application registers users using their citizenship, which means any resident of
Kathmandu, with a citizenship is able to use the application. The system is not limited to
the type of vehicle owned by a commuter and it is definitely not compulsory that the
commuter own a vehicle at all. The application can be used by pedestrians as well to mark
any point in a route that has some kind of traffic disturbances. It means that a person on
foot, can be a contributor to a commuter on a vehicle, if they choose to update the map
about a certain traffic problem. This in return rewards the individual with points, which

3
although have no monetary value, but are a way to perform the simplest form of community
service.

However, this doesn’t mean that the system cannot be used for simple route tracing for
someone who wants to get somewhere

1.5. Limitations

The limitations of this project can be listed out as follows:

 The nature of the traffic jam is unpredictable


 Users who are stuck in a traffic jam may not update the conditions of a certain route
at all
 Faulty updates of a route, which cannot be verified
 No form of remuneration whatsoever, which may discourage commuters to use the
application at all

4
CHAPTER 2. REQUIREMENT ANALYSIS AND
FEASIBILITY ANALYSIS
2.1. Literature Review

2.1.1. Study of Previous Literature (Previous academic literature)

Community based navigation is a technique by the use of which commuters work together
to improve each other’s driving experiences. The use of this technique helps to share real-
time information about traffic conditions, road structures, accidents etc.
A research article on the famous “social-navigation” platform, Waze has stated that
spontaneity and playfulness are vital factors that affect driving dynamics. By allowing the
users to interact with an interface which covers general, social practices, authors have made
the claim that experience of driving was slipping into our technological unconscious [1].

Waze app has an innovation that allows users to update the map, so that the information
obtained has greater accuracy and can shorten the distance. In contrast to other navigation
applications, application Waze is a social community-based navigation application. Waze
app connects users to be able to interact and share information on traffic conditions
around so the information obtained is actual and accurate. The more people use Waze
application as an application navigation while driving of course the more accurate the
information obtained [2].

However, another study has stated that the intensive use of smartphones and other mobile
devices generates a significant volume of data, since wherever people go their trajectories
can be recorded, and there are many ways for them to express themselves on the visited
places [3]

Altogether, every person in the country is immensely affected by the transportation


management and has a hand in it one way or the other. By transportation management in
the valley, basically means the proper organization in the road transportation system. This

5
would basically include public’s participation in the making of the road more economical,
sustainable, and organized that will benefit people for their livelihood [4].

2.1.2. Study of Existing system

Traffic navigation is a problem domain in which a lot of work has been done previously
by renowned companies. The tech giant, Google, with its famous Google Maps application
has definitely been on the top of navigation over the last couple of years. [Google Maps
has over 154 million US users, more than six times the amount of Apple Maps users. Most
but not all of these users use Google Maps in their smartphones. Even among iOS users,
Google Maps is the preferred map app [5].

Especially, with Google purchasing the Israeli map app Waze, in the year 2013, huge
contributions to Google traffic data have been made. Other popular mobile-based
navigation apps include MapQuest, OsmAnd, HERE WeGo Maps, and Maps.me.
Although the mentioned apps do a respectable job when it comes to step-by-step
navigation, and some do even account for congestion information, Waze has a different
approach to traffic navigation.
Waze, which is a community-based traffic navigation app is powered by the masses,
meaning that it relies on the data provided by the users of the app, who are referred to as
Wazers. Real time information is gathered from the users, that translates into factors like
traffic conditions, road structures, accidents, weather conditions and much more, which is
in turn actively reported to the community after immediate analysis so that other users are
provided with optimal routes and related information, whenever required. Rather secretive
when it comes to the algorithms used, Waze has optimized conventional routing algorithms
according to their use.

Another powerful instance of mobile navigation is the Naver Map, which only works in
Korea, and nowhere else in the world, does not only support navigation, but can also be
used to check bus timings, check which bus stop all the buses are currently at, estimate the
cost of taking a taxi to a destination, finding out the cost of using public transport.

6
Mentioned above, are a few fine cases of mobile-based navigation, popularized over
international platforms, with a tremendously gigantic user base and a data collection
strategy of the same caliber. However, RoadBuddy is targeted only towards the Nepalese
audience, and that too, for residents of Kathmandu city.

2.2. Requirement Collection Methods

2.2.1 Sources of Data

Content Analysis: Qualitative content analysis was conducted, so as to systematically


draw inferences by analyzing qualitative information from pre-conducted interviews, focus
groups, open-ended surveys, questions, documents and research papers. We used a variety
of analytic strategies to categorize, compare and contrast a large volume of data. One
technique that we heavily made use of is selective reduction. By reducing the text to
categories consisting of a word, set of words or phrases, we focused on specific words or
patterns that are indicative of the research question and provided us with the required data.

2.3. Requirement Specification

2.3.1 Functional Requirement

Functional requirements define the statements of services that the system should provide
first hand and how the system should react to behave to the particular inputs and particular
situations. The functional requirements of RoadBuddy are defined with the use Use-case
diagrams as follows:

7
2.3.1.1. Register User

The system shall authenticate the user after registering to the system with the required
email address and desired password.

Figure: 1 Use case for user registration

2.3.1.2. Login

User shall be able to login to the system after the successful registration with the valid user
name and password. User shall now access the system after the login.

Figure: 2 Use case for user login

8
2.3.1.3. Update Traffic Data

This functional requirement provides the contributor to update the current jam data on the
map and the system updates this data on the map with the help of geo-tagging.

Figure: 3 Use case for updating traffic data

2.3.1.4. Navigate

This requirement provides the commuter by providing the best path from the current
location to the destination.

Figure: 4 Use case for navigation

9
2.3.2 Non-Functional Requirement

 Concurrency: Since RoadBuddy is a real time application, it has the potential to


handle multiple computations and should execute simultaneously for each of the
user. And each user should potentially interact with the each other’s data.

 Reliability: All the data including the user data and the traffic data are stored in the
database and is under the authentication of the admin. So, all the transactions of
data are safe and reliable.

 Usability: With the provided user-interface, the application is simple and


convenient to use where updating traffic data and navigating is easy.

2.4. Feasibility study

The feasibility study is the initial design stage of the project that indicates if the
proposed project is possible or not. It determines if the proposed project is useful or
not and defines the practicality of the project or a system. The study also determines
if the system can be built efficiently on required time with the available resources.

2.4.1. Technical feasibility

The technical feasibility study focuses on gaining an understanding of the present


technical resources and their applicability to the expected needs of the proposed
system. All the tools and software product that are required for this project is easily
available in the internet. It requires a web server and Database Management System
to operate which are easily affordable. However, the implementation of algorithm and
the calculations are rather complex.
 Hardware Requirements:
The application is for the mobile platform and hence requires a mobile phone
that runs on Android Operating system.

10
 Software Requirements:
The application will be compatible with mobile devices with at least an API
level of 14, which means the minimum android version is Android 4.0 (Ice
Cream Sandwich), based on Linux kernel 3.0.1.
 Communication:
The application is real-time, which means it requires an internet connection,
which can be handled via the respective mobile carrier, also referred to as
mobile data.
 Permissions:
The application is heavily dependent upon geolocation, which means it will
ask the user for location permission, and if allowed, the application can track
the user’s current location.

2.4.2. Operational feasibility

Operational feasibility measures how well a proposed system can solve the defined
problem, and takes advantage of the opportunities identified during scope definition
and how it satisfies the requirements identified in the requirements analysis phase.
The system can be developed to be reliable, maintainable, usable, sustainable and
affordable. So, this system is operationally feasible.

2.4.3. Economic feasibility

Economic feasibility analyses the project’s costs and revenue in an effort to determine
whether it is possible to complete or not. Although no extra equipment was bought
for conducting our project, we had to select a suitable plan for configuring and using
the database, called the Spark Plan, which provided us with a level of configuration
up to 10k authentications per month, Crashlytics, a real time database and 10 virtual
device tests per day. Potential cost that may be added upon the system, could be that
of as the proposed project requires no extra equipment to be bought and the required
needs are already present, so the system is economically feasible. Maintaining an

11
extensive database, which would be required as the number of users of the app starts
increasing. Also, additional cost could be linked with advanced plans regarding the
MapBox SDK, which provide high end services like the MapBox Vision SDK.

2.4.4. Schedule Feasibility

Table 1 Gantt chart

The above Gantt chart displays the overall timeline of the project. It presents the
sequential breakdown of the task involved in the project with the time taken for each
task. The first two activities were carried out per schedule. Implementation and coding
phase was carried out in parallel with the report preparation. The testing phase of the
project was carried along with the documentation until the completion of the project.

12
2.5. Structuring System Requirements

2.5.1. Process Modeling (DFD Level-0 and Level-1)

2.5.1.1. Context Level Diagram (DFD level-0)

Figure: 5 Context level diagram

The above context level diagram shows the overall data flow throughout the system where
commuter and the contributor works in parallel. The commuter request for the best path.
The contributor updates the traffic conditions to the system and the admin verifies all the
data running through the system.

13
2.5.1.2. DFD Level-1

Figure: 6 DFD level-1 diagram

The DFD Level-1 diagram shows the inner process of the system which includes
navigation, traffic data controller and authentication system. The diagram depicts the flow
of data throughout the system.

14
CHAPTER 3. SYSTEM DESIGN

System Design includes the means and methodologies to improve the management and
control of the software development process. It includes structuring and simplifying the
process using several diagrams and standardizing the development process by specifying
the required activities and techniques to be implemented.

3.1. System Architecture and Overview

A system architecture is the conceptual model that defines the structure, behavior of a
system. It can comprise system components, the expanded systems developed, that works
together to implement the overall system. For our proposed project, we developed a system
that works under the requirement of an android mobile handset, a database and a working
app. Since our project is based on android application, it specifically runs on an android
mobile handset. Our app handles real-time data so, we use Firebase as our database service
as it provides real-time syncing to the clients subscribed to the server at any given instance.

Figure: 7 System architecture

15
3.1.1. Database Schema

Firebase is based on NoSQL database model so, database is stored in firebases as large
JSON document [7]. The data is stored as a large data objects which can hold key values
where a value can be a string, number or other objects. Since firebase doesn’t support query
language, we cannot use extra objects or tables with reference to other objects like in SQL
databases. Hence, data in firebase is stored as JSON Structure or JSON tree.

Figure: 8 Database schema

As the object keys are written here like:


"User1","User2","ReportByUser1",”ReportByUser2” etc. In practical scenarios, firebase
generate keys which look like '-JglJnGDXcqLq6m844pZ'. Firebase uses these keys to
facilitate ordering and sorting.

16
3.2. Algorithms Used

3.2.1. Multi-Parameter Dijkstra’s Algorithm

Dijkstra’s Algorithm is conventionally used to find the shortest path between the locations.
But we needed an algorithm to calculate the shortest path that could also incorporate
several other factors like average time, congestion factors and heuristic values. So, the
algorithm for the shortest path along with the alternate route calculation is the modification
of the Dijkstra’s algorithm that uses multiple parameters to find the valid shortest path
instead of just one; it is called as Multi-Parameter Dijkstra’s Algorithm (MPD) [6]. Since
this project requires calculation of shortest path based on several factors such as time taken
to travel and congestion factor, this algorithm incorporates these parameters for an efficient
calculation of the shortest path.

Algorithm
1. Begin
2. for each vertex v in Graph do
3. alternate_path[i]=NULL
4. dist.[v]=infinity
5. weight_update(choice)
6. for each vertex v in Graph do
7. if v = source or v = destination then
8. for each neighbor u of v do
9. if alternate_path[i] > dist[u] + distance(u,v) then
o alternate_path[i] = >dist[u] + distance(u,v) then
10. end if
11. end for
12. end if
13. end for
14. end for
15. end

17
Algorithm for multi-parameter (weight-update (choice))
1. Begin
2. if choice = average_time then
3. weight = average_time
4. else if choice = congestion then
5. weight = average_time*congestion_factor
6. else
7. weight = average_time + heuristic
8. return weight
9. end

3.3. UML Diagrams

The UML diagrams below includes different types of diagrams incorporating the structure
and behavior of the system. The diagrams designed to develop the system are shown below.

3.3.1. Class Diagram

Figure: 9 Class Diagram

18
3.3.2. Sequence Diagram
A sequence diagram shows object interactions arranged in time sequence. It depicts the
objects and classes involved in the scenario and the sequence of messages exchanged
between the objects needed to carry out the functionality of the scenario. Sequence
diagrams are typically associated with use case realizations in the logical view of the
system under development.

3.3.2.1. Update Data

Figure: 10 Sequence diagram for updating data

19
The diagram in the Figure 10 is the Sequence diagram for updating the traffic data. This
diagram depicts how the data updated by the contributor associated with the traffic
conditions, which is added to the database and updated in the application interface itself.
There is an interaction between the four component i.e. Contributor, User Interface, System
Controller and Database. Initially, the working mechanism starts with the contributor
adding the traffic condition at the specific location. The system, then verifies the
information using the associated location data residing in the database.

3.3.2.2. Navigation

Figure: 11 Sequence diagram for navigation

The diagram in the Figure 11 is the Sequence diagram for navigating from the current
location to the desired destination. This sequence diagram depicts how the path is generated
for the commuter to navigate from the source to destination. There is an interaction between
the components that includes commuter, user interface, controller and the database. Here,
the working mechanism starts with the commuter selecting the desired destination. The

20
system then generates the path using the multi-parameter Dijkstra’s algorithm that uses
several parameters to generate the optimized path.

3.3.3. Activity Diagram


Activity diagram is another important diagram in UML to describe the dynamic aspects of
the system. Activity diagram is basically a flowchart to represent the flow from one activity
to another activity. The activity can be described as an operation of the system. The control
flow is drawn from one operation to another.

Figure: 12 Activity diagram

21
The activity diagram shown in Figure 12 shows the flow of one activity to another in the
system starting from the user login which is authenticated by the admin. After the user is
logged in, the user can perform one of the two functions, updating the traffic condition or
navigating from one place to another. The traffic data triggered by the user is updated in
the database and the relevant information is displayed in the application.

22
CHAPTER 4. SYSTEM IMPLEMENTATION AND
TESTING

4.1. Implementation Overview

Process model used


The Incremental Development model is an incremental approach for developing a
software product as the product is designed, implemented and tested incrementally until
the product is finished. This approach for developing a software applies the waterfall
model incrementally. Incremental development model is used where the requirements
are clear before the development of the product and can be implemented in phases.
Since this project doesn’t deal with any clients, incremental development is used so, all
the requirements are clear. Development of the software is carried by tackling the
highest priority requirement and goes through each development phases for each of the
requirements until the final product is delivered.
We are using incremental development model as each increments for the specific
requirements can be reviewed for the required changes or modification.

4.2. Tools Used

4.2.1. Front End Tools

Mapbox API: The Mapbox web services APIs allows us to programmatically access
Mapbox tools and services. It is an open source mapping platform, for custom designed
maps. Mapbox provides robust geospatial data with our Streets, Terrain, Traffic, and
Satellite tilesets, but mapping applications often require custom data. We can upload
our own data as tilesets or create datasets to add custom data to our map. We used
Mapbox API to load the map in our application. This API also allowed us to refer to

23
the traffic data of Kathmandu, which has limited predictability. It also provides us with
additional control over the map design and map layout.

4.2.2. Back End Tool

Kotlin: Kotlin is a cross-platform, general-purpose programming language which is


designed to interoperate fully with Java, and depends on the Java Class Library. Kotlin
was officially announced as the primary language for Android. Since our app is also
based on android, the core functionality was developed using Kotlin like navigation,
route planning along with other functionality like user registration and login.

Firebase: Firebase is a backend platform for building mobile and web application
where we can build application quickly with real time data update. Firebase stores data
in JSON format. Using firebase is easy as we do not need to configure your server.
Everything will be handled by firebase automatically. So no coding on server side is
required. We used firebase because it is a BAAS (Backend as a service) which is a
NOSQL database. It provides us control over our database in real-time which
simultaneously updates the application at any given instance as per the changes made
by clients.

4.3. Modules Description

This project can be decomposed into following modules:

a) Login module: This module is responsible for a registered user to login to the web
application and do the proceedings.

b) Registration module: This module is responsible for registering a new user to the
web application and create a new account for him/her.

c) Sessions module: This module is responsible for creating a session when a user
logs in and continues till he/she logs out.

24
d) Mapbox module: This module contains all the functionalities of the map.
The classes used in this project are as follows:
 CommuterActivity
 ContributorActivity
 LoginActivity
 Report
 SignUpActivity
 SplashActivity
 MapBoxActivity

Methods used:
 onCreate()
 getFirebaseData()
 createOptionsMenu(location: String, lat: Double , long: Double)
 onMapLongClick(point: LatLng)
 onMapReady()
 getRoute(origin: Point, destination: Point)
 enableLocationComponent(loadedMapStyle: Style)
 onBackPressed()
 sentToFirebase(type: String, lat: Double, long: Double )

25
4.4. Testing
Software testing is the process or an activity to check whether the actual results match
the expected results and to ensure that the software system is free of errors. Testing is
carried out during the development of the software.

4.4.1. Unit Testing


Unit testing is the part of the testing methodology which includes testing of
individual software modules and the components that make up the entire software.
Each modules or the components are individually tested to check for any kind of
errors or misbehaviors.

Table 2: Test case for installation

S Test Case Test Input Test Expected Actual Result Remarks


N ID Description Data Result

1 TC-INS-01 Install Transfer Application Application Pass


RoadBuddy RoadBuddy opens with executed with
app on app loaded welcome
android welcome page page
phone

Table 3: Test case for Application Login

S Test Case Test Description Input Test Expected Actual Result Remark
N ID Data Result s
1 TC-LG- Enter valid data in ram@gmail.co Load map, Displayed map Pass
01 email and m with current for user ram,
password field location for in the current
******** user ram location
2 TC-LG- Enter valid data in ram@gmail.co Show error Displayed Pass
02 email and leave m message “Enter
password field Password”
empty

26
3 TC-LG- Leave email Show error Displayed Pass
03 empty and enter message “Enter Email”
password ********
4 TC-LG- Enter invalid ram@gmale.co Show error Displayed Pass
04 email address and m message “You are not
password Registered”
******

Table 4: Test case for Navigation

SN Test Case ID Test Input Test Expected Actual Result Remar


Description Data Result ks
1 TC-NVG-01 Select desired Map press Navigation Route for Pass
destination route from the navigation
point by current user displayed, with
clicking on the location to the turn-by-turn
map desired point voiceover
instructions

Table 5: Test case for Traffic report

SN Test Case ID Test Input Test Expected Result Actual Result Remarks
Description Data
1 TC-RP-01 Report of Long press Dialog box User verified Pass
any traffic appears for the traffic data is
congestion user to select the sent to the
on specific nature of the real-time
point the problem database
map

27
4.4.2. System Testing
System testing is the part of the testing methodology that includes the testing of the
entire integrated system for any kind of errors and bugs. System testing is basically
done to check if the system works when executed. This test is carried out by
interfacing the components of the entire system and testing it as a whole.

Table 6: System Testing

S Test Test Description Input Test Expected result Actual Result Remarks
N Case ID data
1 TC-INS- Install Transfer Application opens Application Pass
01 RoadBuddy app RoadBuddy with welcome page executed with
on android phone app welcome page

2 TC-LG- Enter valid data in abc@gmail. Load map, with Displayed map Pass
01 email and com current location for for user abc, in
password field user abc the current
******** location
3 TC- Select desired Map press Navigation route Route for Pass
NVG-01 destination point from the current navigation with
by clicking on the user location to the turn-by-turn
map desired point voiceover
instructions

4 TC-RP- Report of any Long press Dialog box appears User verified Pass
01 traffic congestion for the user to traffic data is
on specific point select the nature of sent to the real-
by long clicking the problem time database
on the map

28
CHAPTER 5. CONCLUSION

5.1. Conclusion

The development of this application provides a platform for users to help fellow users
to outsmart traffic and navigate efficiently. We expect the application to work properly
on the installed systems i.e. mobile devices that function on the android operating
systems. Provided the necessary conditions, like a stable network connection or internet
connection, location permission, the app will be able to load a map which will not only
provide basic navigation functions and guidelines but information related to congestion
in the traffic conditions, caused by the existing problems like traffic jam, road
construction, blocked roads etc., which are shared by other users of the app and can be
very helpful for the users to get around the city. Overall, RoadBuddy promotes the
concept of community-based navigation in the extremely intricate road traffic
conditions of Kathmandu.

5.2. Recommendation

RoadBuddy can be used by the everyday common man, who has faced problems related
to traffic congestion and would like to outsmart the traffic condition to get to their
destination. Also this application is highly recommended to people who believe that
they have a sense of responsibility towards the society as the app can provide a platform
for just that. The app is pretty simple to use and can be used by anyone who wants to
get to their destination, without having to face the trouble of getting stuck in a jam.

29
Future Scope

The app, although finished can be integrated with further enhancements. The UI and
the UX can be improved by working with the Mapbox API and a crucial addition can
be made to the app i.e. suggestion of faster routes to the user, in case of a blocked route.
Other factors like data collection strategies can be enhanced so that the app can be made
more accountable.

30
BIBILOGRAPHY

[1] S. Hinda. & A. Gekker. , “Outsmarting Traffic, Together” in Driving as Social


Navigation 2014, vol. 1, 2014.

[2] N. Noerkaisar, B. Suharjo, L. Noor Yuliati “The adaptation stages of mobile


navigation technology waze app as Jakarta Traffic Jam Solution” in Independent
Journal of Management & Production 2016, vol. 7, pp. 916, 2016.

[3] Y. Zheng, Y. Chen, X. Xie, and W. Ma, “GeoLife2.0: A location-based social


networking service” in Inter-national Conference on Mobile Data Management:
Systems, Services and Middleware 2009, pp. 357–358, 2009.

[4] Manjul. Bajracharya, “Problems in transportation management in Kathmandu


valley” Ace institute of management, Pokhara University, 2016.

[5] Emarketer.com, 'Social Networking Reaches Nearly One in Four Around the
World', 2014. [Online]. Available: http://www.emarketer.com/Article/Social-
Networking-Reaches-Nearly-One-Four-Around-World/1009976. [Accessed: 23-
Jun- 2014].

[6] S. Sivakumar, Dr. C.Chandrasekar, “Modified Dijkstra’s Shortest Path Algorithm”


in International Journal of Innovative Research in Computer and Communication
Engineering, Vol. 2, Issue 11, pp. 6453-6454, 2014.

[7] R. Khanna, “Structuring your Firebase Data correctly for a Complex App”, 2015.
[Online]. Available: https://www.airpair.com/firebase/posts/structuring-your-
firebase-data. [Accessed: 23-Jun-2014].

31
APPENDIX-1
(Screenshots)

32
33
34
Appendix-2
(Codes)

MapboxActivity.kt

package com.road.buddy.mapbox

// classes needed to initialize map

// classes needed to add the location component

// classes needed to add a marker

// classes to calculate a route

// classes needed to launch navigation UI


import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.os.Bundle
import android.os.Handler
import android.support.v4.content.res.ResourcesCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.Toast
import com.github.ybq.android.spinkit.style.DoubleBounce
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.GeoPoint
import com.mapbox.android.core.permissions.PermissionsListener
import com.mapbox.android.core.permissions.PermissionsManager
import com.mapbox.api.directions.v5.models.DirectionsResponse
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.geojson.Feature
import com.mapbox.geojson.Point
import com.road.buddy.R
import kotlinx.android.synthetic.main.activity_mapbox.*
import kotlinx.android.synthetic.main.dialog_feedback.view.*
import kotlinx.android.synthetic.main.dialog_sucess.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MapBoxActivity : AppCompatActivity(), OnMapReadyCallback,


MapboxMap.OnMapClickListener, PermissionsListener,
MapboxMap.OnMapLongClickListener {

// variables for adding location layer


private lateinit var mapView: MapView
private lateinit var mapboxMap: MapboxMap

35
// variables for adding location layer
private var permissionsManager: PermissionsManager? = null
private var locationComponent: LocationComponent? = null
// variables for calculating and drawing a route
private var currentRoute: DirectionsRoute? = null
private var navigationMapRoute: NavigationMapRoute? = null
// variables needed to initialize navigation
private var button: Button? = null
val db = FirebaseFirestore.getInstance()
var userEmail: String? = null
var fireBaseDataLat: ArrayList<String>? = null
var fireBaseDataLong: ArrayList<String>? = null
var fireBaseType: ArrayList<String>? = null

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
Mapbox.getInstance(this, getString(R.string.access_token))
setContentView(R.layout.activity_mapbox)

mapView = this.findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
if (intent.extras != null) {
this.userEmail = intent.getStringExtra("UserEmail")
}
getFireBaseData()
feedback.setOnClickListener {
createDialog()
}
}
private fun createDialog() {

val dialog = Dialog(this)


dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(true)
dialog.setContentView(R.layout.dialog_sucess)
val btOk = dialog.findViewById<Button>(R.id.btn_dialog)
btOk.setOnClickListener {
val feegback = dialog.et_feedback.text.toString()
sendFeedBackToFireBase(feegback)
dialog.dismiss()
}
dialog.show()

private fun sendFeedBackToFireBase(msg: String) {

val report = HashMap<String, Any>()


report["userEmail"] = userEmail.toString()
report["Feedback"] = msg

// Add a new document with a generated ID


db.collection("FeedBackByUser")
.add(report)

36
.addOnSuccessListener { documentReference ->
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
showDialogThankYou()

}
.addOnFailureListener { e ->

Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()


}
}

private fun getFireBaseData() {


db.collection("ReportByUser")
.get()
.addOnSuccessListener { result ->
result.toObjects(report::class.java)

for (document in result) {

val lat = document.data["Latitude"].toString()


val long = document.data["Longitude"].toString()
val type = document.data["Type"].toString()
Log.d(TAG, "${document.id} => ${document.data}")
setMarkerOnMap(lat, long, type)

}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents.", exception)
}
}

private fun setMarkerOnMap(lat: String, long: String, type: String) {


val lati = lat.toDouble()
val longi = long.toDouble()
Log.d("TEST",lati.toString())
Log.d("TEST",longi.toString())
Log.d("TEST",type.toString())

val IconBlocked = ResourcesCompat.getDrawable(resources,


R.drawable.blocked, null)
val iconConstruction = ResourcesCompat.getDrawable(resources,
R.drawable.construction, null)
val iconJam = ResourcesCompat.getDrawable(resources, R.drawable.jam,
null)

val marker = MarkerOptions()


marker.position(LatLng(lati,longi))
when(type){
"construction" -> marker.title= "Road under construction, Please
take another way"
"blocked" -> marker.title= "Road blocked, Please take another way"
else -> marker.title =" Road Jam, Please take another way"
}
mapboxMap.addMarker(marker)

R.drawable.person, null)

37
}

private fun createOptionsMenu(location: String, lat: Double, long: Double)


{

val dialogFuelRequestSuccess =
layoutInflater.inflate(R.layout.dialog_feedback, null)
dialogFuelRequestSuccess.vRequestSuccess.text = "$location"
val alertDialog = AlertDialog.Builder(this)
.setView(dialogFuelRequestSuccess)
.setCancelable(true)
.create()

alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
alertDialog.show()
dialogFuelRequestSuccess.construction.isClickable = false

dialogFuelRequestSuccess.blocked.setOnClickListener {
val type = "blocked"
if (alertDialog.isShowing)
alertDialog.dismiss()
// showProgressBarInDialog(dialogFuelRequestSuccess)
sendToFireBase(type, lat, long)

dialogFuelRequestSuccess.construction.setOnClickListener {
val type = "construction"
if (alertDialog.isShowing)
alertDialog.dismiss()
sendToFireBase(type, lat, long)

dialogFuelRequestSuccess.jam.setOnClickListener {
val type = "jam"
if (alertDialog.isShowing)
alertDialog.dismiss()
sendToFireBase(type, lat, long)

private fun sendToFireBase(


type: String,
lat: Double,

38
long: Double
) {

showDialogThankYou()

val report = HashMap<String, Any>()


report["userEmail"] = userEmail.toString()
report["Latitude"] = lat
report["Longitude"] = long
report["Type"] = type

// Add a new document with a generated ID


db.collection("ReportByUser")
.add(report)
.addOnSuccessListener { documentReference ->
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show()
getFireBaseData()

// Log.d("TAG", "DocumentSnapshot added with


ID: ${documentReference.id}")
}
.addOnFailureListener { e ->

Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()


}
}

private fun showDialogThankYou() {


val dialogFuelRequestSuccess =
layoutInflater.inflate(R.layout.dialog_thankyou, null)
val alertDialog = AlertDialog.Builder(this)
.setView(dialogFuelRequestSuccess)
.setCancelable(true)
.create()

alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
alertDialog.show()
Handler().postDelayed({
if (alertDialog.isShowing)
alertDialog.dismiss()
//since error while restarting app was redirected
}, 2000)
}

override fun onMapLongClick(point: LatLng): Boolean {

createOptionsMenu("on this location", point.latitude, point.longitude)


return true
}

override fun onMapReady(mapboxMap: MapboxMap) {

39
this.mapboxMap = mapboxMap

mapboxMap.setStyle("mapbox://styles/masterwayne3007/cjvjk1lfv1brr1dlr54kjpczt")
{ style ->
val trafficPlugin = TrafficPlugin(mapView, mapboxMap,style)
trafficPlugin.setVisibility(true) // Enable the traffic view
enableLocationComponent(style)
addDestinationIconSymbolLayer(style)
mapboxMap.addOnMapClickListener(this@MapBoxActivity)
mapboxMap.addOnMapLongClickListener(this@MapBoxActivity)
button = findViewById(R.id.startButton)
button!!.setOnClickListener {
if (currentRoute != null) {
val simulateRoute = false
val options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build()
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(this@MapBoxActivity,
options)
} else
Toast.makeText(this, "Please Press Again",
Toast.LENGTH_SHORT).show()

}
}

mapView.invalidate()

private fun test() {


TODO("not implemented") //To change body of created functions use File
| Settings | File Templates.
}

private fun addDestinationIconSymbolLayer(loadedMapStyle: Style) {


loadedMapStyle.addImage(
"destination-icon-id",
BitmapFactory.decodeResource(this.resources,
R.drawable.mapbox_marker_icon_default)
)
val geoJsonSource = GeoJsonSource("destination-source-id")
loadedMapStyle.addSource(geoJsonSource)
val destinationSymbolLayer = SymbolLayer("destination-symbol-layer-id",
"destination-source-id")
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
)
loadedMapStyle.addLayer(destinationSymbolLayer)
}

@SuppressLint("MissingPermission")
override fun onMapClick(point: LatLng): Boolean {

40
val destinationPoint = Point.fromLngLat(point.longitude,
point.latitude)
val originPoint = Point.fromLngLat(

locationComponent!!.lastKnownLocation!!.longitude,
locationComponent!!.lastKnownLocation!!.latitude
)

val source = mapboxMap.style!!.getSourceAs<GeoJsonSource>("destination-


source-id")
source?.setGeoJson(Feature.fromGeometry(destinationPoint))

getRoute(originPoint, destinationPoint)
button!!.isEnabled = true
button!!.setBackgroundResource(R.color.mapboxBlue)
return false
}

private fun getRoute(origin: Point, destination: Point) {


NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken()!!)
.origin(origin)
.destination(destination)
.build()
.getRoute(object : Callback<DirectionsResponse> {
override fun onResponse(call: Call<DirectionsResponse>,
response: Response<DirectionsResponse>) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code())
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the
right user and access token.")
return
} else if (response.body()!!.routes().size < 1) {
Log.e(TAG, "No routes found")
return
}

currentRoute = response.body()!!.routes()[0]

// Draw the route on the map


if (navigationMapRoute != null) {
navigationMapRoute!!.removeRoute()
} else {
navigationMapRoute = NavigationMapRoute(null, mapView,
mapboxMap, R.style.NavigationMapRoute)
}
navigationMapRoute!!.addRoute(currentRoute)
}

override fun onFailure(call: Call<DirectionsResponse>,


throwable: Throwable) {
Log.e(TAG, "Error: " + throwable.message)
}
})
}

41
@SuppressLint("MissingPermission")
private fun enableLocationComponent(loadedMapStyle: Style) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.locationComponent

locationComponent!!.activateLocationComponent(this, loadedMapStyle)
locationComponent!!.isLocationComponentEnabled = true
// Set the component's camera mode
locationComponent!!.cameraMode = CameraMode.TRACKING
} else {
permissionsManager = PermissionsManager(this)
permissionsManager!!.requestLocationPermissions(this)
}
}

override fun onRequestPermissionsResult(requestCode: Int, permissions:


Array<String>, grantResults: IntArray) {
permissionsManager!!.onRequestPermissionsResult(requestCode,
permissions, grantResults)
}

override fun onExplanationNeeded(permissionsToExplain: List<String>) {


Toast.makeText(this, R.string.user_location_permission_explanation,
Toast.LENGTH_LONG).show()
}

override fun onPermissionResult(granted: Boolean) {


if (granted) {
enableLocationComponent(mapboxMap.style!!)
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted,
Toast.LENGTH_LONG).show()
finish()
}
}

override fun onStart() {


super.onStart()
mapView.onStart()
}

override fun onResume() {


super.onResume()
mapView.onResume()
}

override fun onPause() {


super.onPause()
mapView.onPause()
}

override fun onStop() {


super.onStop()
mapView.onStop()
}

42
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}

override fun onDestroy() {


super.onDestroy()
mapView.onDestroy()
}

override fun onLowMemory() {


super.onLowMemory()
mapView.onLowMemory()
}

companion object {
private val TAG = "DirectionsActivity"
}
}

LoginActivity.kt

package com.road.buddy.login

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import com.github.ybq.android.spinkit.style.Wave
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.road.buddy.R
import com.road.buddy.mapbox.MapBoxActivity
import com.road.buddy.signup.SignUpActivity
import com.road.buddy.utils.BaseActivity
import com.road.buddy.utils.Utils
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity() {

private var doubleBackToExitPressedOnce = false

private lateinit var auth: FirebaseAuth

private var commuter = "adit"


private var contributer = "alex"
private var pass = "123"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = FirebaseAuth.getInstance()

etEmail.setText("abc@gmail.com")

43
etPassword.setText("123456789")
val progressbar = findViewById<ProgressBar>(R.id.progressBar2)
val wave = Wave()
progressbar.setIndeterminateDrawableTiled(wave)

// Create a new user with a first and last name

btnLogin.setOnClickListener {
btnLogin.visibility = View.GONE
progressBar2.visibility = View.VISIBLE
val username = etEmail.text.toString()
val password = etPassword.text.toString()

auth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener(this)
{ task ->
if (task.isSuccessful) {
val user = auth.currentUser
Log.d("Here", user.toString())
startActivity(Intent(this,
MapBoxActivity::class.java).putExtra("UserEmail", username))
Toast.makeText(this, "Login Successful",
Toast.LENGTH_LONG).show()
btnLogin.visibility = View.VISIBLE
progressBar2.visibility = View.GONE
} else {

Toast.makeText(this, "Login Unsuccessful",


Toast.LENGTH_LONG).show()
btnLogin.visibility = View.VISIBLE
progressBar2.visibility = View.GONE

}
}
}

startActivity(Intent(this,ContributorActivity::class.java))

btnSignup.setOnClickListener {
startActivity(Intent(this, SignUpActivity::class.java))
}
}

override fun onBackPressed() {


if (doubleBackToExitPressedOnce) {
Utils.exitApp(this)
} else {
this.doubleBackToExitPressedOnce = true
Utils.showToast(this,
getString(com.road.buddy.R.string.please_click_again_to_exit))
Handler().postDelayed({ doubleBackToExitPressedOnce = false },
2000)
}
}

44

You might also like