You are on page 1of 118

A

PROJECT REPORT
ON
“Automated Canteen Ordering System”

:: Submitted by ::
Mr. Abhijeet Baliram Pawale
Miss. Shradha Devanand
Jogdand Miss. Anjali Jaywantrao
Pawale Miss. Samiksha
Chakkawar

::Department of ::
COMPUTER ENGINEERING

GRAMIN POLYTECHNIC,
VISHNUPURI NANDED: - 431606
ACADEMIC YEAR
2020-21
A
PROJECT REPORT
ON
“Automated Canteen Ordering System”

:: Submitted by ::
Mr. Abhijeet Baliram Pawale
Miss. Shradha Devanand
Jogdand Miss. Anjali Jaywantrao
Pawale Miss. Samiksha
Chakkawar

:: Guided by ::
Ms. Dudhmal M.N.
In partial fulfillment for the award of the diploma in
COMPUTER ENGINEERING

GRAMIN POLYTECHNIC,
VISHNUPURI NANDED: - 431606
ACADEMIC YEAR
2020-21
CERTIFICATE

This is to certify that project entitled “Automated Canteen Ordering System”


being submitted by Mr. Abhijeet Baliram Pawale, Miss. Shradha Devanand
Jogdand,Miss. Anjali Jaywantrao Pawale,Miss. Samiksha Chakkawar to
“Maharashtra State Board of Technical Education, Mumbai” as a partial fulfillment
of award of Diploma in Computer Engineering, is record of bonafied work carried
out by them under my supervision and guidance. The matter contain in this project
work has not been submitted to any other institute for award of any degree or
diploma.

( ) ( )
Mr.Wahi G.S Ms. Dudhmal M.N.

Head of Department Project Guide

( )
Dr. Pawar V.S.
Principal
PROJECT APPROVAL SHEET

Following team has done the appropriate work related to the “Automated
Canteen Ordering System” in partial fulfillment for the award of diploma in
Computer Engineering of “MSBTE” and is being submitted to Gramin Polytechnic
Vishnupuri, Nanded.

Team:
Mr. Abhijeet Baliram Pawale
Miss. Shradha Devanand
Jogdand Miss. Anjali Jaywantrao
Pawale Miss. Samiksha
Chakkawar Guide:
Ms. Dudhmal M.N.
Date:
Place: Nanded.

( ) ( )
Internal Examiner External Examiner
ACKNOWLEDGEMENT

We would like to thank our scheme, faculties and mentors for giving us the opportunity to
work under their guidance and help us in our final project. I would like to thank our beloved
principal Dr. Pawar V.S. who is the force behind this project. My sincere thanks to Ms.
Dudhmal
M.N. as our internal project guide for giving us valuable inputs and ideas right from the selection
of topic for project till its successful completion.

I thank Mr. Wahi G.S (HOD of Computer Department) for his ongoing support and
encouragement in every aspect Last but not the least entire staff of Department of Computer
Engineering for guiding their thoughts and vision.

The successful completion of our final project report would not have been possible
without the dedicated support from all our mentors, family and friends. Finally, yet importantly I
would like to express my heartfelt thanks to my beloved parents for their blessings, my friends,
and all those who supported me directly or indirectly for their help and wishes for successful
completion of this project.

1. Mr. Abhijeet Baliram Pawale


2. Miss. Shradha Devanand Jogdand.
3. Miss. Anjali Jaywantrao Pawale
4. Miss. Samiksha Chakkawar
Automated Collage Canteen Ordering System using Android

The main aim of this project Canteen management system is to provide fast services to
their college students, Staffs etc. Usually People have to go to canteen and order the foods and
they have to wait in queue for a long time to get the orders. But with the help of this you just
have to follow a very simple process to order your stuffs. And you need not to wait in the long
queue.

This android application will provide the list of different menu list with different
categories. User can select any item from canteen and can order for it by using UPI payment or
wallet Payment. Wallet Recharging available with UPI details or admin can add amount in user’s
wallet.

Users have to register with valid details and OTP which will get sent to their mobile
number to login with canteen. Users also get recommendation for food items, Trending food
items.

Canteen Management system manages the all details of food items which contains name,
description, image, price etc. Admin can view the confirm order and update the status of the
order accordingly. Customer can check their balance, order history and able to delete the order
according to order status.

Advantages
 Completely automated online ordering of food in a canteen.
 Order can be placed using personal android phones.
 Food ordering pages that look and feel exactly the same as the existing restaurant
Android Application.
 Food ordering pages hosted on secure and special server so no risk of customers
getting.

Disadvantages
 Requires an active internet connection.
 Requires Android phone if user is ordering.
INDEX

Chapter Name of the Title Page

No. No.

1 Introduction 1

1.1 Aim of Project 1


1.2 Project Analysis 1
1.3. Scope of Project 1
1.4. Objectives 2
1.5. Features 2
1.6. Module 2
1.7 Software Requirement 3
1.8 Hardware Requirement 3

2 Literature Survey 4
2.1 Introduction 4
2.2 Technologies Used 4
3 System Requirements Specifications 6
3.1. Hardware Requirement 6
3.2. Software Requirement 6
4 System Design 7
4.1 Design Document 7
4.2. E-R Diagram 7
4.3 Data Flow Diagram 7
4.4. Undefined Modeling Diagram 8
4.5 Use Case Diagram 8
4.6 Flow Chart Diagram 11
4.7 Activity Diagram 21

5 System Implementation 22
5.1. User Application Coding 22

5.2. Common Classes both sides 55

5.3. Admin Application Coding 61

6 Testing 85
6.1 Testing 85
6.2 Testing Objectives 85
6.3 Levels of Testing 85
6.4 Types of Testing 86
6.5 White box testing 88
6.6 Black box testing 88
6.7 Test Case 88
7 Advantages 91
8 Conclusion 92
9 References 93
Canteen Ordering System 2020-2021

CHAPTER 1
INTRODUCTION

1.1 AIM OF THE PROJECT

The main aim of this project Canteen management system is to provide fast services to
their college students, Staffs etc. Usually People have to go to canteen and order the foods and
they have to wait in queue for a long time to get the orders. But with the help of this you just
have to follow a very simple process to order your stuffs. And you need not to wait in the long
queue.

1.2 PROJECT ANALYSIS

This android application will provide the list of different menu list with different
categories. User can select any item from canteen and can order for it by using UPI payment or
wallet Payment. Wallet Recharging available with UPI details or admin can add amount in user’s
wallet.

1.3 SCOPE OF THE PROJECT

Another significant contributor to the growth of eCommerce in India in the future is the
e- tailing industry which largely deals in providing jewelry, apparel and kitchen appliances
online. Day to day e-commerce business is increase. Know every one comes on Internet and
Online business. Some of local business man developed own mobile application.

If any Collage Canteen use automated canteen order system application then increase this
collage popularity and image. Every think about this collage positive i.e. If Canteen provide
online services like zomato and swiggy. The scope of eCommerce business is turning out to be
more famous day-after-day according to the market demand. And this requirement is generating
innovations worldwide focused on delivery time, ease of transactions and several features served
by eCommerce businesses, for example, drone delivery or artificial intelligence. Websites like

Gramin Polytechnic Vishnupuri, Nanded. Page 1


Canteen Ordering System 2020-2021
Flipkart, Myntra, Amazon, Snapdeal, Jabong, etc. are all examples of the enormous success of

Gramin Polytechnic Vishnupuri, Nanded. Page 2


Canteen Ordering System 2020-2021

eCommerce in India. Due to these firms, India is one of the fastest growing eCommerce markets
in Asia/Pacific with China investing as much. Many analysts believe that the advent of 3G/4G
speed in net connectivity has been a major cog in the wheel for such a growth in this market.

1.4 OBJECTIVES
 Avoid traveling charges.
 Less time conssumes.
 Easy to order from any location.
 You can see and watch maximum product.
 Currently Covid problem incease then you can use this application.
 You can save your time.
 Using this application promot degitalition.
 Reduce management costs.
 Providing a unique customer experience.

1.5 FEATURES
 It is easy to set up.
 There are no geographical boundaries.
 Much cheaper than traditional business.
 Easy to manage customer information.
 All data store online.
 Admin know all report.
 There is no personal touch.
 You can track easily your orders.
 Admin knows all shop details from any location.

1.6 MODULE

🠶 User

Gramin Polytechnic Vishnupuri, Nanded. Page 3


Canteen Ordering System 2020-2021

🠶 Admin

1.7 SOFTWARE REQUIREMENTS

 Operating System : Windows


 Coding Language : Java, XML
 Database : Server – Firebase
 IDE : Android Studio

1.8 HARDWARE REQUIREMENTS

 System : Intel 3,5,7


 Hard disk : 40 GB
 Ram : 4 GB

Gramin Polytechnic Vishnupuri, Nanded. Page 4


Canteen Ordering System 2020-2021

CHAPTER 2
LITERATURE
2.1 INTRODUCTION
SURVEY

In this project we are explain and importance of digit world. The main aim of this project
Canteen management system is to provide fast services to their college students, Staffs etc.
Usually People have to go to canteen and order the foods and they have to wait in queue for a
long time to get the orders. But with the help of this you just have to follow a very simple
process to order your stuffs. And you need not to wait in the long queue.

This android application will provide the list of different menu list with different
categories. User can select any item from canteen and can order for it by using UPI payment or
wallet Payment. Wallet Recharging available with UPI details or admin can add amount in user’s
wallet.

Users have to register with valid details and OTP which will get sent to their mobile
number to login with canteen. Users also get recommendation for food items, Trending food
items.

2.2 TECHNOLOGIES USED


This application uses three different technologies namely:

2.2.1 PROGRAMING LANGUAGE


 Java
Now a days we using Java programming language was originally developed by Sun
Microsystems which was initiated by James Gosling and released in 1995 as core component of
Sun Microsystems'.
With the advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. Java is guaranteed to be Write Once, Run
Anywhere.

Gramin Polytechnic Vishnupuri, Nanded. Page 5


Canteen Ordering System 2020-2021
 XML
Extensible Markup Language is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. The World
Wide Web

Gramin Polytechnic Vishnupuri, Nanded. Page 6


Canteen Ordering System 2020-2021

Consortium's XML 1.0 Specification of 1998 and several other related specifications—all of
them free open standards—define XML.

2.2.2 TOOLS

 Android Studio (IDE)


Android Studio. Android Studio is the official integrated development environment (IDE)
for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed
specifically for Android development. It is available for download on Windows, MAC OS and
Linux based operating systems. The code editor helps you write better code, work faster, and be
more productive by offering advanced code completion, refactoring, and code analysis. As you
type, Android Studio provides suggestions in a dropdown list. Simply press Tab to insert the
code.

2.2.3 DATABASE

 Firebase(Server)

Firebase is a platform developed by Google for creating mobile and web applications. It
was originally an independent company founded in 2011. In 2014, Google acquired the platform
and it is now their flagship offering for app development.

Firebase's first product was the Firebase Realtime Database, an API that synchronizes
application data across iOS, Android, and Web devices, and stores it on Firebase's cloud. The
product assists software developers in building real-time, collaborative applications.

Gramin Polytechnic Vishnupuri, Nanded. Page 7


Canteen Ordering System 2020-2021

CHAPTER 3
SYSTEM REQUIREMENT SPECIFICATIONS
A System requirement specification (abbreviated SRS when needed to be distinct from a
SRS) is structured collection of information that embodies the requirements of the system.

3.1 HARDWARE REQUIREMENT


The selection of hardware is very important in the existence and proper working of any
software. In the selection of hardware, the size and the capacity requirements are also important.
 Pentium processor -------- 233 MHZ or above
 RAM Capacity -------- 128MB
 Hard Disk -------- 20GB
 Floppy disk -------- 1.44 MB
 CD-ROM Drive -------- 32 HZ
 Keyboard -------- 108 Standard

3.2 SOFTWARE REQUIREMENTS


One of the most difficult tasks is that, the selection of the software, once system requirement
is known is determining whether a particular software package fits the requirements. After initial
selection further security is needed to determine the desirability of particular software compared
with other candidates. This section first summarizes the application requirement question and then
suggests more detailed comparisons.
 Operating System -------- Windows 95/98/NT/2000
 Browser -------- IE
 Web/Application Server -------- Java Web Server2.0
 Database Server -------- Oracle
 Database Connectivity -------- JDBC
 Other Tools & Technologies -------- Java (JDK), Servlets (JSDK)

Gramin Polytechnic Vishnupuri, Nanded. Page 8


Canteen Ordering System 2020-2021

CHAPTER 4
SYSTEM DESIGN
4.1 DESIGN DOCUMENT

The entire system is projected with a physical diagram which specifics the actual storage
parameters that are physically necessary for any database to be stored on to the disk. The overall
systems existential idea is derived from this diagram.
The relation upon the system is structure through a conceptual ER-Diagram, which not
only specifics the existential entities but also the standard relations through which the system
exists and the cardinalities that are necessary for the system state to continue.

4.2 ER-DIAGRAM

 The entity Relationship Diagram (ERD) depicts the relationship between the data
objects. The ERD is the notation that is used to conduct the date modeling activity
the attributes of each data object noted is the ERD can be described resign a data
object descriptions.

 The set of primary components that are identified by the ERD are

 Data object

 Relationships

 Attributes

 Various types of indicators.

 The primary purpose of the ERD is to represent data objects and their relationships.

4.3 DATA FLOW DIAGRAM (DFD)


 The DFD is also called as bubble chart. It is a simple graphical formalism that can be
used to represent a system in terms of input data to the system, various processing
carried out on this data, and the output data is generated by this system.
 The data flow diagram (DFD) is one of the most important modeling tools. It is used
to model the system components. These components are the system process, the data

Gramin Polytechnic Vishnupuri, Nanded. Page 9


Canteen Ordering System 2020-2021

used by the process, an external entity that interacts with the system and the
information flows in the system.
 DFD shows how the information moves through the system and how it is modified
by a series of transformations. It is a graphical technique that depicts information
flow and the transformations that are applied as data moves from input to output
 DFD is also known as bubble chart. A DFD may be used to represent a system at any
level of abstraction. DFD may be partitioned into levels that represent increasing
information flow and functional detail.

4.4 UNIFIED MODELING LANGUAGE DIAGRAMS (UML)

 The unified modeling language allows the software engineer to express an analysis model
using the modeling notation that is governed by a set of syntactic semantic and pragmatic
rules.

 A UML system is represented using five different views that describe the system from
distinctly different perspective. Each view is defined by a set of diagram, which is as
follows.

 User Model View.

4.5 USE CASE DIAGRAM

A use case diagram shows a set of use cases and actors and their relationships. Use
case diagrams address the static use case view of a system. These diagrams are especially
important in organizing and modeling the behaviors of a system.

A use case diagram is a just a special kind of diagram and shares the same common
properties as do all other diagrams. A use case diagram differs from all other kinds of
diagrams in its particular content.

Gramin Polytechnic Vishnupuri, Nanded. Page 10


Canteen Ordering System 2020-2021

4.5.1 Contents

Use case diagram commonly contain:

 Use case:

Use case is a description of set of sequence of actions that a system performs that
yields an observable result of value to a particular actor. A use case is used to structure the
behavioral things in a model. A use case is realized by collaboration. Graphically a use case
is rendered as an ellipse with solid lines, usually including only its name, as shown below.

Place order

Fig.4.5(a) Use Case

 Relationships:

Dependency is a semantic relationship between two things in which a change to one


thing may affect the semantics of the other thing. Graphically, a dependency is rendered as
a dashed line, possibly directed, and occasionally including a label. As in below.

Dependency

Fig.4.5(b) Dependency

An association is a structural relationship that describes a set of links, a link


being a connection among objects. Aggregation is a special kind of association,
representing a structural relationship between a whole and its parts. Graphically, an
association is rendered as a solid line, possibly directed, occasionally including a label.

0….1 *
Association

Fig.4.5(c) Association

Gramin Polytechnic Vishnupuri, Nanded. Page 11


Canteen Ordering System 2020-2021

A generalization is a specialization / generalization relationship in which objects of


the specialized element (child) are substitutable for objects of the generalized element
(parent). Graphically, a generalization relationship is rendered as a solid line with a hollow
arrow head pointing to the parent.

Generalization

Fig.4.5(d) Generalization

4.5.1 USE CASE DIAGRAM

Fig.4.5.1 Use Case Diagram

Gramin Polytechnic Vishnupuri, Nanded. Page 12


Canteen Ordering System 2020-2021

4.6 FLOW CHART DIAGRAMS

4.6.1 Flow Chart Diagram of Canteen Ordering System User App

Gramin Polytechnic Vishnupuri, Nanded. Page 13


Canteen Ordering System 2020-2021

4.6.2 Flow Chart Diagram of Canteen Ordering System Admin App

Gramin Polytechnic Vishnupuri, Nanded. Page 14


Canteen Ordering System 2020-2021

4.6.3 Flow Chart Diagram of Canteen Ordering System User App Register
Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 15


Canteen Ordering System 2020-2021

4.6.4 Flow Chart Diagram of Canteen Ordering System User App Home
Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 16


Canteen Ordering System 2020-2021

4.6.5 Flow Chart Cart Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 17


Canteen Ordering System 2020-2021

4.6.6 Flow Chart Diagram of Category Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 18


Canteen Ordering System 2020-2021

4.6.7 Flow Chart Diagram of Contact Us Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 19


Canteen Ordering System 2020-2021

4.6.8 Flow Chart Diagram of Admin Home Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 20


Canteen Ordering System 2020-2021

4.6.9 Flow Chart Diagram of Admin Order Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 21


Canteen Ordering System 2020-2021

4.6.9 Flow Chart Diagram of Admin Update Delivery Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 22


Canteen Ordering System 2020-2021

4.7 ACTIVITY DIAGRAM

4.7.1 Admin App Activity Diagram

4.7.2 User App Activity Diagram

Gramin Polytechnic Vishnupuri, Nanded. Page 23


Canteen Ordering System 2020-2021

CHAPTER 5
SYSTEM IMPLEMENTION
5.1 USER APPLICATION CODING/IMPLEMENTATION

5.1.1 Main Activity:

public class MainActivity extends AppCompatActivity


{ private static int SPLASH_TIME_OUT = 1500;
String user;
String pwd;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paper.init(this);
user=Paper.book().read(Common.USER_KEY);
pwd=Paper.book().read(Common.PWD_KEY);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(user !=null && pwd !=null) {
if (!user.isEmpty() && !pwd.isEmpty()) {
login(user,pwd);
}else{
Intent i = new Intent(MainActivity.this, signin.class);
startActivity(i);
finish(); }
}else {
Intent i = new Intent(MainActivity.this, signin.class);
startActivity(i);
finish();
} } }, SPLASH_TIME_OUT); }
private void login(final String phone, final String pwd) {

FirebaseDatabase database =FirebaseDatabase.getInstance();


final DatabaseReference table_user=database.getReference("User");

if (Common.isConnectedToInternet(getBaseContext())) {
final ProgressDialog mDialog = new
ProgressDialog(MainActivity.this); mDialog.setMessage("Please
Waiting....................................................");
mDialog.show();
table_user.addValueEventListener(new ValueEventListener() {
@Override
Gramin Polytechnic Vishnupuri, Nanded. Page 24
Canteen Ordering System 2020-2021

public void onDataChange(@NonNull DataSnapshot dataSnapshot)


{ if (dataSnapshot.child(phone).exists()) {
mDialog.dismiss();
User user = dataSnapshot.child(phone).getValue(User.class);
user.setPhone(phone);
if (user.getPassword().equals(pwd)) { {
Intent homeIntent = new Intent(MainActivity.this, BottomActivity.class);
Common.currentUser = user;
startActivity(homeIntent);
finish();
} } else {
Toast.makeText(MainActivity.this, "Wrong Password",
Toast.LENGTH_SHORT).show();
} } else {
mDialog.dismiss();
Toast.makeText(MainActivity.this, "User not exits in database",
Toast.LENGTH_SHORT).show();
} }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} });
}else {
Toast.makeText(MainActivity.this,"please check your connection
!!",Toast.LENGTH_SHORT).show();
return;
}}}

Gramin Polytechnic Vishnupuri, Nanded. Page 25


Canteen Ordering System 2020-2021

5.1.2 Signin/Login Activity:

public class signin extends AppCompatActivity


{ EditText edtPhone,edtPassword;
Button
btnSignIn,btnSignUp;
CheckBox ckbRemember;
Gramin Polytechnic Vishnupuri, Nanded. Page 26
Canteen Ordering System 2020-2021

TextView txtForgotPwd;
FirebaseDatabase database ;
DatabaseReference
table_user; ImageView
imageicon; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edtPhone=(EditText) findViewById(R.id.edtPhone);
edtPassword=(EditText)
findViewById(R.id.edtPassword);
btnSignIn=(Button)findViewById(R.id.btnSignIn);
ckbRemember=(CheckBox)findViewById(R.id.ckbRemember);
txtForgotPwd=(TextView) findViewById(R.id.txtForgotPwd);
btnSignUp=(Button)findViewById(R.id.signup);
Paper.init(this);
imageicon=findViewById(R.id.imgicon);
imageicon.setImageDrawable(getResources().getDrawable(R.drawable.logo));
database = FirebaseDatabase.getInstance();
table_user=database.getReference("User");
txtForgotPwd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showForgotPwdDialog();
} });
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent loginIntent=new Intent(signin.this,signup.class);
startActivity(loginIntent);
} });
btnSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Common.isConnectedToInternet(getBaseContext()))
{ if (ckbRemember.isChecked()) {
Paper.book().write(Common.USER_KEY,edtPhone.getText().toString());
Paper.book().write(Common.PWD_KEY,edtPassword.getText().toString());
}
final ProgressDialog mDialog = new
ProgressDialog(signin.this); mDialog.setMessage("Please
Waiting....................................................");
mDialog.show();
table_user.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ if (dataSnapshot.child(edtPhone.getText().toString()).exists()) {
Gramin Polytechnic Vishnupuri, Nanded. Page 27
Canteen Ordering System 2020-2021
mDialog.dismiss();

Gramin Polytechnic Vishnupuri, Nanded. Page 28


Canteen Ordering System 2020-2021

User user = dataSnapshot.child(edtPhone.getText().toString()).getValue(User.class);


user.setPhone(edtPhone.getText().toString());
if (user.getPassword().equals(edtPassword.getText().toString())) {
{
Intent homeIntent = new Intent(signin.this, BottomActivity.class);
Common.currentUser = user;
startActivity(homeIntent);
finish();
table_user.removeEventListener(this);
} } else {
Toast.makeText(signin.this, "Somthing is wrong",
Toast.LENGTH_SHORT).show();
} } else {
mDialog.dismiss();
Toast.makeText(signin.this, "User not exits in database",
Toast.LENGTH_SHORT).show();
} }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} });
}else {
Toast.makeText(signin.this,"please check your connection
!!",Toast.LENGTH_SHORT).show();
return;
} } });
String user= Paper.book().read(Common.USER_KEY);
String pwd= Paper.book().read(Common.PWD_KEY);
}
private void showForgotPwdDialog() {
AlertDialog.Builder builder = new
AlertDialog.Builder(this); builder.setTitle("Forget
Password"); builder.setMessage("Enter your secure code");
LayoutInflater inflater =this.getLayoutInflater();
View forgot_view=inflater.inflate(R.layout.forgot_password_layout,null);
builder.setView(forgot_view);
builder.setIcon(R.drawable.logo);
final EditText edtPhone=(EditText)forgot_view.findViewById(R.id.edtPhone);
final EditText edtSecureCode=(EditText)forgot_view.findViewById(R.id.edtSecureCode);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i)
{ table_user.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User
user=dataSnapshot.child(edtPhone.getText().toString()).getValue(User.cl
ass); if
Gramin Polytechnic Vishnupuri, Nanded. Page 29
Canteen Ordering System 2020-2021
(user.getSecureCode().equals(edtSecureCode.getText().toString()).

Gramin Polytechnic Vishnupuri, Nanded. Page 30


Canteen Ordering System 2020-2021

Toast.makeText(signin.this,"Your Password
:"+user.getPassword(),Toast.LENGTH_SHORT).show();
else
Toast.makeText(signin.this,"Wrong
Secure Code",Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} }); } });
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
} });
builder.show();
}}

Login Form

Gramin Polytechnic Vishnupuri, Nanded. Page 31


Canteen Ordering System 2020-2021

5.1.3 Signup/Register Activity


public class signup extends AppCompatActivity
{ Button btnSignUp,btnSignIn;
EditText
edtPhone,edtName,password,edtrepassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
edtName=(EditText)findViewById(R.id.edtName);
edtrepassword=(EditText)findViewById(R.id.edtrepassword);
password=(EditText)findViewById(R.id.password);
edtPhone=(EditText)findViewById(R.id.edtPhone);
btnSignUp=(Button)findViewById(R.id.btnSignUp);
btnSignIn=findViewById(R.id.sign_in_button);
final FirebaseDatabase database= FirebaseDatabase.getInstance();
final DatabaseReference table_user=database.getReference("User");
btnSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent loginIntent=new Intent(signup.this, signin.class);
startActivity(loginIntent);
} });
btnSignUp.setOnClickListener(new View.OnClickListener()
{ Boolean failFlag;
@Override
public void onClick(View v) {
if (edtName.getText().toString().trim().length() == 0)
{ edtName.setError("Enter your Name");
} else if (edtPhone.getText().toString().trim().length() == 0 )
{ edtPhone.setError("Enter your 10 Digit Mobile No");
} else if (edtPhone.getText().toString().trim().length() > 10)
{ edtPhone.setError("Enter your 10 Digit Mobile No");
} else if (edtPhone.getText().toString().trim().length() <=9)
{ edtPhone.setError("Enter your 10 Digit Mobile No");
} else if (password.getText().toString().trim().length() == 0)
{ password.setError("Enter Password");
} else if (edtrepassword.getText().toString().trim().length() !
= password.getText().toString().trim().length()) {
edtrepassword.setError("Enter Confirm Password");
} else {
if (Common.isConnectedToInternet(getBaseContext())) {
final ProgressDialog mDialog = new
ProgressDialog(signup.this); mDialog.setMessage("Please
Waiting....................................................");
mDialog.show();
Gramin Polytechnic Vishnupuri, Nanded. Page 32
Canteen Ordering System 2020-2021

table_user.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ if (!dataSnapshot.child(edtPhone.getText().toString()).exists()) {
mDialog.dismiss();
String name = edtName.getText().toString();
String pass = password.getText().toString();
String secureCode = edtrepassword.getText().toString();
User user = new User(name, pass, secureCode);
table_user.child(edtPhone.getText().toString()).setValue(user);
Toast.makeText(signup.this, "Sign Up Successfully", Toast.LENGTH_SHORT).show();
Intent login_intent=new Intent(signup.this, signin.class);
startActivity(login_intent);

else { }

if(dataSnapshot.child(edtPhone.getText().toString()).exists())
{ mDialog.dismiss();
Toast.makeText(signup.this, "You have Sign Up Successfully,Please
Login for continue your shopping", Toast.LENGTH_SHORT).show();
Intent login_intent=new Intent(signup.this, signin.class);
startActivity(login_intent);
} } }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} });
} else {
Toast.makeText(signup.this, "please check your connection !!",
Toast.LENGTH_SHORT).show();
return;
}}
} });
}
}

Gramin Polytechnic Vishnupuri, Nanded. Page 33


Canteen Ordering System 2020-2021

Registration Form
5.1.4 Bottom Activity (Home)
public class BottomActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference
category;

Gramin Polytechnic Vishnupuri, Nanded. Page 34


Canteen Ordering System 2020-2021
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;

Gramin Polytechnic Vishnupuri, Nanded. Page 35


Canteen Ordering System 2020-2021

TextView txtFullName;
RecyclerView
recycler_menu;
RecyclerView.LayoutManager layoutManager;
SwipeRefreshLayout swipeRefreshLayout;
CounterFab fab;
View view;
HashMap<String,String>
image_list; SliderLayout mSlider;
Toolbar toolbar;
TabLayout
tabLayout;
static FrameLayout viewPager;
TabItem tabHome, tabCart, tabCategory, tabCustomer;
private int[] tabIcons = {
R.drawable.house, R.drawable.list, R.drawable.cart, R.drawable.cussupport
};
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
MultiDex.install(this);
DrawerLayout
drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,
drawer,toolbar,0,0);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView
navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView =navigationView.getHeaderView(0);
txtFullName=(TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
tabLayout = findViewById(R.id.tablayout);
tabHome = findViewById(R.id.tabHome);
tabCategory = findViewById(R.id.tabCategory);
tabCart = findViewById(R.id.tabCart);
tabCustomer = findViewById(R.id.tabContact);
viewPager = findViewById(R.id.viewPager);
Fragment fragment = new Home();
getSupportFragmentManager().beginTransaction()
.replace(R.id.viewPager, fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();
Gramin Polytechnic Vishnupuri, Nanded. Page 36
Canteen Ordering System 2020-2021
tabClick();
setupTabIcons();
}

Gramin Polytechnic Vishnupuri, Nanded. Page 37


Canteen Ordering System 2020-2021

private void tabClick() {


tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab)
{ switch (tab.getPosition()) {
case 0:
Fragment fragment1 = new
Home();
moveToFragment(fragment1);
break;
case 1:
Fragment fragment2 = new CategoryFragment();
moveToFragment(fragment2);
break;
case 2:
Fragment fragment3 = new Cart();
moveToFragment(fragment3);
break;
case 3:
Fragment fragment4 = new CustomerSupportFragment();
moveToFragment(fragment4);
break;
} }
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
} }); }
private void moveToFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.viewPager, fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
{ int id = item.getItemId();
if(id==R.id.nav_menu){
Fragment fragment1 = new Home();
moveToFragment(fragment1);
}else if(id==R.id.nav_goal){
Gramin Polytechnic Vishnupuri, Nanded. Page 38
Canteen Ordering System 2020-2021

Fragment categoryFragment= new


com.spam.maddy.automatedcanteenordersystem.CustomerSupportFragment();
moveToFragment(categoryFragment);
}else if(id==R.id.nav_orders){
Fragment orderStatus= new OrderStatus();
moveToFragment(orderStatus);
}else if(id==R.id.nav_cart)
{ Fragment cart= new Cart();
moveToFragment(cart);
} else if(id==R.id.nav_log_out){
Paper.book().destroy();
Intent siIntent=new Intent(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this,
com.spam.maddy.automatedcanteenordersystem.signin.class);
signIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(signIntent);
}else if (id==R.id.nav_change_password){
showChangePasswordDialog();
}
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static void setCurrentItem(int item, boolean smoothScroll) {
}
private void showChangePasswordDialog()
{ AlertDialog.Builder alertDialog = new
AlertDialog.Builder(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this);
alertDialog.setTitle("CHANGE PASSWORD");
alertDialog.setMessage("Please fill all information");
LayoutInflater inflater= LayoutInflater.from(this);
View layout_pwd=inflater.inflate(R.layout.change_password_layout,null);
MaterialEditText edtPassword=layout_pwd.findViewById(R.id.editPassword);
MaterialEditText
edtNewPassword=layout_pwd.findViewById(R.id.editNewPassword);
MaterialEditText
edtRepeatPassword=layout_pwd.findViewById(R.id.editRepeatPassword);
alertDialog.setView(layout_pwd);
alertDialog.setPositiveButton("CHANGE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i)
{ android.app.AlertDialog waitingDialog = new
SpotsDialog(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this);
waitingDialog.show();
if (edtPassword.getText().toString().equals(Common.currentUser.getPassword()))
{ if (edtNewPassword.getText().toString().equals(edtRepeatPassword.getText().toString())) {
Map<String, Object> passwordUpdate = new HashMap<>();
Gramin Polytechnic Vishnupuri, Nanded. Page 39
Canteen Ordering System 2020-2021

passwordUpdate.put("password", edtNewPassword.getText().toString());
DatabaseReference user = FirebaseDatabase.getInstance().getReference("User");
user.child(Common.currentUser.getPhone()).updateChildren(passwordUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
waitingDialog.dismiss();
Toast.makeText(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this,
"Password was update", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this,
e.getMessage(), Toast.LENGTH_SHORT).show();
} }); } else {
waitingDialog.dismiss();
Toast.makeText(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this, "New
Password doesn't match", Toast.LENGTH_SHORT).show();
} }
else {
Toast.makeText(com.spam.maddy.automatedcanteenordersystem.BottomActivity.this, "Wrong
old password", Toast.LENGTH_SHORT).show();
} } });
alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
} });
alertDialog.show();
}
public void onBackPressed(){
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
} }
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}

Gramin Polytechnic Vishnupuri, Nanded. Page 40


Canteen Ordering System 2020-2021

Home Ativity Dashboard

5.1.5 Buy Activity

public class BuyActivity extends Fragment


{ NumberFormat fmt;
Locale locale;
String
address,comment; long
total=0;
List<Order> cart1=new ArrayList<>();
FirebaseDatabase database;
DatabaseReference
requests,deliveryDatabase; CartAdapter
adapter;
TextView
totalBill1,userName,userNo,deliveryCharge,netAmount; Button
btnBuy;

Gramin Polytechnic Vishnupuri, Nanded. Page 41


Canteen Ordering System 2020-2021
MaterialEditText
edtAddress,edtComment; View view;
String na;

Gramin Polytechnic Vishnupuri, Nanded. Page 42


Canteen Ordering System 2020-2021

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_buy, container, false);
database= FirebaseDatabase.getInstance();
requests=database.getReference("Restaurants").child("02").child("detail").child("Requests");
locale = new Locale("en","IN");
fmt=NumberFormat.getCurrencyInstance(locale);
totalBill1=(TextView)view.findViewById(R.id.totalBill1);
userName=(TextView)view.findViewById(R.id.userName);
userNo=(TextView)view.findViewById(R.id.userNo);
deliveryCharge=(TextView)view.findViewById(R.id.deliveryCharge);
netAmount=(TextView)view.findViewById(R.id.netAmount);
btnBuy=(Button)view.findViewById(R.id.btnBuy1);
userName.setText(Common.currentUser.getName());
userNo.setText(Common.currentUser.getPhone());
cart1=new Database(getContext()).getCarts(Common.currentUser.getPhone());
adapter=new CartAdapter(cart1,this);
adapter.notifyDataSetChanged();
for(Order order:cart1)
total+=(Integer.parseInt(order.getDiscount()))*(Integer.parseInt(order.getQuantity()));
totalBill1.setText(fmt.format(total));
deliveryDatabase=database.getReference("Delivery");
deliveryDatabase.child("deliveryCharge").addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
deliveryCharge.setText(String.valueOf(snapshot.getValue()));
int dc= Integer.parseInt(String.valueOf(snapshot.getValue()));
na= String.valueOf(dc+total);
netAmount.setText(na);
}
@Override
public void onCancelled(DatabaseError databaseError) {
} });
edtAddress=(MaterialEditText)view.findViewById(R.id.editAddress1);
edtComment=(MaterialEditText)view.findViewById(R.id.editComment1);
RadioButton
Address1=(RadioButton)view.findViewById(R.id.rdiHomeAddress1);
rdiHomeAddress1.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){

Gramin Polytechnic Vishnupuri, Nanded. Page 43


Canteen Ordering System 2020-2021

if (Common.currentUser.getHomeAddress()!=null||!
TextUtils.isEmpty(Common.currentUser.getH omeAddress())) {
address = Common.currentUser.getHomeAddress();
edtAddress.setText(Common.currentUser.getHomeAddress());
}else {
Toast.makeText(getContext(), "Please Address", Toast.LENGTH_SHORT).show();
} } } });
btnBuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (total >= 10) {
address = edtAddress.getText().toString();
comment =
edtComment.getText().toString(); if
(TextUtils.isEmpty(address)) {
edtAddress.setError("Enter Your Address");
Toast.makeText(getContext(), "Please enter address ", Toast.LENGTH_SHORT).show();
return;
}
Request rqst = new Request(Common.currentUser.getPhone(),
Common.currentUser.getName(), address,na,"0", comment,cart1,
Common.restaurantSelected );
String order_number = String.valueOf(System.currentTimeMillis());
requests.child(order_number).setValue(request);
new
Database(getContext()).cleanCart(Common.currentUser.getPhone());
Toast.makeText(getContext(), "Thank You, Order Place",
Toast.LENGTH_SHORT).show();
Fragment fragment = new Home();
getFragmentManager().beginTransaction()
.replace(R.id.viewPager, fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
else {
Toast.makeText(getContext(),"Please Buy Minimum 100 Rs, Thank
You!"+total,Toast.LENGTH_SHORT).show();
} } });
return view;
}}

Gramin Polytechnic Vishnupuri, Nanded. Page 44


Canteen Ordering System 2020-2021

Buy Activity
5.1.6 Cart Activity

public class Cart extends Fragment /*implements GoogleApiClient.ConnectionCallbacks,


GoogleApiClient.OnConnectionFailedListener, LocationListener */{
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
Gramin Polytechnic Vishnupuri, Nanded. Page 45
Canteen Ordering System 2020-2021

DatabaseReference requests;
Button btnPlace;
ImageButton btnDelete;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
TextView totalBill;
NumberFormat
fmt; Locale locale;
String
address,comment;
double total=0;
View
view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_cart, container, false);
locale = new Locale("en","IN");
fmt=NumberFormat.getCurrencyInstance(locale);
database= FirebaseDatabase.getInstance();
requests=database.getReference("Restaurants").child(Common.restaurantSelected).child("detail"
).child("Requests");
recyclerView=(RecyclerView)view.findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
cart=new
Database(getContext()).getCarts(Common.currentUser.getPhone());
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
btnPlace=(Button)view.findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cart.size() > 0) {
Fragment fragment = new BuyActivity();
getFragmentManager().beginTransaction()
.replace(R.id.viewPager, fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}else {
Toast.makeText(getContext(), "Your cart is empty !!!",
Toast.LENGTH_SHORT).show();
} } });
loadListFood();
return view;
}
Gramin Polytechnic Vishnupuri, Nanded. Page 46
Canteen Ordering System 2020-2021
public void loadListFood() {
adapter.notifyDataSetChanged();

Gramin Polytechnic Vishnupuri, Nanded. Page 47


Canteen Ordering System 2020-2021

for(Order order:cart)
total+=(Integer.parseInt(order.getDiscount()))*(Integer.parseInt(order.getQuantity()));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle().equals(Common.DELETE))
deleteCart(item.getOrder());
return true;
}
private void deleteCart(int position) {
cart.remove(position);
new Database(getContext()).cleanCart(Common.currentUser.getPhone());
for(Order item:cart)
new Database(getContext()).addToCart(item);
loadListFood();
}}

Product List

Gramin Polytechnic Vishnupuri, Nanded. Page 48


Canteen Ordering System 2020-2021

5.1.7 CustomerSupport Activity


public class CustomerSupportFragment extends Fragment
{ View view;
ImageButton
whatsappBtn,smsBtn,gmailBtn,phoneBtn; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_customer_support, container, false);
whatsappBtn=(ImageButton)view.findViewById(R.id.whatsappBtn);
smsBtn=(ImageButton)view.findViewById(R.id.smsBtn);
gmailBtn=(ImageButton)view.findViewById(R.id.emailBtn);
phoneBtn=(ImageButton)view.findViewById(R.id.phoneBtn);
whatsappBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("smsto:" + "9689222645");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));
} });
smsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "sms:" + ""));
intent.putExtra( "sms_body", "" );
startActivity(intent);
} });
gmailBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new
String[]{"easysaleonlineshoping@gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT,
""); i.putExtra(Intent.EXTRA_TEXT ,
""); try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex)
{ Toast.makeText(getContext(), "There are no email clients installed.",
Toast.LENGTH_SHORT).show();
} } });
phoneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri number = Uri.parse("tel:
");
Gramin Polytechnic Vishnupuri, Nanded. Page 49
Canteen Ordering System 2020-2021

Intent callIntent = new Intent(Intent.ACTION_DIAL, number);


startActivity(callIntent);
} });
return view;
}}

Customer Support Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 50


Canteen Ordering System 2020-2021

5.1.8 Fooddetail Activity


public class FoodDetail extends Fragment {
TextView
food_name,food_price,food_description,food_detail_disscount_price;
ImageView food_image;
CollapsingToolbarLayout
collapsingToolbarLayout; CounterFab btnCart;
ElegantNumberButton
numberButton; String foodId="";
Food currentFood;
FirebaseDatabase database;
DatabaseReference
foods,ratingTb1 View view;
Button
btnShowComment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_food_detail, container, false);
database= FirebaseDatabase.getInstance();
foods=database.getReference("Restaurants").child("02")
.child("detail").child("Foods");
numberButton=(ElegantNumberButton)view.findViewById(R.id.number_button);
btnCart=(CounterFab) view.findViewById(R.id.btnCart);
btnCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isExists=new
Database(getContext()).chechFoodExists(foodId,Common.currentUser.getPhone());
if (!isExists) {
new Database(getContext()).addToCart(new Order(
Common.currentUser.getPhone(),foodId,currentFood.getName(),numberButton.getNumber(),cur
rentFood.getPrice(),currentFood.getDiscount(),currentFood.getImage() ));
}else {
new Database(getContext()).increaseCart(Common.currentUser.getPhone(),foodId);
}
Toast.makeText(getContext(),"Added to Cart",Toast.LENGTH_SHORT).show();
}
});
btnCart.setCount(new
Database(getContext()).getCountCart(Common.currentUser.getPhone()));
food_description=(TextView)view.findViewById(R.id.food_description);
food_name=(TextView)view.findViewById(R.id.food_name);
food_price=(TextView)view.findViewById(R.id.food_price);
food_detail_disscount_price=(TextView)view.findViewById(R.id.disscountPriceDetail);
food_image=(ImageView)view.findViewById(R.id.img_food);
collapsingToolbarLayout=(CollapsingToolbarLayout)view.findViewById(R.id.collapsing);
Gramin Polytechnic Vishnupuri, Nanded. Page 51
Canteen Ordering System 2020-2021
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar);

Gramin Polytechnic Vishnupuri, Nanded. Page 52


Canteen Ordering System 2020-2021

collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppbar);
String value = getArguments().getString("FoodId");
if(com.spam.maddy.automatedcanteenordersystem.FoodDetail.this!=null) if(!
foodId.isEmpty()){
if (Common.isConnectedToInternet(getContext())) {
getDetailFood(foodId);
}else {
Toast.makeText(getContext(),"check your connection !!",Toast.LENGTH_SHORT).show();
} }
return view;
}
private void getDetailFood(final String foodId)
{ foods.child(foodId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
currentFood=dataSnapshot.getValue(Food.class);
Picasso.with(getContext()).load(currentFood.getImage()).into(food_image);
collapsingToolbarLayout.setTitle(currentFood.getName());
food_price.setText(String.format("MRP ₹ %s",current
ood.getPrice()));
food_detail_disscount_price.setText(String.format("₹ ",cu
rrentFood.getDiscount()));
food_name.setText(currentFood.getName());
food_description.setText(currentFood.getDescription());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}}

Gramin Polytechnic Vishnupuri, Nanded. Page 53


Canteen Ordering System 2020-2021

Food Detail Information Activity


5.1.8 FoodList Activity
public class FoodList extends Fragment
{ RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference foodList,itemcount;
FirebaseRecyclerAdapter<Food, FoodViewHolder> adapter;
Gramin Polytechnic Vishnupuri, Nanded. Page 54
Canteen Ordering System 2020-2021

List<String> suggestList= new ArrayList<>();


MaterialSearchBar materialSearchBar;
private int scrollPosition = 0;
private Parcelable listState;
private boolean shouldKeepScrollPosition = true;
String categoryId="";
TextView
txtCount; Database
localDB; View
view;
SwipeRefreshLayout
swipeRefreshLayout; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_food_list, container, false);
setRetainInstance(true);
database= FirebaseDatabase.getInstance();
foodList=database.getReference("Restaurants").child("02")
.child("detail").child("Foods");
String value = getArguments().getString("CategoryId");
localDB=new Database(getContext());
swipeRefreshLayout=(SwipeRefreshLayout)view.findViewById(R.id.swipe_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,android.R.color.holo_gree
n_dark,
android.R.color.holo_orange_dark,android.R.color.holo_blue_dark);
swipeRefreshLayout.setOnRefreshListener(new
SwipeRefreshLayout.OnRefreshListener()
{
@Override
public void onRefresh() { if(getActivity()!
=null
categoryId=value;
if(!categoryId.isEmpty() && categoryId != null){
if
(Common.isConnectedToInternet(getContext())
) loadListFood(categoryId);
else{
Toast.makeText(getContext(),"please !!",Toast.LENGTH_SHORT).show();
return;
} }
loadSuggest();
} });
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
if(getContext()!=null)
categoryId=value;
Gramin Polytechnic Vishnupuri, Nanded. Page 55
Canteen Ordering System 2020-2021
if(!categoryId.isEmpty() && categoryId != null){
if (Common.isConnectedToInternet(getContext()))

Gramin Polytechnic Vishnupuri, Nanded. Page 56


Canteen Ordering System 2020-2021

loadListFood(categoryId);
else{
Toast.makeText(getContext(),"connection !!",Toast.LENGTH_SHORT).show();
return;
} } } });
recyclerView=(RecyclerView)view.findViewById(R.id.recycler_food);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
txtCount=(TextView)view.findViewById(R.id.txtCount);
foodList.orderByChild("menuId").equalTo(value).addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getChildrenCount()); //prints "Do you have data? You'll
love Firebase." }
@Override
public void onCancelled(atabaseError databaseError) {
} });
mBundleRecyclerViewState = new Bundle();
mListState = recyclerView.getLayoutManager().onSaveInstanceState();
mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, mListState);
return view;
}
private void loadSuggest() {
foodList.orderByChild("menuId").equalTo(categoryId).addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ for(DataSnapshot postSnapshot:dataSnapshot.getChildren()){
Food
item=postSnapshot.getValue(Food.class);
suggestList.add(item.getName());
}
materialSearchBar.setLastSuggestions(suggestList);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} }); }
private void loadListFood(String categoryId) {
Query
searchByName=foodList.orderByChild("menuId").equalTo(categoryId);
FirebaseRecyclerOptions<Food> foodOptions=new
FirebaseRecyclerOptions.Builder<Food>()
.setQuery(searchByName,Food.class)
.build();
Gramin Polytechnic Vishnupuri, Nanded. Page 57
Canteen Ordering System 2020-2021
adapter=new FirebaseRecyclerAdapter<Food, FoodViewHolder>(foodOptions) {

Gramin Polytechnic Vishnupuri, Nanded. Page 58


Canteen Ordering System 2020-2021

@Override
protected void onBindViewHolder(@NonNull FoodViewHolder viewHolder, int
position, @NonNull Food model) {
viewHolder.food_price.setText(String.format("MRP ₹ %s",model.getPrice().toString()));
String emptyStr=model.getPrice();
if(!emptyStr.equals("000"))
{ viewHolder.food_name.setText(model.getName());
viewHolder.quick_cart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{ boolean isExists=new
Database(getContext()).chechFoodExists(adapter.getRef(position).getKey(),Common.currentUse
r.getPhone());
if (!isExists) {
new Database(getContext()).addToCart(new
Order( Common.currentUser.getPhone(),adapter.getRef(position).getKe
y(), model.getName(),viewHolder.numberButton.getNumber(),
model.getPrice(),model.getDiscount(),model.getImage() ));
}else {
new
Database(getContext()).increaseCart(Common.currentUser.getPhone(),adapter.getRef(position).
getKey());
}
Toast.makeText(getContext(), "Added to Cart",
Toast.LENGTH_SHORT).show();
} });
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick)
{ mBundleRecyclerViewState = new Bundle();
mListState = recyclerView.getLayoutManager().onSaveInstanceState();
mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, mListState);
Fragment fragment = new FoodDetail();
Bundle args = new Bundle();
args.putString("FoodId",adapter.getRef(position).getKey());
fragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.viewPager, fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();
} }); }
else{
viewHolder.food_name.setText("Product Not Available");
viewHolder.quick_cart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Product Not Available", Toast.LENGTH_SHORT).show();

Gramin Polytechnic Vishnupuri, Nanded. Page 59


Canteen Ordering System 2020-2021

} });
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick)
Toast.makeText(getContext(), "Product Not Available", Toast.LENGTH_SHORT).show();
} }); }
viewHolder.food_price.setPaintFlags(viewHolder.food_price.getPaintFlags() )
viewHolder.disscountPrice.setText(String.format("₹ %s",model.getDiscount().toString()));
Picasso.with(getContext()).load(model.getImage()).into(viewHolder.food_image);
if
(localDB.isFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone()))
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp);
viewHolder.fav_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!localDB.isFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone()))
{
calDB.addToFavorites(adapter.getRef(position).getKey(),Common.currentUser.getPhone());
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_black_24dp);
Toast.makeText(getContext(),""+model.getName()+" was added to
Favorites",Toast.LENGTH_SHORT).show();
}else{ localDB.removeToFavorites(adapter.getRef(position).getKey(),Common.cu
rrentUser.getPhone()
);
viewHolder.fav_image.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Toast.makeText(getContext(),""+model.getName()+" was remove from
Favorites",Toast.LENGTH_SHORT).show();
} } });
final Food local=model;
}
@NonNull
@Override
public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View itemView= LayoutInflater.from(parent.getContext())
.inflate(R.layout.food_item,parent,false);
return new FoodViewHolder(itemView);
} };
adapter.startListening();
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
Gramin Polytechnic Vishnupuri, Nanded. Page 60
Canteen Ordering System 2020-2021

@Override
public void onResume() {
super.onResume();
if (mBundleRecyclerViewState != null) {
mListState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(mListState);
}
recyclerView.setLayoutManager(layoutManager);
}
@Override
public void onPause() {
super.onPause();
mBundleRecyclerViewState = new Bundle();
mListState = recyclerView.getLayoutManager().onSaveInstanceState();
mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE,
mListState);
}}

Gramin Polytechnic Vishnupuri, Nanded. Page 61


Canteen Ordering System 2020-2021
Product Category Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 62


Canteen Ordering System 2020-2021

5.1.8 OrderList Activity


public class OrderStatus extends Fragment
{ public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
FirebaseDatabase database;
DatabaseReference requests;
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_order_status, container, false);
database= FirebaseDatabase.getInstance();
requests=database.getReference("Restaurants").child("02").child("detail").child("Requests");
recyclerView=(RecyclerView)view.findViewById(R.id.listOrders);
recyclerView.setHasFixedSize(true);
layoutManager=new
LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
loadOrders(Common.currentUser.getPhone());
return view;

private void loadOrders(String phone) {


Query getOrderByUser=requests.orderByChild("phone")
.equalTo(phone);
FirebaseRecyclerOptions<Request> orderOptions=new
FirebaseRecyclerOptions.Builder<Request>()
.setQuery(getOrderByUser,Request.class)
.build();
adapter= new FirebaseRecyclerAdapter<Request, OrderViewHolder>(orderOptions) {
@Override
protected void onBindViewHolder(@NonNull OrderViewHolder viewHolder, int
position, @NonNull Request model) {
viewHolder.txtOrderId.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(Common.convertCodeToStatus(model.getStatus()));
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderPhone.setText(model.getPhone());
viewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Common.currentRequest=model;
Fragment fragment = new OrderDetail();
Bundle args = new Bundle();
args.putString("Order
ID",adapter.getRef(position).getKey());
fragment.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.viewPager,
Gramin Polytechnic Vishnupuri, Nanded. Page 63
Canteen Ordering System 2020-2021
fragment,
fragment.getClass().getSimpleName()).addToBackStack(null).commit();

Gramin Polytechnic Vishnupuri, Nanded. Page 64


Canteen Ordering System 2020-2021

} }); }
@NonNull
@Override
public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View itemView= LayoutInflater.from(parent.getContext())
.inflate(R.layout.order_layout,parent,false);
return new OrderViewHolder(itemView);
} };
adapter.startListening();
recyclerView.setAdapter(adapter);
}
@Override
public void onStop() {
super.onStop();
}}

Old Order List Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 65


Canteen Ordering System 2020-2021

5.1.9 OrderDetails Activity


public class OrderDetail extends Fragment {

TextView
order_id,order_phone,order_address,order_total,order_comment; String
order_id_value="";
RecyclerView lstFoods;
RecyclerView.LayoutManager layoutManager;
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.activity_order_detail, container, false);
order_id=(TextView)view.findViewById(R.id.order_id1);
order_phone=(TextView)view.findViewById(R.id.order_phone1);
order_address=(TextView)view.findViewById(R.id.order_address1);
order_total=(TextView)view.findViewById(R.id.order_total1);
order_comment=(TextView)view.findViewById(R.id.order_comment1);
lstFoods=(RecyclerView)view.findViewById(R.id.lstFoods1);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
lstFoods.setLayoutManager(layoutManager);
lstFoods.setItemAnimator(new DefaultItemAnimator());
if (getActivity()!=null) {
String value = getArguments().getString("Order Id");
order_id_value = value;
}
order_id.setText(order_id_value);
order_phone.setText(Common.currentRequest.getPhone());
order_total.setText(Common.currentRequest.getTotal());
order_address.setText(Common.currentRequest.getAddress());
order_comment.setText(Common.currentRequest.getComment());
OrderDetailAdapter adapter=new
OrderDetailAdapter(Common.currentRequest.getFoods(),this);
adapter.notifyDataSetChanged();
lstFoods.setAdapter(adapter);
return view;
}}

Gramin Polytechnic Vishnupuri, Nanded. Page 66


Canteen Ordering System 2020-2021

Order Detail Activity

Gramin Polytechnic Vishnupuri, Nanded. Page 67


Canteen Ordering System 2020-2021

5.2 Common Classes in both application:


5.2.1 OrderViewHolder Class
public class OrderViewHolder extends RecyclerView.ViewHolder{// implements
View.OnClickListener {
public TextView
txtOrderId,txtOrderStatus,txtOrderPhone,txtOrderAddress,btnDetail; public
OrderViewHolder(@NonNull View itemView) {
super(itemView)
txtOrderAddress=(TextView)itemView.findViewById(R.id.order_address);
txtOrderId=(TextView)itemView.findViewById(R.id.order_id);
txtOrderStatus=(TextView)itemView.findViewById(R.id.order_status);
txtOrderPhone=(TextView)itemView.findViewById(R.id.order_phone);
btnDetail=(TextView)itemView.findViewById(R.id.btnDetail);
}}

5.2.2 VaccineViewHolder Class


public class FoodViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
public TextView food_name,food_price,disscountPrice;
public Button fb,quick_cart;
public ImageView food_image,fav_image;
public ElegantNumberButton numberButton;
private ItemClickListener itemClickListener;
public void setItemClickListener(ItemClickListener itemClickListener)
{ this.itemClickListener = itemClickListener;
}
public FoodViewHolder(@NonNull View itemView) {
super(itemView);
food_name=(TextView)itemView.findViewById(R.id.food_name);
food_image=(ImageView)itemView.findViewById(R.id.food_image);
fav_image=(ImageView)itemView.findViewById(R.id.fav);
quick_cart=(Button)itemView.findViewById(R.id.btn_quick_cart);
food_price=(TextView)itemView.findViewById(R.id.food_price);
disscountPrice=(TextView)itemView.findViewById(R.id.disscountPrice);
numberButton=(ElegantNumberButton)itemView.findViewById(R.id.number_button1);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}

Gramin Polytechnic Vishnupuri, Nanded. Page 68


Canteen Ordering System 2020-2021

5.2.3 Common Class


public class Common {
public static String topicName="News"
public static User currentUser;
public static Request currentRequest;
public static String restaurantSelected="";
public static String PHONE_TEXT="userPhone";
public static final String INTENT_FOOD_ID="FoodId";
public static String DELETE="Delete"
public static String USER_KEY="User";
public static String PWD_KEY="password";
public static final String BASE_URL="https://fcm.googleapis.com/"
public static final String GOOGLE_API_URL="https://maps.googleapis.com/";
public static String convertCodeToStatus(String status)
if(status.equals("0"))
return "Placed";
else if (status.equals("1"))
return "On my way";
else if (status.equals("2"))
return "Shipping";
else
return "Shipped";
}
public static boolean isConnectedToInternet(Context context){ ConnectivityManager
connectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVI
TY_SERVICE);
if (connectivityManager != null){
NetworkInfo[]
info=connectivityManager.getAllNetworkInfo(); if (info !=
null){
for (int i=0;i<info.length;i++){
if (info[i].getState() == NetworkInfo.State.CONNECTED)
return true;
} } }
return false;
}}

5.2.4 User Class


public class User
{ private String
Name;
private String Password;
private String Phone;
private String IsStaff;
private String secureCode;
Gramin Polytechnic Vishnupuri, Nanded. Page 69
Canteen Ordering System 2020-2021
private String homeAddress;

Gramin Polytechnic Vishnupuri, Nanded. Page 70


Canteen Ordering System 2020-2021

private String balance;


public User(){
}
public User(String name, String password,String secureCode)
{ Name = name;
Password = password;
IsStaff="false";
this.secureCode=secureCode;
}
public String getBalance()
{ return balance;
}
public void setBalance(String balance)
{ this.balance = balance;
}
public String getSecureCode()
{ return secureCode;
}
public void setSecureCode(String secureCode)
{ this.secureCode = secureCode;
}
public String getIsStaff()
{ return IsStaff;
}
public void setIsStaff(String isStaff)
{ IsStaff = isStaff;
}
public String getPhone()
{ return Phone;
}
public void setPhone(String phone)
{ Phone = phone;
}

public String getName()


{ return Name;
}
public void setName(String name){
Name=name;
}
public String getPassword()
{ return Password;
}
public void setPassword(String password){
Password=password;
}

Gramin Polytechnic Vishnupuri, Nanded. Page 71


Canteen Ordering System 2020-2021

public String getHomeAddress()


{ return homeAddress;
}
public void setHomeAddress(String homeAddress)
{ this.homeAddress = homeAddress;
}
}

7.2.5 Food Class


public class Food {
private String Name,Image,Description,Price,Discount,MenuId;
public Food(){
}
public Food(String name, String image, String description, String price, String discount, String
menuId) {
Name = name;
Image = image;
Description = description;
Price = price;
Discount = discount;
MenuId = menuId;
}
public String getName()
{ return Name;
}
public void setName(String name)
{ Name = name;
}
public String getImage()
{ return Image;
}
public void setImage(String image)
{ Image = image;
}
public String getDescription()
{ return Description;
}
public void setDescription(String description)
{ Description = description;

public String getPrice()


{ return Price;
}

Gramin Polytechnic Vishnupuri, Nanded. Page 72


Canteen Ordering System 2020-2021

public void setPrice(String price)


{ Price = price;
}
public String getDiscount()
{ return Discount;
}
public void setDiscount(String discount)
{ Discount = discount;
}
public String getMenuId() {
return MenuId;
}
public void setMenuId(String menuId)
{ MenuId = menuId;
}
}

5.2.6 Order Class


public class Order {

private String UserPhone;


private String ProductId;
private String ProductName;
private String Quantity;
private String Price;
private String Discount;
private String Image;
public Order(){
}
public Order(String userPhone, String productId, String productName, String quantity, String
price, String discount, String image) {
UserPhone = userPhone;
ProductId = productId;
ProductName = productName;
Quantity = quantity;
Price = price;
Discount = discount;
Image = image;
}
public String getUserPhone()
{ return UserPhone;
}
public void setUserPhone(String userPhone)
{ UserPhone = userPhone;

Gramin Polytechnic Vishnupuri, Nanded. Page 73


Canteen Ordering System 2020-2021

}
public String getProductId()
{ return ProductId;
}
public void setProductId(String productId)
{ ProductId = productId;
}
public String getProductName()
{ return ProductName;
}
public void setProductName(String productName)
{ ProductName = productName;
}
public String getQuantity()
{ return Quantity;
}
public void setQuantity(String quantity)
{ Quantity = quantity;
}
public String getPrice()
{ return Price;
}
public void setPrice(String price)
{ Price = price;
}
public String getDiscount()
{ return Discount;
}
public void setDiscount(String discount)
{ Discount = discount;
}
public String getImage()
{ return Image;
}
public void setImage(String image)
{ Image = image;
}
}

5.2.7 Category Class


public class Category
{ private String
Name; private String
Image; public
Category(){
}
Gramin Polytechnic Vishnupuri, Nanded. Page 74
Canteen Ordering System 2020-2021

public Category(String name,String image){


Name=name;
Image=image;
}
public String getName()
{ return Name;
}
public void setName(String name){
Name=name;
}
public String getImage()
{ return Image;
}
public void setImage(String image){
Image=image;
}
}

5.3 Admin Application Code


5.3.1 Home Activity
public class Home extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
TextView txtFullName;
FirebaseDatabase database;
DatabaseReference categories;
FirebaseStorage storage;
StorageReference
storageReference;
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
EditText edtName;
Button
btnSelect,btnUpload;
Category newCategory;
DrawerLayout drawer;
Uri
saveUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu Management");

Gramin Polytechnic Vishnupuri, Nanded. Page 75


Canteen Ordering System 2020-2021
setSupportActionBar(toolbar);
database=FirebaseDatabase.getInstance();
categories=database.getReference("Restaurants").child("02")

Gramin Polytechnic Vishnupuri, Nanded. Page 76


Canteen Ordering System 2020-2021

.child("detail").child("Category");
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
} });
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawer,toolbar,0,0);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView =navigationView.getHeaderView(0);
txtFullName=(TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText("Admin");
recycler_menu=(RecyclerView)findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
updateToken(FirebaseInstanceId.getInstance().getToken());

}
private void updateToken(String token)
{ FirebaseDatabase
db=FirebaseDatabase.getInstance(); DatabaseReference
tokens=db.getReference("Tokens"); Token data=new
Token(token,true);
tokens.child("1234567891").setValue(data);
}
private void showDialog()
AlertDialog.Builder alertDialog=new AlertDialog.Builder(Home.this);
alertDialog.setTitle("Add new Category");
alertDialog.setMessage("Please fill full information");
LayoutInflater inflater=this.getLayoutInflater();
View
add_menu_layout=inflater.inflate(R.layout.add_new_menu_layout,null);
edtName=add_menu_layout.findViewById(R.id.edtName);
btnSelect=add_menu_layout.findViewById(R.id.btnSelect);
btnUpload=add_menu_layout.findViewById(R.id.btnUpload);
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
Gramin Polytechnic Vishnupuri, Nanded. Page 77
Canteen Ordering System 2020-2021
} });

Gramin Polytechnic Vishnupuri, Nanded. Page 78


Canteen Ordering System 2020-2021

btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadImage();
} });
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (newCategory!=null){
categories.push().setValue(newCategory);
Snackbar.make(drawer,"New Category"+newCategory.getName()+" was
added",Snackbar.LENGTH_SHORT).show();
} } });
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
} });
alertDialog.show();
}
private void uploadImage()
{ if (saveUri!=null){
final ProgressDialog mDialog=new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(Home.this,"Uploaded !!!",Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
newCategory=new Category(edtName.getText().toString(),uri.toString());

} }); }
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {

Gramin Polytechnic Vishnupuri, Nanded. Page 79


Canteen Ordering System 2020-2021

mDialog.dismiss();
Toast.makeText(Home.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 *
taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
mDialog.setMessage("Uploaded "+progress+"%");
} }); } }
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
if (requestCode==Common.PICK_IMAGE_REQUEST &&
resultCode==RESULT_OK && data!=null && data.getData()!=null){
saveUri=data.getData();
btnSelect.setText("Image
Selected!");
} }
private void chooseImage()
{ Intent intent=new
Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select
Picture"),Common.PICK_IMAGE_REQUEST);
}
private void loadMenu()
{ FirebaseRecyclerOptions<Category> options = new
FirebaseRecyclerOptions.Builder<Category>()
.setQuery(categories,Category.class)
.build();
adapter= new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull MenuViewHolder viewHolder, int
position, @NonNull Category model) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.imageView);
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick)
{ Intent foodList=new Intent(Home.this,FoodList.class);
foodList.putExtra("CategoryId",adapter.getRef(position).getKey());
startActivity(foodList);
} }); }
@NonNull
@Override
Gramin Polytechnic Vishnupuri, Nanded. Page 80
Canteen Ordering System 2020-2021

public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int


viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item,parent,false);
return new MenuViewHolder(itemView);
} };
adapter.startListening();
adapter.notifyDataSetChanged();
recycler_menu.setAdapter(adapter);
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
@Override
protected void onResume() {
super.onResume();
adapter.startListening();
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public void onBackPressed(){
DrawerLayout
drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);

}else{
super.onBackPressed();
} }
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.home,
menu);
return true;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
{ int id = item.getItemId();
if(id==R.id.nav_menu){
Intent orderIntent=new Intent(Home.this, Home.class);
startActivity(orderIntent);
}else if(id==R.id.nav_user_list){
Intent shipper=new Intent(Home.this, UserDetails.class);
startActivity(shipper);
Gramin Polytechnic Vishnupuri, Nanded. Page 81
Canteen Ordering System 2020-2021
}else if(id==R.id.nav_orders){

Gramin Polytechnic Vishnupuri, Nanded. Page 82


Canteen Ordering System 2020-2021

Intent shipper=new Intent(Home.this, OrderStatus.class);


startActivity(shipper);
}else if(id==R.id.nav_sign_out){
Intent signIntent=new Intent(Home.this, signin.class);
signIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(signIntent);
finish();
}else if(id==R.id.nav_delivery_charge){
Intent shipper=new Intent(Home.this, UpdateActivity.class);
startActivity(shipper);
}
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.UPDATE)){
howUpdateDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}else if(item.getTitle().equals(Common.DELETE)){
deleteCategory(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteCategory(String key) {
DatabaseReference foods = database.getReference("Foods");
Query foodInCategory =foods.orderByChild("menuId").equalTo(key);
foodInCategory.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ for (DataSnapshot postSnapShot:dataSnapshot.getChildren()){
postSnapShot.getRef().removeValue();
} }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} });
categories.child(key).removeValue();
Toast.makeText(this,"Item Deleted!!!",Toast.LENGTH_SHORT).show();
}
private void showUpdateDialog(final String key, final Category item)
{ AlertDialog.Builder alertDialog=new
AlertDialog.Builder(Home.this); alertDialog.setTitle("Update
Category"); alertDialog.setMessage("Please fill full information");
LayoutInflater inflater=this.getLayoutInflater();
View add_menu_layout=inflater.inflate(R.layout.add_new_menu_layout,null);

Gramin Polytechnic Vishnupuri, Nanded. Page 83


Canteen Ordering System 2020-2021

edtName=add_menu_layout.findViewById(R.id.edtName);
btnSelect=add_menu_layout.findViewById(R.id.btnSelect);
btnUpload=add_menu_layout.findViewById(R.id.btnUpload);
edtName.setText(item.getName());
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
} });
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeImage(item);
} });
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
item.setName(edtName.getText().toString());
categories.child(key).setValue(item);
} });
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
} });
alertDialog.show();
}
private void changeImage(final Category item)
{ if (saveUri!=null){
final ProgressDialog mDialog=new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(Home.this,"Uploaded !!!",Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
@Override

Gramin Polytechnic Vishnupuri, Nanded. Page 84


Canteen Ordering System 2020-2021

public void onSuccess(Uri uri) {


item.setImage(uri.toString());
} }); }
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(Home.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 *
taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
mDialog.setMessage("Uploaded "+progress+"%");
} }); } }
}

Category List(Home Activity) Add Category (Home Activity)

Gramin Polytechnic Vishnupuri, Nanded. Page 85


Canteen Ordering System 2020-2021

5.3.2 Product/Food List Activity


public class FoodList extends AppCompatActivity
{ RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FloatingActionButton fab;
FirebaseDatabase db;
DatabaseReference foodList;
FirebaseStorage storage;
StorageReference
storageReference; String
categoryId="";
FirebaseRecyclerAdapter<Food, FoodViewHolder> adapter;
EditText edtName,edtDescription,edtPrice,edtDiscount;
Button btnSelect,btnUpload;
Food newFood;
Uri saveUri;
RelativeLayout rootLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
db=FirebaseDatabase.getInstance();
foodList=db.getReference("Restaurants").child(Common.currentUser.getRestaurantId())
.child("detail").child("Foods");
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
recyclerView=(RecyclerView)findViewById(R.id.recycler_food);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
rootLayout=(RelativeLayout)findViewById(R.id.rootLayout);
fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAddFoodDailog();
} });
if(getIntent()!=null)
categoryId= getIntent().getStringExtra("CategoryId"); if(!
categoryId.isEmpty())
loadListFood(categoryId);
}
@Override
protected void onResume() {
super.onResume();
adapter.startListening();
Gramin Polytechnic Vishnupuri, Nanded. Page 86
Canteen Ordering System 2020-2021

}
private void showAddFoodDailog() {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(FoodList.this);
alertDialog.setTitle("Add new Food");
alertDialog.setMessage("Please fill full information");
LayoutInflater inflater=this.getLayoutInflater();
View add_menu_layout=inflater.inflate(R.layout.add_new_food_layout,null);
edtName=add_menu_layout.findViewById(R.id.edtName);
edtDescription=add_menu_layout.findViewById(R.id.edtDescription);
edtPrice=add_menu_layout.findViewById(R.id.edtPrice);
edtDiscount=add_menu_layout.findViewById(R.id.edtDiscount);
btnSelect=add_menu_layout.findViewById(R.id.btnSelect);
btnUpload=add_menu_layout.findViewById(R.id.btnUpload);
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
} });
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadImage();
} });
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (newFood!=null){
foodList.push().setValue(newFood);
Snackbar.make(rootLayout,"New Category"+newFood.getName()+" was
added",Snackbar.LENGTH_SHORT).show();
} } });
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
} });
alertDialog.show()
}
private void uploadImage()
{ if (saveUri!=null){
final ProgressDialog mDialog=new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();

Gramin Polytechnic Vishnupuri, Nanded. Page 87


Canteen Ordering System 2020-2021

String imageName= UUID.randomUUID().toString();


final StorageReference imageFolder=storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(FoodList.this,"Uploaded !!!",Toast.LENGTH_SHORT).show()
; imageFolder.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri)
{ newFood=new Food();
newFood.setName(edtName.getText().toString());
newFood.setDescription(edtDescription.getText().toString());
newFood.setPrice(edtPrice.getText().toString());
newFood.setDiscount(edtDiscount.getText().toString());
newFood.setMenuId(categoryId);
newFood.setImage(uri.toString());
} }); }
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FoodList.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 *
taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
mDialog.setMessage("Uploaded "+progress+"%");
} }); } }
private void chooseImage()
{ Intent intent=new
Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),
Common.PICK_IMAGE_REQUEST);
}
private void loadListFood(String categoryId) {
Query listFoodByCategoryId = foodList.orderByChild("menuId").equalTo(categoryId);
FirebaseRecyclerOptions<Food> options = new FirebaseRecyclerOptions.Builder<Food>()
.setQuery(listFoodByCategoryId,Food.class)
.build();
adapter= new FirebaseRecyclerAdapter<Food, FoodViewHolder>(options) {
Gramin Polytechnic Vishnupuri, Nanded. Page 88
Canteen Ordering System 2020-2021

@Override
protected void onBindViewHolder(@NonNull FoodViewHolder viewHolder, int
position, @NonNull Food model) {
viewHolder.food_name.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.food_image);
viewHolder.setItemClickListener(new ItemClickListener() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
} }); }
@NonNull
@Override
public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.food_item,parent,false);
return new FoodViewHolder(itemView);
} };
adapter.startListening();
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{ super.onActivityResult(requestCode, resultCode, data);
if (requestCode==Common.PICK_IMAGE_REQUEST && resultCode==RESULT_OK
&& data!=null && data.getData()!=null){
saveUri=data.getData();
btnSelect.setText("Image
Selected!");
} }
@Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.UPDATE)){
howUpdateoodDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()
));
}else if(item.getTitle().equals(Common.DELETE)){
deleteFood(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteFood(String key) {
foodList.child(key).removeValue();
Gramin Polytechnic Vishnupuri, Nanded. Page 89
Canteen Ordering System 2020-2021

Snackbar.make(rootLayout," Food was deleted",Snackbar.LENGTH_SHORT).show();


}
private void showUpdateFoodDialog(final String key, final Food item)
{ AlertDialog.Builder alertDialog=new
AlertDialog.Builder(FoodList.this); alertDialog.setTitle("Edit Food");
alertDialog.setMessage("Please fill full information");
LayoutInflater inflater=this.getLayoutInflater();
View
add_menu_layout=inflater.inflate(R.layout.add_new_food_layout,null);
edtName=add_menu_layout.findViewById(R.id.edtName);
edtDescription=add_menu_layout.findViewById(R.id.edtDescription);
edtPrice=add_menu_layout.findViewById(R.id.edtPrice);
edtDiscount=add_menu_layout.findViewById(R.id.edtDiscount);
edtName.setText(item.getName());
edtDiscount.setText(item.getDiscount());
edtPrice.setText(item.getPrice());
edtDescription.setText(item.getDescription());

btnSelect=add_menu_layout.findViewById(R.id.btnSelect);
btnUpload=add_menu_layout.findViewById(R.id.btnUpload);
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
} });
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeImage(item);
} });
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
item.setName(edtName.getText().toString());
item.setPrice(edtPrice.getText().toString());
item.setDiscount(edtDiscount.getText().toString());
item.setDescription(edtDescription.getText().toString());
foodList.child(key).setValue(item);
Snackbar.make(rootLayout," Food "+item.getName()+" was
Edited",Snackbar.LENGTH_SHORT).show();
} });
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Gramin Polytechnic Vishnupuri, Nanded. Page 90
Canteen Ordering System 2020-2021

dialogInterface.dismiss();
} });
alertDialog.show();
}
private void changeImage(final Food item)
{ if (saveUri!=null){
final ProgressDialog mDialog=new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(FoodList.this,"Uploaded !!!",Toast.LENGTH_SHORT).show()
; imageFolder.getDownloadUrl().addOnSuccessListener(new
OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
item.setImage(uri.toString());
}

});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mDialog.dismiss();
Toast.makeText(FoodList.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot)
{ double progress=(100.0 *
taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
mDialog.setMessage("Uploaded "+progress+"%");
}
});
} }
}

Gramin Polytechnic Vishnupuri, Nanded. Page 91


Canteen Ordering System 2020-2021

Category Wise Product List Add New Product List Category

5.3.3 OrderList Activity


public class OrderStatus extends AppCompatActivity
{ RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
FirebaseDatabase db;
DatabaseReference requests;
MaterialSpinner
spinner,shipperSpiner; @Override

Gramin Polytechnic Vishnupuri, Nanded. Page 92


Canteen Ordering System 2020-2021

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
db=FirebaseDatabase.getInstance();
requests=db.getReference("Restaurants").child(Common.currentUser.getRestaurantId())
.child("detail").child("Requests");
recyclerView=(RecyclerView)findViewById(R.id.listOrders);
recyclerView.setHasFixedSize(true);
layoutManager= new LinearLayoutManager(this);
((LinearLayoutManager)
layoutManager).setReverseLayout(true);
((LinearLayoutManager) layoutManager).setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
loadOrder();
}
private void loadOrder()
{ FirebaseRecyclerOptions<Request> options = new
FirebaseRecyclerOptions.Builder<Request>()
.setQuery(requests,Request.class)
.build();
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull OrderViewHolder viewHolder, int
position, @NonNull Request model) {
viewHolder.txtOrderId.setText(adapter.getRef(position).getKey());
wHolder.txtOrderStatus.setText(Common.convertCodeToStatus(model.getStatus()));
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderPhone.setText(model.getPhone());
viewHolder.txtOrderDate.setText(Common.getDate(Long.parseLong(adapter.getRef(position).g
etKey())));
viewHolder.order_name.setText(model.getName());
viewHolder.btnEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showUpdateDialog(adapter.getRef(position).getKey(),
adapter.getItem(position));
} });
viewHolder.btnRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteOrder(adapter.getRef(position).getKey());
} });
viewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent orderDetail = new Intent(OrderStatus.this, OrderDetail.class);
Common.currentRequest = model;
Gramin Polytechnic Vishnupuri, Nanded. Page 93
Canteen Ordering System 2020-2021

orderDetail.putExtra("Order ID", adapter.getRef(position).getKey());


startActivity(orderDetail);
}
}); }
@NonNull
@Override
public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.order_layout, parent, false);
return new OrderViewHolder(itemView);
}
};
adapter.startListening();
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();

@Override
protected void onResume() {
super.onResume();
adapter.startListening();
}
@Override
public boolean onContextItemSelected(MenuItem item)
{ if (item.getTitle().equals(Common.UPDATE))
wUpdateDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
else if (item.getTitle().equals(Common.DELETE))
deleteOrder(adapter.getRef(item.getOrder()).getKey());
return super.onContextItemSelected(item);
}
private void deleteOrder(String key)
{ requests.child(key).removeValue(
); adapter.notifyDataSetChanged();
}
private void showUpdateDialog(String key, final Request item) {
final AlertDialog.Builder alertDialog=new AlertDialog.Builder(OrderStatus.this);
alertDialog.setTitle("Update Order");
alertDialog.setMessage("Please choose status");
LayoutInflater inflater=this.getLayoutInflater();
final View view=inflater.inflate(R.layout.update_order_layout,null);
spinner=(MaterialSpinner)view.findViewById(R.id.statusSpinner);

Gramin Polytechnic Vishnupuri, Nanded. Page 94


Canteen Ordering System 2020-2021

spinner.setItems("Placed","On my way","Delivered");
shipperSpiner=(MaterialSpinner)view.findViewById(R.id.shipperSpinner);
List<String> shipperList= new ArrayList<>();
FirebaseDatabase.getInstance().getReference(Common.SHIPPERS_TABLE).addListenerForSin
gleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ for (DataSnapshot shipperSnapShot:dataSnapshot.getChildren())
shipperList.add(shipperSnapShot.getKey());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
alertDialog.setView(view);
final String localKey=key;
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
item.setStatus(String.valueOf(spinner.getSelectedIndex()))
if (item.getStatus().equals("2"))
{
FirebaseDatabase.getInstance().getReference(Common.ORDER_NEED_SHIP_TABLE)
.child(shipperSpiner.getItems().get(shipperSpiner.getSelectedIndex()).toString())
.child(localKey)
.setValue(item);
requests.child(localKey).setValue(item);
adapter.notifyDataSetChanged()
sendOrderShipRequestToShipper(localKey,item);
}else{
requests.child(localKey).setValue(item);
adapter.notifyDataSetChanged();
}
requests.child(localKey).setValue(item);
adapter.notifyDataSetChanged();
sendOrderStatusToUser(localKey,item);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();

Gramin Polytechnic Vishnupuri, Nanded. Page 95


Canteen Ordering System 2020-2021

}
private void sendOrderStatusToUser(final String key,Request item)
{ DatabaseReference tokens=db.getReference("Tokens");
tokens.orderByKey().equalTo(item.getPhone())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ for (DataSnapshot postSnapShot:dataSnapshot.getChildren()){
Token serverToken=postSnapShot.getValue(Token.class);
Map<String,String> dataSend=new HashMap<>();
dataSend.put("title","EasySale");
dataSend.put("message","Your Order : "+key+" was
updated"); DataMessage dataMessage=new
DataMessage(serverToken.getToken(),dataSend);
String test=new Gson().toJson(dataMessage);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void sendOrderShipRequestToShipper(String shipperPhone, Request item) {
DatabaseReference tokens=db.getReference("Tokens");
tokens.child(shipperPhone)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ for (DataSnapshot postSnapShot:dataSnapshot.getChildren()){
Token
serverToken=postSnapShot.getValue(Token.class);
Map<String,String> dataSend=new HashMap<>();
dataSend.put("title","EasySale");
dataSend.put("message","Your have new order");
DataMessage dataMessage=new
DataMessage(serverToken.getToken(),dataSend);
String test=new Gson().toJson(dataMessage);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}

Gramin Polytechnic Vishnupuri, Nanded. Page 96


Canteen Ordering System 2020-2021

User Order List

5.3.4 User Details Activity( User List)


public class UserDetails extends AppCompatActivity
{ RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase db;
DatabaseReference userdetails;

Gramin Polytechnic Vishnupuri, Nanded. Page 97


Canteen Ordering System 2020-2021

FirebaseRecyclerAdapter<UserCustomer, UserViewHolder> adapter


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
db = FirebaseDatabase.getInstance();
userdetails = db.getReference("User");
recyclerView=(RecyclerView)findViewById(R.id.recycler_userdetails);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
userD();
}
private void userD()
{ FirebaseRecyclerOptions<UserCustomer> options = new
FirebaseRecyclerOptions.Builder<UserCustomer>()
.setQuery(FirebaseDatabase.getInstance()
.getReference()
.child("User"), UserCustomer.class)
.build();
adapter = new FirebaseRecyclerAdapter<UserCustomer, UserViewHolder>(options) {
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.user_layout, parent, false);
return new UserViewHolder(itemView);
}
@Override
protected void onBindViewHolder(@NonNull UserViewHolder viewHolder, int position,
@NonNull UserCustomer model) {
viewHolder.txtUserName.setText(model.getName());
viewHolder.txtUserPhone.setText(adapter.getRef(position).getKey());
viewHolder.txtUserAddress.setText(model.getAddress());
viewHolder.btnCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+adapter.getRef(position).getKey()));
startActivity(intent);
} }); } };
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}

Gramin Polytechnic Vishnupuri, Nanded. Page 98


Canteen Ordering System 2020-2021

Register User List With Information

Gramin Polytechnic Vishnupuri, Nanded. Page 99


Canteen Ordering System 2020-2021

5.3.4 Delivery Charge Update Activity


public class UpdateActivity extends AppCompatActivity
{ FirebaseDatabase database;
DatabaseReference delivery;

EditText
edtDeliverCharge; Button
btnUpdate; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
database=FirebaseDatabase.getInstance();
delivery=database.getReference("Delivery");
edtDeliverCharge=findViewById(R.id.edtDeliverCharge);
btnUpdate=findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (edtDeliverCharge.getText().toString().trim().length() == 0)
{ edtDeliverCharge.setError("Enter Delivery Charge");
}else{
if (Common.isConnectedToInternet(getBaseContext())) {
final ProgressDialog mDialog = new
ProgressDialog(UpdateActivity.this); mDialog.setMessage("Please
Waiting....................................................");
mDialog.show();
delivery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{ Delivery user = new
Delivery(edtDeliverCharge.getText().toString());
delivery.setValue(user);
Toast.makeText(UpdateActivity.this, "Update Successfully",
Toast.LENGTH_SHORT).show();
mDialog.dismiss();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
} });
} else {
Toast.makeText(UpdateActivity.this, "please check your connection !!",
Toast.LENGTH_SHORT).show();
return;
} } }
});
}}
Gramin Polytechnic Vishnupuri, Nanded. Page
100
Canteen Ordering System 2020-2021

Update Delivery Charge

Gramin Polytechnic Vishnupuri, Nanded. Page


101
Canteen Ordering System 2020-2021

CHAPTER 6
TESTING & DEBUGGING STRATEGIES & TEST CASES
6.1 TESTING

Testing is the process of detecting errors. Testing performs a very critical role for quality
assurance and for ensuring the reliability of software. The results of testing are used later on during
maintenance also.

6.1.1 Psychology of Testing

The aim of testing is often to demonstrate that a program works by showing that it has no
errors. The basic purpose of testing phase is to detect the errors that may be present in the
program. Hence one should not start testing with the intent of showing that a program works, but
the intent should be to show that a program doesn’t work. Testing is the process of executing a
program with the intent of finding errors.

6.2 TESTING OBJECTIVES

The main objective of testing is to uncover a host of errors, systematically and with
minimum effort and time. Stating formally, we can say:

 Testing is a process of executing a program with the intent of finding an error.


 A successful test is one that uncovers an as yet undiscovered error.
 A good test case is one that has a high probability of finding error, if it exists.
 The tests are inadequate to detect possibly present errors.
 The software more or less confirms to the quality and reliable standards.

6.3LEVELS OF TESTING

In order to uncover the errors present in different phases we have the concept of levels testing.
The basic levels of testing are as shown below…

 System Testing

Gramin Polytechnic Vishnupuri, Nanded. Page


102
Canteen Ordering System 2020-2021

The philosophy behind testing is to find errors. Test cases are devised with this in mind.
A strategy employed for system testing is code testing.

 Code Testing:

This strategy examines the logic of the program. To follow this method we developed
some test data that resulted in executing every instruction in the program and module i.e. every
path is tested. Systems are not designed as entire nor are they tested as single systems. To ensure
that the coding is perfect two types of testing is performed or for that matter is performed or that
matter is performed or for that matter is performed on all systems.

6.4 TYPES OF TESTING

 Unit Testing
 Link Testing

6.4.1 Unit Testing

Unit testing focuses verification effort on the smallest unit of software i.e. the module.
Using the detailed design and the process specifications testing is done to uncover errors within
the boundary of the module. All modules must be successful in the unit test before the start of the
integration testing begins.

In this project each service can be thought of a module. There are so many modules like
Login, HWAdmin, MasterAdmin, Normal User, and PManager. Giving different sets of inputs
has tested each module. When developing the module as well as finishing the development so
that each module works without any error. The inputs are validated when accepting from the
user.

In this application developer tests the programs up as system. Software units in a system
are the modules and routines that are assembled and integrated to form a specific function. Unit
testing is first done on modules, independent of one another to locate errors. This enables to
detect errors. Through this errors resulting from interaction between modules initially avoided.

Gramin Polytechnic Vishnupuri, Nanded. Page


103
Canteen Ordering System 2020-2021

6.4.2 Link Testing


Link testing does not test software but rather the integration of each module in system.
The primary concern is the compatibility of each module. The Programmer tests where modules
are designed with different parameters, length, type etc.

6.4.3 Integration Testing


After the unit testing we have to perform integration testing. The goal here is to see if
modules can be integrated properly, the emphasis being on testing interfaces between modules.
This testing activity can be considered as testing the design and hence the emphasis on testing
module interactions.

In this project integrating all the modules forms the main system. When integrating all
the modules I have checked whether the integration effects working of any of the services by
giving different combinations of inputs with which the two services run perfectly before
Integration.

6.4.4 System Testing

Here the entire software system is tested. The reference document for this process is the
requirements document, and the goal os to see if software meets its requirements.

Here entire ‘ATM’ has been tested against requirements of project and it is checked
whether all requirements of project have been satisfied or not.

6.4.5 Acceptance Testing


Acceptance Test is performed with realistic data of the client to demonstrate that the
software is working satisfactorily. Testing here is focused on external behavior of the system; the
internal logic of program is not emphasized.

In this project ‘Network Management Of Database System’ I have collected some data
and tested whether project is working correctly or not.

Test cases should be selected so that the largest number of attributes of an equivalence
class is exercised at once. The testing phase is an important part of software development. It is
the process of finding errors and missing operations and also a complete verification to
determine whether the objectives are met and the user requirements are satisfied.

Gramin Polytechnic Vishnupuri, Nanded. Page


104
Canteen Ordering System 2020-2021

6.5 WHITE BOX TESTING

This is a unit testing method where a unit will be taken at a time and tested thoroughly at
a statement level to find the maximum possible errors. I tested step wise every piece of code,
taking care that every statement in the code is executed at least once. The white box testing is
also called Glass Box Testing.

I have generated a list of test cases, sample data. which is used to check all possible
combinations of execution paths through the code at every module level.

6.6 BLACK BOX TESTING

This testing method considers a module as a single unit and checks the unit at interface
and communication with other modules rather getting into details at statement level. Here the
module will be treated as a block box that will take some input and generate output. Output for a
given set of input combinations are forwarded to other modules.

6.7 TEST CASES

6.7.1 Test cases for Payroll System

Sr Test Test case Steps Excepted Actual Status


No. case objective result result
ID
01. TC_1 Check the 1. Fill Toast msg Toast msg is Pass
registration registration should generated
form is form and generate with with new
properly work submit. new popup popup
or not window. window.
02. TC_2 Check the login 1. Fill id & Show home Show home Pass
is properly password. activity page. activity page
work or not
2. click on
login.
03. TC_3 Check 1. Enter Id & Open Directly Open Directly Pass
remember me Paassword Home Home
check box then login. Activity. Activity.
works or not.

Gramin Polytechnic Vishnupuri, Nanded. Page


105
Canteen Ordering System 2020-2021

2. Click on
Check box.

3. Reopen
Application.
04. TC_4 Check Forget 1.Click on Show Forget Show Forget Pass
Password Forget Password Password
Button work or Password Popup Popup
not. Button. Layout. Layout.
05. TC_5 Check already 1.Enter this Show Toast Show Toast Pass
register User number massege User massege User
Detect or not. which is Already Already
already Register. Register.
register.
06. TC_6 Check Contact 1.Click on Show Contect Show Contect Pass
Information Contact Us Type Image Type Image
work properly Tab item. and Button. and Button.
or not.
07. TC_7 Check call 1.Click on Call to Call to Pass
button work call button. Customer Customer
properly or not. Support. Support.
08. TC_8 Check 1.Click on Show Show Pass
Whatsapp whatsapp tab. whatsapp of whatsapp of
button work customer care. customer care.
properly or not.
09. TC_9 Check SMS 1.Click on Show SMS of Show SMS of Pass
button work SMS tab. customer care. customer care.
properly or not.
10. TC_10 Check Gmail 1.Click on Show Gmail Show Gmail Pass
button work Gmail tab. of customer of customer
properly or not. care. care.
11. TC_11 Check logout 1.Click on Go to login Go to login Pass
tab work Logout tab. activiy activiy
properly or not.
12. TC_12 Check 1.Click on Directly exit Directly exit Pass
backpressed backpressed from from
work properly button. application. application.
or not.
13. TC_13 Check 1.Click on Show Show Pass
Dashboard navigation Dashboard. Dashboard.
Work Properly mark.
or not..
14. TC_14 Check Change 1.Enter all Show toast Show toast Pass
password work password and msg chage msg chage
or not. fill this form. password password
successfully. successfully.

Gramin Polytechnic Vishnupuri, Nanded. Page


106
Canteen Ordering System 2020-2021

15 TC_15 Check Category 1.Click on Display all Display all Pass


item view work any one product list product list
or not category related to related to
item. category. category.
16. TC_16 Check Product 1. Click on Show Product Show Product Pass
item view work any one Details. Details.
or not Product
item.
17. TC_17 Check Number 1. Click on Increase and Increase and Pass
Button work or plus. decrese decrese
not. properly. properly.
2. Click on
Minus.
18. TC_18 Check Add 1. Click on Show product Show product Pass
Button work or Add in cart list. in cart list.
not. Button.

2. Click On
Cart tab.
19. TC_19 Check Place 1. Clear Cart Show toast Show toast Pass
Order Empty list. “Your Cart is “Your Cart is
Condition work empty”. empty”.
or not. 2. Click on
place order.
20. TC_20 Check Buy 1. Goto Calculate Calculate Pass
Activity Work buy Amount Amount
or not. activity. Properly and Properly and
place order place order
2. Check Successfully. Successfully.
Calculation of
price.

3. Click on
buy Button.
21. TC_21 Check Admin 1. Enter id & Open Home Open Home Pass
Login work or Password Activity. Activity.
not properly. then Login.

22. TC_22 Check Add 1. Click on Show toast Show toast Pass
Product. add button.. add product add product
successfully. successfully.
23 TC_23 Check Update 1. Enter Show Toast Show Toast Pass
Delivery charge of message message
Charge work or delivery. update update
not. successfully. successfully.

Gramin Polytechnic Vishnupuri, Nanded. Page


107
Canteen Ordering System 2020-2021

CHAPTER 7
ADVANTAGES

 Completely automated online ordering of food in a canteen.


 Order can be placed using personal android phones.
 Improved client service through greater flexibility.
 Cost savings.
 User friendly.
 Faster delivery of products.
 You can able to login any device.
 Less paper waste.
 Opportunities to manage your business from anywhere in the world.

Gramin Polytechnic Vishnupuri, Nanded. Page


108
Canteen Ordering System 2020-2021

CHAPTER 8

CONCLUSIONS & RECOMMENDATIONS

9.1 CONCLUSION

The internet has opened so many opportunities for doing business online, and e-
commerce is one of the most popular ones. Not only does it require low investment, it actually is
a type of business that does not require a full-time commitment, especially if you are selling a
limited number of products.

Online ordering will boost your productivity by eliminating the inefficient process of
taking orders. It will help you to plan and implement an adaptive marketing campaign. Utilising
the latest online ordering technology for your restaurant will also help you to tap into a massive
customer base which is tech-savvy and believes in ‘online way’.

9.2 RECOMMENDATION ON FUTURE IMPROVEMENT


There is always room for improvement, and the software we created can also be
improved. This is especially because we had to create it within a limited time. With more time,
the software network-esssnabled, and eventually web-enabled. This was our original after-
thought to programming the software, and we had chosen XML .

Gramin Polytechnic Vishnupuri, Nanded. Page


109
Canteen Ordering System 2020-2021

CHAPTER 9

REFERENCE
1. Websites:-
1. www.androidtutorials.com
2. www.javatpoint.com
3. www.progchamp.com
4. https://www.emarketinginstitute.org/
5. https://www.restolabs.com/

2. Books:-

1. Hello, Android by Ed Burnette.

2. Java: A beginner’s guide by Herbert Schildt.

3. Thinking in java by Bruce Eckel.

4. Android Programming for Beginners by John Horton.

Gramin Polytechnic Vishnupuri, Nanded. Page


110

You might also like