You are on page 1of 150

A PROJECT REPORT ON

(The Health Detectives)


submitted in partial fulfillment of the requirement for the award of the degree of
MASTER OF COMPUTER APPLICATION
Mini Project- KCA 353

DEPARTMENT OF MASTER OF COMPUTER APPLICATION


HI-TECH INSTITUTE OF ENGINEERING & TECHNOLOGY,
GHAZIABAD
(Affiliated to AKTU Lucknow)

SUBMITTED BY SUBMITTED TO
Rahul Saini Mrs. Aruna Kumari (Asst. Professor)
2202200140064

i
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to Mrs. Aruna Kumari Asst. Professor
of the Department of MCA, for her invaluable guidance and support throughout
this project. Her expertise and insights were instrumental in shaping this app.

I am also thankful to Dr. Pankaj Mishra, Director of the MCA program, for his
encouragement and support. His vision and encouragement motivated me to strive
for excellence.

Despite working alone, I was able to complete this project thanks to the
unwavering support of my professors. Their belief in me gave me the strength to
overcome challenges and achieve my goals.

Rahul Saini
MCA Department
Roll Number: 2202200140064
Date:

ii
CERTIFICATE OF ORIGINALITY

I hereby declare that the work which is being presented in this project work entitled The

Health Detectives in partial fulfillment of the requirements for the award of the degree of

Master of Computer Applications at Hi-Tech Institute of Engineering &

Technology, Ghaziabad is an authentic record of my own work carried out during the

period 2023 to 2024 under the supervision and guidance of Asst. Prof. Aruna Kumari.

I have not submitted the matter embodied in this project work anywhere for the

award of any degree or diploma.

Place:

Date: Signature of the candidate.

iii
GUIDE/INDUSTRY /COMPANY CERTIFICATE

Certificate

This is to certify that the Project entitled The Health Detectives is a bonafide

record of independent work done by Rahul Saini (Roll. No.: 2202200140064)

under my supervision during MCA , in partial fulfillment of the requirements for the

award of the degree of Master of Computer Applications at Hi-Tech Institute of

Engineering & Technology, Ghaziabad.(Affiliated to UPTU Lucknow (U.P))

in session 2023-24 and that the Project has not previously formed the basis for

the award of any other degree, Diploma, Associate ship, Fellowship or other title.

Signature of the Project Manager/Supervisor


(With Seal)

iv
Table Of Content

Front Page ………………………………………………………………….. i

Acknowledgement ………………………………………………………….. ii

Certificate Of Originality ………………………………………………….. iii

Guide Certificate …………………………………………………………… iv

Table Of Content ……………………………………………………………. v

1. Introduction ………………………………………………………………. 1

2. System Analysis …………………………………………………………... 6

3. Feasibility Study ………………………………………………………….. 9

4. S/W & H/W Requirement Specification ………………………………… 13

5. System Design …………………………………………………………….. 18

6. Snapshots And Working Of Modules …………………………………… 23

7. Database ………………………………………………………………….. 68

8. Coding……………………………………………………………………... 73

9. Testing …………………………………………………………………….. 137

10. Maintenance …………………………………………………………….. 140

11. System Security Measures ……………………………………………… 142

12. Future Scope Of The Project ……………………………………………144

v
Chapter1
INTRODUCTION
The Health Detective App is a comprehensive mobile application designed to
empower users with tools and information to take control of their health and well-
being. In today's fast-paced world, where health concerns are paramount, having
easy access to reliable health information and services is crucial. This app aims to
bridge the gap between users and their healthcare needs by offering a range of
features tailored to facilitate disease prediction, detection, and management.

With a user-friendly interface, the Health Detective App provides a centralized


platform where users can seamlessly navigate through various functionalities.
From predicting diseases based on symptoms to providing detailed information
about specific illnesses, the app serves as a reliable companion for users seeking
valuable insights into their health conditions.

Key features of the Health Detective App include:

1. Disease Prediction based on Symptoms and MRI Images


2. Disease Information
3. Fix Doctor Appointment
4. Check Appointment Status
5. BMI Calculator
6. Upload Patients Data

With the Health Detective App, users can embark on a journey towards improved

1
health outcomes, equipped with valuable insights, convenient tools, and access to
professional healthcare services at their fingertips. Whether it's staying informed
about common ailments, tracking personal health metrics, or seeking expert
medical advice, this app is dedicated to empowering individuals to make informed
decisions and lead healthier lives.

Problem Statement

In the realm of healthcare, readily available, accurate information is often the first
line of defense against preventable health concerns and missed diagnoses. Yet,
navigating the complexities of medical jargon and finding reliable sources can be
daunting, particularly for individuals with limited medical background or specific
health anxieties. This often leads to delayed diagnoses, ineffective treatments, and
unnecessary stress, impacting both personal well-being and healthcare costs.

Enter Health Detective, an Android app designed to bridge the gap between
accessible knowledge and empowered health management. Recognizing the
challenges individuals face in deciphering symptoms, understanding disease
complexities, and accessing qualified healthcare professionals, Health Detective
aims to become a one-stop shop for proactive health engagement.

Through its innovative features, Health Detective empowers users to take control
of their health journey:

• Predictive Insights: By analyzing reported symptoms, the app offers valuable


preliminary insights into potential health concerns, prompting users to seek

2
professional advice when necessary. While not intended for diagnosis, this feature
serves as a crucial first step in navigating potential health issues.

• Disease Exploration: Demystifying complex medical terminology, the app


provides comprehensive and easy-to-understand information on various diseases
and conditions. Users can delve deeper into specific concerns, gaining valuable
knowledge and making informed decisions about their health.
• Doctor Connect: Bridging the gap between patients and qualified healthcare
professionals, Health Detective allows users to locate doctors in their area based on
specific needs and preferences. The seamless appointment scheduling feature
empowers users to access timely and appropriate care, eliminating unnecessary
hurdles and delays.

• Personalized Health Data: Recognizing the importance of individual health


history and ongoing monitoring, the app offers secure storage for personal health
data, including vital signs, medical history, and medication information. This
empowers users to track their progress, identify trends, and make informed
decisions about their well-being.

• BMI Calculator: Providing a quick and convenient tool for assessing body mass
index (BMI), the app helps users understand their weight status and make informed
lifestyle choices.

3
By addressing the core problem of limited health information accessibility and user
empowerment, Health Detective goes beyond being just an app. It aspires to be a
personalized health companion, guiding individuals towards proactive health
management, informed decision-making, and seamless access to qualified
professionals. By bridging this critical gap, Health Detective empowers users to
embark on a journey towards a healthier, happier, and more informed version of
themselves.

OBJECTIVE

The primary objective of the Health Detective App is to empower users withtools
and resources to take control of their health and well-being.
Key objectives of the project include:

1. Disease Prediction and Detection: Implement advanced deep learning


algorithms to predict potential diseases based on user-entered symptoms and
analyze MRI images for accurate disease detection and diagnosis.

2. Access to Reliable Health Information: Provide users with comprehensive


information about various diseases, including symptoms, causes, risk factors, and
treatment options, sourced from reputable medical sources.

3. Facilitate Healthcare Access: Streamline the process of accessing healthcare


services by recommending specialized doctors based on predicted diseases or

4
abnormalities and enabling users to schedule appointments directly through the
app.

4. Promote Proactive Health Management: Empower users to monitor their


health status through features such as a BMI calculator and secure health data
management, fostering proactive disease prevention and early intervention.

5. Enhance User Experience: Develop a user-friendly interface and intuitive


navigation system to ensure a seamless user experience, catering to users of all
levels of technical proficiency and healthcare knowledge.

6. Health Education and Awareness Campaigns: Launch health education and


awareness campaigns within the app to educate users about preventive healthcare
measures, disease management strategies, and healthy lifestyle choices through
interactive quizzes, articles, and videos.

7. Personalized Health Recommendations: Utilize machine learning algorithms


to analyze user data and provide personalized health recommendations.

By achieving these objectives, the Health Detective App aims to redefine the
traditional healthcare paradigm, empowering individuals to make informed
decisions about their health and leading to improved health outcomes and
enhanced quality of life for all users.

5
Chapter 2
System Analysis

The system analysis phase of the Health Detective App project involved
studying and analyzing the requirements and functionalities of the proposed
system. This phase aimed to identify user needs, define system requirements,
and establish the foundation for system design and development.

• Identification of Need:
The identification of the need for the Health Detective App stemmed from the
recognition of several challenges and gaps in the existing healthcare system:

1. Limited Accessibility: Many individuals face barriers to accessing timely


healthcare services, including long wait times, geographical constraints, and
limited availability of healthcare professionals.

2. Lack of Disease Awareness: There is a lack of awareness and knowledge


among the general population regarding various diseases, their symptoms, risk
factors, and preventive measures.

3. Inefficient Healthcare Delivery: The traditional healthcare delivery model


often relies on reactive rather than proactive approaches to health management
, leading to delays in disease detection and treatment.

4. Data Fragmentation: Personal health data is often fragmented across

6
multiple sources, making it difficult for individuals to track and manage their
health effectively.

5. Need for Technological Solutions: With the proliferation of mobile


technology and advancements in artificial intelligence, there is an opportunity
to leverage these technologies to address the aforementioned challenges and
improve healthcare delivery and access.

• Preliminary Investigation:
The preliminary investigation phase involved conducting research and
gathering information to assess the feasibility and viability of developing the
Health Detective App. Key activities and findings during this phase include:

1. Market Research: Analyzing the market landscape for healthcare apps,


identifying existing solutions, and evaluating their features, strengths, and
weaknesses.

2. User Needs Analysis: Conducting surveys, interviews, and focus groups


with potential users to understand their healthcare needs, preferences, and pain
points.

3. Technical Feasibility: Assessing the technical feasibility of implementing


deep learning algorithms for disease prediction and MRI image analysis,
considering factors such as available resources, expertise, and infrastructure.

7
4. Regulatory Compliance: Investigating regulatory requirements and
compliance standards related to healthcare apps, including data privacy
regulations such as HIPAA (Health Insurance Portability and Accountability
Act) and GDPR (General Data Protection Regulation).

5. Business Model Evaluation: Exploring potential revenue models for the


app, including freemium, subscription-based, or ad-supported models, and
assessing the market potential and monetization opportunities.

6. Partnership Opportunities: Identifying potential partners and


collaborators, such as healthcare institutions, medical professionals, and
technology providers, to support the development and deployment of the app.

By conducting a thorough preliminary investigation, the project team gained


valuable insights into the market landscape, user needs, technical feasibility,
regulatory requirements, and business opportunities, laying the groundwork for
the subsequent phases of project planning and development.

8
Chapter 3
FEASIBILITY STUDY

A feasibility study is an assessment of the practicality and viability of a


proposed project or system. It helps stakeholders, including project managers,
investors, and decision-makers, determine whether the project is worth
pursuing or if it should be abandoned or modified. Feasibility studies are
typically conducted at the early stages of a project to evaluate various aspects,
including technical, economic, operational, and legal considerations.
1. Technical Feasibility:
Technical feasibility refers to the assessment of whether the proposed project
can be implemented using the available technology and resources.
In the case of the Health Detective App, the following factors contribute to its
technical feasibility:

1. Availability of Technology: The availability of advanced technologies such as


deep learning algorithms, mobile app development frameworks (e.g., Android
Studio) enables the implementation of the desired features, including disease
prediction, MRI image analysis, and user interface development.
2. Expertise and Skills: The project team possesses the necessary technical expertise
and skills in machine learning, mobile app development, and healthcare technology
to implement the required functionalities effectively. Any gaps in expertise can be
addressed through training or hiring additional resources.
3. Hardware and Software Requirements: The hardware and software
requirements for developing and deploying the Health Detective App, including

9
computers, smartphones, and development tools, are readily available and
compatible with the project's needs.
4. Integration Capabilities: The app's architecture allows for seamless integration
with external services and APIs, such as doctor recommendation systems,
appointment scheduling platforms, and healthcare databases, ensuring
interoperability and scalability.

Overall, the technical feasibility assessment indicates that the Health Detective
App can be implemented successfully using the available technology and
resources, with the project team possessing the necessary expertise to execute the
project effectively.

2. Economic Feasibility:

Economic feasibility evaluates whether the proposed project is financially viable


and cost-effective. Considerations for economic feasibility in the context of the
Health Detective App include:

1. Development Costs: The initial development costs for designing, coding, testing,
and deploying the app, including expenses related to hiring developers, purchasing
software licenses, and acquiring datasets for training machine learning models.
2. Operational Costs: The ongoing operational costs associated with maintaining
and supporting the app, including server hosting fees, software updates, customer
support services, and marketing expenses.
3. Revenue Potential: The potential revenue streams for the app, including
subscription fees, in-app purchases, advertising revenue, and partnerships with
healthcare providers or pharmaceutical companies.

10
4. Return on Investment (ROI): The projected ROI for the project, taking into
account the expected revenue generated from the app and the associated costs over
time.

By conducting a thorough economic feasibility analysis, the project team can


determine whether the potential benefits of developing the Health Detective App
outweigh the associated costs and whether the project is financially viable in the
long run.

3. Operational Feasibility:

Operational feasibility assesses whether the proposed project can be implemented


smoothly within the existing operational environment and whether it meets the
needs of its users. Considerations for operational feasibility in the context of the
Health Detective App include:

1. User Acceptance: The willingness of users, including both healthcare


professionals and end-users, to adopt and use the app as part of their daily routines
for managing health and accessing healthcare services.
2. Training and Support: The availability of training and support resources to help
users learn how to use the app effectively, including user guides, tutorials, and
customer support channels.
3. Integration with Existing Systems: The compatibility of the app with existing
healthcare systems, processes, and workflows, ensuring seamless integration and
interoperability with other tools and platforms used by healthcare providers.
4. Scalability and Flexibility: The ability of the app to scale and adapt to changing
user needs, technological advancements, and regulatory requirements over time,
ensuring its long-term viability and relevance in the healthcare landscape.

11
By addressing these operational considerations, the Health Detective App can be
designed and implemented in a manner that maximizes user acceptance, usability,
and operational efficiency, ultimately contributing to its success and impact in
improving healthcare delivery and access.

12
Chapter 4
S/W & H/W Requirement Specification
• Software Requirements:

1. Development Environment: Android Studio IDE for developing Android


applications.
2. Programming Languages: Kotlin for Android app development, XML for
designing user interfaces.
3. Database: Firebase Realtime Database for storing patient data and other
information.
4. Machine Learning Framework: TensorFlow Lite for implementing AI models
for disease prediction and detection.
5. Version Control: Git for version control and collaboration.
6. Testing Frameworks: JUnit for unit testing, Espresso for UI testing.

Android Studio:
Android Studio is the official Integrated Development Environment (IDE) for
Android app development, provided by Google. It is based on the IntelliJ IDEA
IDE and is specifically designed for building Android apps. Android Studio offers
a range of features and tools to streamline the app development process, including:

1. User Interface Designer: Android Studio includes a visual designer for creating
app layouts using XML files. The designer allows developers to drag and drop UI
components onto the screen and preview how the layout will look on different
devices.

13
2. Code Editor: Android Studio provides a powerful code editor with features like
syntax highlighting, code completion, and refactoring tools. It supports multiple
programming languages, including Kotlin, Java, and C++.
3. Build Tools: Android Studio comes with tools for building, testing, and packaging
Android apps. It includes support for Gradle, a build automation tool used for
managing dependencies and building app packages (APKs).
4. Emulator: Android Studio includes an Android Emulator that allows developers
to test their apps on virtual devices. The emulator supports various Android
versions and device configurations, making it easy to test apps across different
devices.
5. Debugging Tools: Android Studio provides tools for debugging Android apps,
including breakpoints, watches, and a debugger console. Developers can use these
tools to identify and fix issues in their code.
6. Performance Profiler: Android Studio includes a performance profiler that allows
developers to monitor the performance of their apps in real-time. The profiler
provides insights into CPU, memory, and network usage, helping developers
optimize their apps for better performance.

Overall, Android Studio is a comprehensive IDE that provides everything


developers need to build high-quality Android apps. It is constantly updated with
new features and improvements to support the latest Android development
practices and technologies.

XML:
XML (Extensible Markup Language) is a markup language that is commonly used
for structuring and storing data. It uses tags to define the structure of data elements
and their relationships. XML is designed to be both human-readable and machine-

14
readable, making it widely used for data interchange between different systems and
applications.

Key features of XML include:

1. Tags: XML uses tags to define elements in a hierarchical structure. Tags are
enclosed in angle brackets (< >) and are used to mark the beginning and end of
elements (<element>...</element>).
2. Attributes: XML elements can have attributes that provide additional information
about the element. Attributes are specified within the opening tag of an element
(<element attribute="value">).
3. Nesting: XML elements can be nested inside other elements to create complex
data structures. This allows for the representation of hierarchical data.
4. Self-closing Tags: XML allows for self-closing tags, which are used for elements
that do not have any content (<element/>).
5. Well-Formedness: XML documents must adhere to certain rules to be considered
well-formed, such as having a single root element, properly nested elements, and
correctly formatted tags.

XML is widely used in web development, data exchange, and configuration


settings. It is often used in conjunction with other technologies, such as XSLT
(XML Stylesheet Language Transformations) for transforming XML data, and
XPath for querying XML documents.

KOTLIN:
Kotlin is a statically typed programming language that runs on the Java Virtual
Machine (JVM) and can also be compiled to JavaScript or native code. It was
developed by JetBrains and officially supported by Google for Android app

15
development since 2017. Kotlin is known for its conciseness, safety features, and
interoperability with Java, making it a popular choice for Android development
and other JVM-based applications.

Key features of Kotlin include:

1. Conciseness: Kotlin reduces boilerplate code common in Java, making code more
readable and maintainable. Features like type inference, data classes, and extension
functions contribute to this.
2. Null Safety: Kotlin's type system distinguishes between nullable and non-nullable
types, reducing the risk of null pointer exceptions. This is achieved through the use
of nullable types (Type?) and safe call operator (?.).
3. Interoperability: Kotlin is fully interoperable with Java, allowing developers to
use Kotlin and Java code together in the same project. This makes it easy to adopt
Kotlin gradually in existing Java projects.
4. Extension Functions: Kotlin allows adding new functions to existing classes
without modifying their source code. These functions are called extension
functions and can be used to extend the functionality of classes from external
libraries or SDKs.
5. Smart Casts: Kotlin's type system includes smart casts, which automatically cast a
variable to a more specific type when certain conditions are met. This reduces the
need for explicit type checks and casts in code.
6. Coroutines: Kotlin provides first-class support for coroutines, which are a way to
write asynchronous, non-blocking code. Coroutines simplify the handling of
asynchronous tasks compared to traditional callback-based approaches.
7. Functional Programming Support: Kotlin includes features from functional
programming paradigms, such as higher-order functions, lambda expressions, and

16
immutable data structures. These features enable concise and expressive code for
handling collections and other tasks.

Overall, Kotlin offers a modern and expressive syntax that improves productivity
and developer experience, especially for Android development. Its compatibility
with existing Java codebases and its safety features make it a compelling choice for
a wide range of software development projects.

• Hardware Requirements Android mobile:


➢ Version 4.4 or higher.
➢ 7 RAM: 512 MB or higher.
➢ Device must be enabled for USB debugging.
➢ Processor: 1GHZ or higher

17
CHAPTER 5
SYSTEM DESIGN
System Design for the Health Detective App:

The system design phase of the Health Detective App involves architecting the
overall structure and components of the app to ensure scalability, reliability, and
performance. Here are key aspects of the system design:

1. Architecture Overview:
• The app follows a client-server architecture, where the client-side
application runs on users' Android devices, and the server-side components
handle data processing, storage, and business logic.
• The client-side application communicates with the server using RESTful
APIs over HTTPS for data exchange and synchronization.
2. Component Diagram:
• The system consists of several interconnected components, including:
• User Interface (UI): Responsible for presenting information to users
and collecting user input.
• Business Logic: Implements the core functionality of the app,
including disease prediction, MRI image analysis, doctor
recommendation, and appointment scheduling.
• Data Access Layer: Manages data storage and retrieval, including
user profiles, health data, disease information, and doctor directories.
• Machine Learning Model: Implements deep learning algorithms for
disease prediction and MRI image analysis.
• Database: Utilizes SQLite for local storage of user data within the
app and possibly a remote database for server-side data storage.

18
3. User Interface Design:
• The user interface is designed to be intuitive, user-friendly, and accessible,
following Material Design principles for consistency and familiarity.
• Key UI components include screens for symptom input, disease prediction
results, doctor recommendations, appointment scheduling, BMI calculation,
and health data management.
4. Data Flow Diagram:
• The data flow diagram illustrates the flow of data and interactions between
different components of the system.
• It depicts how user input is processed, analyzed, and presented back to the
user, as well as interactions with external services and databases.
5. Security Considerations:
• Security measures are implemented to protect user data and ensure privacy
and confidentiality.
• This includes encryption of sensitive data, secure authentication
mechanisms, and adherence to relevant data protection regulations.
6. Scalability and Performance:
• The system is designed to be scalable to accommodate a growing user base
and increasing data volume.
• Performance optimizations are implemented to ensure fast response times
and smooth user experience, including efficient data caching, asynchronous
processing, and resource management.
7. Error Handling and Recovery:
• Robust error handling mechanisms are implemented to detect and handle
exceptions gracefully, ensuring that the app remains stable and responsive
even in the event of failures or unexpected conditions.

19
• Error logging and monitoring tools are employed to track and diagnose
issues, facilitating rapid resolution and continuous improvement.

By designing the system architecture, components, and interactions in a systematic


and well-structured manner, the Health Detective App is poised to deliver a
seamless and efficient user experience while providing valuable health
management and diagnostic capabilities to its users.

DFD 0 Level

20
DFD 1 Level

21
DFD 2 Level

22
CHAPTER 6
SNAPSHOTS AND WORKING OF MODULE

1. Splash Screen:

Visual Impact:

• Female doctor: Represents the app's focus on health and professional


guidance.
• Detective hat: Reinforces the app's theme of investigation and proactive
problem-solving related to health.
• Thermometer: Symbolizes the app's ability to monitor and track health data.

23
• Magnifier glass: Highlights the app's role in uncovering insights and
understanding health issues.
• Sky blue background: Evokes a sense of calmness, trust, and open
communication.

Functionality:

• Splash screen: Acts as the initial screen users see when launching the app.
• Animation: Adds a touch of dynamism and makes the splash screen more
visually appealing.
• Text "The Health Detectives": Clearly communicates the app's name and
brand identity.

Overall Impression:

• The splash screen sets the tone for the app, conveying a message of
professional yet approachable healthcare assistance.
• It piques the user's interest by highlighting the app's investigative and
informative nature.
• The animation adds a touch of fun and modernity, making the app feel
engaging.

2. Logo of the Project :

24
3. Login Screen:

The login screen of the Health Detective App consists of two text fields for
the user to enter their email and password, along with two buttons: a "Login"
button and a "Sign Up" button. Here's how the login screen works:

25
1. Email and Password Validation: When the user enters their email and
password, the app validates these fields to ensure they meet the required
criteria (e.g., valid email format, password length).

2. Login Button: When the user taps the "Login" button, the app attempts to
authenticate the user using the provided email and password. This involves
sending a request to the authentication server (e.g., Firebase Authentication)
to verify the user's credentials.
• If the credentials are valid, the user is successfully logged in, and they
are directed to the app's home screen.
• If the credentials are invalid, the app displays an error message
informing the user that their login attempt was unsuccessful.

3. Sign Up Button: If the user does not have an account or wishes to create a
new account, they can tap the "Sign Up" button. This takes them to the sign-
up screen, where they can enter their details to create a new account.

Overall, the login screen provides a simple and intuitive interface for users to
authenticate and access the Health Detective App's features and
functionalities.

4. SingUp Screen:

26
The signup screen of the Health Detective App features a unique design with
a hand holding a heart, symbolizing care and health. The screen includes four
fields for the user to enter their username, phone number, email, and
password, along with two buttons: a "Register" button and a "Click here to
login" button. Here's how the signup screen works:

1. Email and Password Validation: Similar to the login screen, the signup
screen validates the email and password fields to ensure they meet the
required criteria (e.g., valid email format, password length).

2. Empty Validation: The screen also checks for empty fields to ensure that all
required fields (username, phone number, email, password) are filled in
before proceeding with registration.

27
3. Register Button: When the user taps the "Register" button, the app attempts
to create a new account using the provided details. This involves sending a
request to the authentication server (e.g., Firebase Authentication) to create a
new user account.
• If the registration is successful, the user is notified and can proceed to
login using their newly created account.
• If there are any errors (e.g., duplicate email, weak password), the app
displays an error message informing the user of the issue and prompts
them to correct it.

4. Click Here to Login Button: If the user already has an account or wishes to
login, they can tap the "Click here to login" button. This takes them back to
the login screen, where they can enter their credentials to login.

5. Back Navigation: Optionally, you can include a way for the user to navigate
back to the previous screen if they decide not to register at that time.

Overall, the signup screen provides a visually appealing and user-friendly


interface for users to create a new account and access the Health Detective
App's features.

5. Home Screen:

28
The Home Screen of the Health Detective App serves as the main hub where
users can access various features and functionalities of the app. The screen
features a drawer navigation menu that provides easy access to different
sections of the app, as well as a slide bar that displays project features and
options for disease detection based on symptoms and MRI images.

1. Drawer Navigation Menu:

• The drawer navigation menu provides access to different sections of the app,
such as:
• Diseases Prediction: Allows users to enter symptoms and receive
predictions of possible diseases.

29
• Disease Detection: Provides options for disease detection based on
symptoms and MRI images.
• Disease Information: Offers detailed information about various
diseases.
• Recommended Doctors: Provides a list of doctors recommended for
specific diseases.
• Fix Doctor Appointment: Allows users to schedule appointments with
recommended doctors.
• BMI Calculator: Offers a tool for calculating Body Mass Index based
on user inputs.
• Upload Patients Data: Enables users to securely upload and manage
patient data.

2. Slide Bar:

• The slide bar displays project features and options for disease detection:
• Project Features: Provides an overview of the app's key features, such
as disease prediction, doctor recommendation, and BMI calculator.
• Diseases Detection: Offers options for disease detection based on
symptoms and MRI images.

3. Disease Detection Based on Symptoms:

• Users can enter their symptoms into the app, and based on the input, the app
predicts possible diseases that match those symptoms. This feature helps
users understand their health condition and seek appropriate medical advice.

30
4. Disease Detection Based on MRI Images:

• Users can upload MRI images, such as those for brain tumors, Alzheimer's,
and lung cancer, for disease detection. The app uses advanced AI algorithms
to analyze the images and provide predictions, aiding in early disease
detection and treatment.

Overall, the Home Screen of the Health Detective App provides users with a
central location to access key features and functionalities related to health
management, disease prediction, and detection. The intuitive interface and
navigation options make it easy for users to navigate the app and make
informed decisions about their health.

6. Drawer Navigation Menu:

31
The Drawer Navigation in the Health Detective App provides users with a
convenient way to navigate between different sections of the app. It features a
welcome message, user photo, and a beautiful sky blue wave design, creating
an inviting and visually appealing interface. The navigation menu allows
users to access various features and functionalities of the app, providing a
seamless user experience. Here's a detailed overview of the Drawer
Navigation:

1. Welcome Message and User Photo:

• The Drawer Navigation starts with a welcoming message to the user, creating
a personalized touch.

32
• It also displays the user's photo, adding a sense of familiarity and
customization to the app.

2. Sky Blue Wave Design:

• The sky blue wave design adds a visual element to the Drawer Navigation,
making it more attractive and engaging.
• The design choice reflects the app's focus on health and well-being, creating a
calming and soothing effect.

3. Features of the App:

• The Drawer Navigation provides access to key features of the app, such as:
• Diseases Prediction: Allows users to predict diseases based on
symptoms.
• Disease Detection: Offers options for disease detection using AI
algorithms.
• Disease Information: Provides detailed information about various
diseases.
• Recommended Doctors: Lists doctors recommended for specific
diseases.
• Fix Doctor Appointment: Enables users to schedule appointments with
recommended doctors.
• BMI Calculator: Provides a tool for calculating Body Mass Index.
• Upload Patients Data: Allows users to securely upload and manage
patient data.

33
4. Navigation to Other Screens:

• Each feature listed in the Drawer Navigation is clickable, allowing users to


navigate to the corresponding screen for more information or action.
• Users can easily switch between different sections of the app, making it
convenient to access the desired information or functionality.

5. User-Friendly Interface:

• The Drawer Navigation is designed to be user-friendly, with clear labels and


intuitive navigation options.
• It enhances the overall user experience by providing quick and easy access to
the app's features and functionalities.

6. Customization Options:

• The Drawer Navigation can be customized to suit the user's preferences, such
as changing the theme color or rearranging the menu items.
• This customization allows users to personalize their app experience, making
it more enjoyable and engaging.

Overall, the Drawer Navigation in the Health Detective App enhances


usability and accessibility, making it easier for users to navigate the app and
access its features. The combination of a welcoming message, user photo,
and attractive design creates a pleasant and immersive user experience,
contributing to the app's overall appeal.

34
7. User Profile:

The User Profile screen in the Health Detective App serves as a centralized
location for users to view and manage their personal information. It includes
various fields such as user image, name, age, gender, phone number, address,
email, password, and read ID. The screen also features an "Edit Profile"
button, allowing users to update their information as needed. Here's a detailed
overview of the User Profile screen:

1. User Image:

35
• The User Profile screen displays the user's profile image, providing a visual
representation of the user.
• Users can upload or change their profile image to personalize their profile.

2. Name, Age, Gender:

• The screen includes fields for the user's name, age, and gender, providing
basic demographic information.
• Users can update these fields to ensure their profile is up-to-date.

3. Phone Number, Address, Email:

• The User Profile screen includes fields for the user's phone number, address,
and email address, allowing users to provide contact information.
• Users can edit these fields to update their contact details.

4. Password:

• The screen includes a field for the user's password, which is displayed as
masked characters for security reasons.
• Users can change their password by entering their current password and then
entering a new password.

5. Read ID:

• The Read ID is a unique identifier assigned to each user, which is used to


access their records and information.
• The Read ID is displayed on the profile screen for reference.

36
6. Edit Profile Button:

• The "Edit Profile" button allows users to update their profile information.
• When clicked, the button opens a form or dialog where users can edit their
details and save the changes.

7. User-Friendly Interface:

• The User Profile screen is designed to be user-friendly, with clear labels and
input fields for each piece of information.
• The interface is intuitive, making it easy for users to navigate and update
their profile information.

8. Privacy and Security:

• The User Profile screen prioritizes user privacy and security, with features
such as masked password fields and secure data storage.
• Users can feel confident that their personal information is protected.

9. Accessibility and Customization:

• The User Profile screen is accessible and customizable, allowing users to


adjust their profile settings to suit their preferences.
• Users can easily manage their profile information and update it as needed.

Overall, the User Profile screen in the Health Detective App provides users
with a convenient and secure way to manage their personal information. It
enhances the user experience by offering a centralized location for users to

37
view and update their profile details, ensuring that their information is up-to-
date and accurate.

8. Disease Detection Based On Symptoms:

The Disease Detection Based on Symptom screen in the Health Detective


App allows users to predict diseases based on the symptoms they select. The
screen includes a message indicating that users should choose three or more
symptoms for the best prediction accuracy. The screen features an
autocomplete view that displays 133 disease symptoms, making it easy for
users to select their symptoms.

38
Once users select their symptoms, they can set them using a "Set Symptoms"
button. The selected symptoms are displayed in a RecyclerView, allowing
users to review their choices. After selecting their symptoms, users can click
a "Show Result" button to initiate the disease prediction process.

1. Text Prompt:

• The text prompt encourages users to select three or more symptoms for the
best prediction accuracy, guiding them on how to use the feature effectively.

2. Autocomplete View:

• The autocomplete view provides a list of 133 disease symptoms, making it


easier for users to select their symptoms from a comprehensive list.

3. Set Symptoms Button:

• The "Set Symptoms" button allows users to confirm their selected symptoms
and proceed with the prediction process.

4. RecyclerView for Selected Symptoms:

• The RecyclerView displays the symptoms selected by the user, allowing


them to review their choices before proceeding.

5. Show Result Button:

• The "Show Result" button triggers the disease prediction process based on
the selected symptoms.

39
6. Disease Prediction Results:

• After clicking the "Show Result" button, the app uses a deep learning
algorithm to predict potential diseases based on the selected symptoms.
• The predicted diseases are displayed in a RecyclerView, showing the names
of the diseases and their corresponding prediction accuracy.

7. Disease Information and Doctor Appointment Options:

• Each disease prediction card in the RecyclerView includes options for


viewing more information about the disease and scheduling a doctor
appointment.
• Users can click on these options to access detailed disease information or
schedule an appointment with a recommended doctor.

8. User-Friendly Interface:

• The Disease Detection Based on Symptom screen is designed to be user-


friendly, with clear instructions and intuitive controls for selecting and
reviewing symptoms.

9. Accuracy and Reliability:

• The deep learning algorithm used for disease prediction aims to provide
accurate and reliable predictions based on the selected symptoms, helping
users make informed decisions about their health.

40
Overall, the Disease Detection Based on Symptom screen provides users with
a powerful tool for predicting diseases based on their symptoms, helping
them understand their health condition and take appropriate actions.

9. Disease Detection Based On MRI image:

The Disease Detection Based on MRI Images screen in the Health Detective
App allows users to predict diseases such as brain tumors, Alzheimer's, and
lung diseases based on MRI images. The screen features options to either
select an image from the gallery or capture a new image using the device's

41
camera. After selecting or capturing an image, users can click a "Show
Result" button to initiate the disease prediction process.

1. Gallery and Camera Buttons:

• The Gallery button allows users to select an MRI image from their device's
gallery.
• The Camera button enables users to capture a new MRI image using their
device's camera.

2. Show Result Button:

• The "Show Result" button triggers the disease prediction process based on
the selected or captured MRI image.

3. Disease Prediction Results:

• After clicking the "Show Result" button, the app uses a deep learning
algorithm to predict potential diseases based on the MRI image.
• The predicted diseases are displayed, showing the names of the diseases and
their corresponding prediction accuracy.

4. Disease Information and Doctor Appointment Options:

• Each disease prediction card includes options for viewing more information
about the disease and scheduling a doctor appointment.
• Users can click on these options to access detailed disease information or
schedule an appointment with a recommended doctor.

42
5. Diseases Detected:

• The deep learning algorithm used for disease detection is capable of detecting
brain tumors, Alzheimer's disease, and lung diseases based on MRI images.

6. User-Friendly Interface:

• The Disease Detection Based on MRI Images screen is designed to be user-


friendly, with clear instructions and intuitive controls for selecting or
capturing images and viewing results.

7. Accuracy and Reliability:

• The deep learning algorithm aims to provide accurate and reliable predictions
based on MRI images, helping users understand their health condition and
take appropriate actions.

Overall, the Disease Detection Based on MRI Images screen provides users
with a powerful tool for predicting diseases based on MRI images, enabling
early detection and timely intervention for better health outcomes.

10. Get Disease Information Screen:

43
The Disease Information screen in the Health Detective App allows users to
access detailed information about various diseases. The screen features an
autocomplete view that displays a list of disease names, making it easy for
users to select a disease of interest. After selecting a disease, users can press a
"Get Information" button to load the corresponding information from a URL
in a WebView.

1. Autocomplete View:

• The autocomplete view provides a list of disease names, allowing users to


easily select a disease of interest.
• This feature helps users quickly find information about specific diseases
without manually searching for them.
44
2. Get Information Button:

• The "Get Information" button triggers the loading of disease information


from a URL in a WebView.
• Users can press this button after selecting a disease to view detailed
information about it.

3. Disease Information Display:

• After pressing the "Get Information" button, the app loads the information
about the selected disease from a URL.
• The disease information is displayed in a WebView, providing users with
detailed descriptions, symptoms, causes, treatments, and other relevant
information about the disease.

4. User-Friendly Interface:

• The Disease Information screen is designed to be user-friendly, with a clear


layout and intuitive controls for selecting a disease and viewing information.
• The autocomplete view and "Get Information" button make it easy for users
to access the information they need quickly.

5. WebView for Displaying Information:

• The WebView component is used to display the disease information loaded


from the URL.
• This allows users to view the information within the app without navigating
to an external website.
45
6. Comprehensive Disease Information:

• The app provides comprehensive information about various diseases,


including descriptions, symptoms, causes, treatments, and prevention
measures.
• Users can use this information to educate themselves about different diseases
and make informed decisions about their health.

Overall, the Disease Information screen provides users with a valuable


resource for learning about various diseases, helping them understand the
conditions better and make informed decisions about their health.

11. Doctor Recommendation Screen:

46
The Doctor Recommendation screen in the Health Detective App provides
users with a list of recommended doctors based on their selected disease and
specialist. The screen features a RecyclerView that displays doctors'
information, including their name, image, specialist, and rate. The screen also
includes a filter option that allows users to filter doctors based on disease and
specialist criteria.

1. RecyclerView for Doctor List:

• The RecyclerView displays a list of doctors recommended for the selected


disease and specialist.
• Each doctor card includes their name, image, specialist, and rate, providing
users with relevant information to make an informed choice.

2. Doctor Filtering:

• The filter option allows users to filter doctors based on their disease and
specialist criteria.
• Users can select a disease and specialist from the filter options to refine the
list of recommended doctors.

3. Cool Animation in the Card:

• The doctor cards feature a cool animation, making the user interface more
engaging and visually appealing.
• This animation adds a touch of interactivity to the screen, enhancing the user
experience.

47
4. User-Friendly Interface:

• The Doctor Recommendation screen is designed to be user-friendly, with a


clear layout and intuitive controls for filtering doctors and viewing their
information.
• The RecyclerView and filter options make it easy for users to find and select
a doctor that meets their criteria.

5. Comprehensive Doctor Information:

• The app provides comprehensive information about each doctor, including


their name, image, specialist, and rate.
• Users can use this information to select a doctor that best suits their needs
and preferences.

6. Accessibility and Customization:

• The Doctor Recommendation screen is accessible and customizable, allowing


users to adjust the filter criteria and view the doctor list based on their
preferences.
• This customization enhances the user experience and makes it easier for users
to find a suitable doctor.

Overall, the Doctor Recommendation screen provides users with a


convenient way to find and select a doctor based on their disease and
specialist criteria. The combination of a RecyclerView, filter options, and

48
cool animations makes the screen engaging and easy to use, helping users
make informed decisions about their healthcare.

12. Doctor Information Screen:

The Doctor Information screen in the Health Detective App provides users
with detailed information about a specific doctor. The screen includes various
fields such as the doctor's image, name, age, number of patients, experience
rating, specialist, about us, working at, and contact information. The screen
also features icons for calling and messaging the doctor, as well as a button to
navigate to the Fix Appointment screen.

49
1. Doctor Image, Name, Age:

• The screen displays the doctor's image, name, and age, providing users with a
visual representation of the doctor.
• This information helps users identify the doctor and build trust.

2. Number of Patients, Experience, Rating:

• The screen includes the number of patients treated by the doctor, their years
of experience, and their rating.
• This information helps users assess the doctor's expertise and reputation.

3. Specialist, About Us, Working At:

• The screen displays the doctor's specialist field, a brief description about the
doctor, and their current workplace.
• This information helps users understand the doctor's expertise and
background.

4. Contact Information:

• The screen includes contact information for the doctor, such as phone number
and email address.
• Users can use this information to contact the doctor directly for appointments
or inquiries.

5. Call and Message Icons:

50
• The screen features icons for calling and messaging the doctor directly from
the app.
• Users can tap these icons to initiate a call or message to the doctor, making it
convenient to communicate with them.

6. Go To Appointment Button:

• The "Go To Appointment" button allows users to navigate to the Fix


Appointment screen to schedule an appointment with the doctor.
• This button provides a seamless transition for users who wish to make
an appointment after viewing the doctor's information.

Overall, the Doctor Information screen provides users with


comprehensive information about a specific doctor, helping them
make informed decisions about their healthcare and facilitating
communication with the doctor.

13. Fix Appointment Screen:

51
The Fix Appointment screen in the Health Detective App allows users to
schedule an appointment with a doctor. The screen includes fields for the
patient's image, name, age, gender, phone number, address, email address,
disease, date, and time. It also features a "Set Appointment" button to
confirm the appointment. Here's a detailed overview of the Fix Appointment
screen:

1. Patient Image, Name, Age, Gender:

• The screen displays the patient's image, name, age, and gender, providing a
visual representation of the patient.
• This information helps the doctor identify the patient and prepare for the
appointment.
52
2. Phone Number, Address, Email Address:

• The screen includes fields for the patient's phone number, address, and email
address, allowing the doctor to contact the patient and send appointment
reminders.
• This information is essential for communication and ensuring that the patient
receives important information about their appointment.

3. Disease:

• The screen includes a field for the patient's disease or reason for the
appointment, providing the doctor with context for the appointment.
• This information helps the doctor prepare for the appointment and ensure that
the patient receives the appropriate care.

4. Date and Time:

• The screen includes fields for selecting the date and time of the appointment.
• Users can choose a convenient date and time for their appointment, making it
easier to schedule around their other commitments.

5. Set Appointment Button:

• The "Set Appointment" button confirms the appointment and schedules it


with the doctor.
• Users can tap this button to finalize their appointment details and receive
confirmation of their appointment.

53
Overall, the Fix Appointment screen provides users with a convenient and
efficient way to schedule appointments with doctors, ensuring that they
receive the care they need in a timely manner.

13. Appointment Status Screen:

The Appointment Status screen in the Health Detective App displays the
appointments of patients in a RecyclerView. Each appointment card includes
the patient's name, disease, date, and time of the appointment. The screen
provides users with an overview of their upcoming appointments, helping

54
them manage their healthcare schedule efficiently. Here's a detailed overview
of the Appointment Status screen:

1. RecyclerView for Appointment List:

• The RecyclerView displays a list of appointments scheduled by the user.


• Each appointment card includes the patient's name, disease, date, and time of
the appointment, providing users with essential information at a glance.

2. Appointment Details:

• The appointment cards show the patient's name, allowing users to identify the
patient easily.
• The cards also display the patient's disease, date, and time of the
appointment, helping users plan their schedule accordingly.

3. User-Friendly Interface:

• The Appointment Status screen is designed to be user-friendly, with a clear


layout and intuitive controls for viewing appointment details.
• The interface is easy to navigate, making it simple for users to manage their
appointments.

4. Comprehensive Appointment Management:

• The Appointment Status screen provides users with a comprehensive view of


their upcoming appointments, helping them stay organized and manage their
healthcare schedule effectively.

55
Overall, the Appointment Status screen provides users with a convenient and
efficient way to view and manage their appointments, ensuring that they
receive the care they need in a timely manner.

14. Patients Information Screen:

The Patient Information screen in the Health Detective App displays detailed
information about a specific patient. It includes fields such as the patient's
image, name, age, gender, phone number, address, email address, disease,
date, and time of the appointment. This screen provides healthcare providers
with essential information about their patients, helping them deliver
personalized care. Here's a detailed overview of the Patient Information
screen:

56
1. Patient Image, Name, Age, Gender:

• The screen displays the patient's image, name, age, and gender, providing a
visual representation of the patient.
• This information helps healthcare providers identify the patient and
personalize their care.

2. Phone Number, Address, Email Address:

• The screen includes fields for the patient's phone number, address, and email
address, allowing healthcare providers to contact the patient and send
important information.
• This information is essential for communication and ensuring that the patient
receives the necessary care.

3. Disease, Date, and Time of Appointment:

• The screen displays the patient's disease, date, and time of the appointment,
providing healthcare providers with context for the appointment.
• This information helps healthcare providers prepare for the appointment and
ensure that the patient receives the appropriate care.

4. User-Friendly Interface:

• The Patient Information screen is designed to be user-friendly, with a clear


layout and intuitive controls for viewing patient information.
• The interface is easy to navigate, making it simple for healthcare providers to
access patient information quickly.
57
5. Comprehensive Patient Information:

• The app provides comprehensive information about each patient, including


their name, image, age, gender, disease, contact information, and
appointment details.
• Healthcare providers can use this information to deliver personalized care
and ensure that the patient's needs are met.

Overall, the Patient Information screen provides healthcare providers with a


comprehensive view of their patients' information, helping them deliver
personalized care and ensure that patients receive the best possible treatment.

15. BMI Screen:

58
The BMI Calculation screen in the Health Detective App allows users to
calculate their Body Mass Index (BMI) based on their height and weight. The
screen features number pickers for selecting the height and weight values, as
well as a "Calculate BMI" button to perform the calculation. After calculating
the BMI, the app navigates to the BMI Result screen to display the calculated
BMI along with the height and weight values. Here's a detailed overview of
the BMI Calculation screen:

1. Number Pickers for Height and Weight:

• The screen includes number pickers for selecting the height and weight
values.
• Users can use these number pickers to input their height and weight, making
it easy to enter accurate values for the BMI calculation.

2. Calculate BMI Button:

• The "Calculate BMI" button triggers the BMI calculation process based on
the selected height and weight values.
• Users can tap this button to perform the BMI calculation and view the results.

3. BMI Calculation Process:

• After the user selects their height and weight values and taps the "Calculate
BMI" button, the app calculates the BMI using the formula:
BMI = weight (kg) / (height (m) * height (m)).
• The calculated BMI is then sent to the BMI Result screen for display.

59
4. User-Friendly Interface:

• The BMI Calculation screen is designed to be user-friendly, with clear


instructions and intuitive controls for entering height and weight values.
• The interface is easy to navigate, making it simple for users to calculate their
BMI.

5. Accessibility and Customization:

• The BMI Calculation screen is accessible and customizable, allowing users to


adjust the height and weight values to suit their preferences.
• This customization enhances the user experience and makes it easier for users
to calculate their BMI accurately.

6. Seamless Navigation to BMI Result Screen:

• After calculating the BMI, the app navigates to the BMI Result screen to
display the calculated BMI along with the height and weight values.
• This seamless navigation allows users to view their BMI results quickly and
easily.

Overall, the BMI Calculation screen provides users with a convenient tool for
calculating their BMI based on their height and weight, helping them monitor
their health and fitness levels.

15. BMI Result Screen:

60
Body Mass Index (BMI) is a measure of body fat based on a person's weight
in relation to their height. It is used as an indicator of whether a person is
underweight, normal weight, overweight, or obese. The BMI categories are
defined as follows:

1. Underweight: BMI less than 18.5


• People with a BMI below 18.5 are considered underweight.
• Being underweight can be associated with health risks such as
weakened immune system, osteoporosis, and fertility issues.
2. Normal Weight: BMI between 18.5 and 24.9
• A BMI between 18.5 and 24.9 is considered normal or healthy.
• People in this range are at lower risk for health problems related to
weight.
61
3. Overweight: BMI between 25.0 and 29.9
• A BMI between 25.0 and 29.9 is considered overweight.
• Overweight individuals are at higher risk for health issues such as heart
disease, diabetes, and high blood pressure.
4. Obese: BMI of 30 or higher
• A BMI of 30 or higher is considered obese.
• Obesity significantly increases the risk of developing serious health
conditions, including heart disease, stroke, type 2 diabetes, and certain
types of cancer.

BMI is a useful screening tool, but it is not a diagnostic tool. Other factors
such as muscle mass, bone density, and distribution of fat can affect BMI
results. It is important to consult with a healthcare provider to determine the
most appropriate weight management plan based on individual health factors.

BMI Result Screen

The BMI Result screen in the Health Detective App displays the calculated
Body Mass Index (BMI) result in terms of different categories such as
underweight, normal weight, overweight, and obese. The screen also provides
users with information about the implications of their BMI category on their
health. Additionally, the screen includes buttons for accessing disease
information and scheduling a doctor's appointment. Here's a detailed
overview of the BMI Result screen:

62
1. BMI Result Display:

• The screen displays the calculated BMI result.


• This categorization helps users understand their BMI status and its
implications on their health.

2. BMI Category Information:

• The screen provides information about each BMI category, including the
potential health risks associated with being underweight, overweight, or
obese.
• This information helps users understand the importance of maintaining a
healthy BMI and the potential consequences of being under or overweight.

3. Disease Information Button:

• The screen includes a button for accessing information about diseases related
to BMI, such as heart disease, diabetes, and hypertension.
• Users can tap this button to learn more about the health risks associated with
their BMI category and how they can mitigate these risks.

4. Doctor Appointment Button:

• The screen features a button for scheduling a doctor's appointment.


• Users can use this button to schedule an appointment with a healthcare
provider to discuss their BMI results and receive personalized advice on
maintaining a healthy weight.

63
5. User-Friendly Interface:

• The BMI Result screen is designed to be user-friendly, with clear labels and
intuitive controls for accessing BMI information and scheduling a doctor's
appointment.
• The interface is easy to navigate, making it simple for users to understand
their BMI results and take appropriate action.

6. Accessibility and Customization:

• The BMI Result screen is accessible and customizable, allowing users to


adjust the font size, color scheme, and other settings to suit their preferences.
• This customization enhances the user experience and makes it easier for users
to access the information they need.

Overall, the BMI Result screen provides users with valuable information
about their BMI status and its implications on their health. It empowers users
to make informed decisions about their health and take proactive steps to
maintain a healthy weight.

15. Patients Records Screen:

64
The Patients Records screen in the Health Detective App displays patients'
records according to the date. It includes a button to upload records, which
opens the Upload Records screen. The Upload Records screen features a
"Select Files" button to choose files from local storage. Additionally, the
screen includes an eye icon that, when clicked, opens a screen with fields for
email and read ID to fetch another patient's data. Here's a detailed overview
of the Patients Records screen:

1. Date-wise Records Display:

• The screen displays patients' records organized according to the date.


• This organization helps users easily navigate through and access specific
records.
65
2. Upload Records Button:

• The screen includes a button to upload records, which opens the Upload
Records screen.
• Users can use this feature to add new records to the app for future reference
and analysis.

3. Upload Records Screen:

• The Upload Records screen features a "Select Files" button to choose files
from local storage.
• Users can select files containing patient records to upload them to the app.

4. Eye Icon for Fetching Data:

66
• The screen includes an eye icon that, when clicked, opens a screen with fields
for email and read ID to fetch another patient's data.
• This feature allows users to easily access and view the records of specific
patients by entering their email and read ID.

5. User-Friendly Interface:

• The Patients Records screen is designed to be user-friendly, with clear labels


and intuitive controls for uploading records and fetching data.
• The interface is easy to navigate, making it simple for users to access and
manage patient records.
• Overall, the Patients Records screen provides users with a convenient way to
access and manage patient records, ensuring that they can easily find and
review relevant information when needed.
67
Chapter 7
DATABASE

Firebase is a platform developed by Google for creating mobile and web


applications. It provides a suite of tools and services to help developers build
high-quality apps, including authentication, real-time database, storage,
hosting, and more. Here's an overview of some key features of Firebase and
how to use it in an Android app:

Key Features of Firebase:

1. Real Time Database: Firebase provides a cloud-hosted NoSQL database


that allows you to store and sync data between users in real-time. It's great for
building collaborative apps that require real-time updates.

68
2. Authentication: Firebase Authentication provides easy-to-use SDKs and
ready-made UI libraries to authenticate users using email/password, phone
numbers, or popular third-party providers like Google, Facebook, and
Twitter.

69
3. Storage: Firebase Storage is a powerful, simple, and scalable object storage
service built for Google scale. It allows you to store user-generated content,
such as photos and videos, and serve them directly to your app.

4. Cloud Firestore: Firestore is Firebase's next-generation document database.


It's a flexible, scalable database for mobile, web, and server development.
Firestore offers seamless integration with other Firebase services and real-
time data synchronization.
5. Cloud Functions: Firebase Cloud Functions allow you to run backend code
in response to events triggered by Firebase features and HTTPS requests.
This lets you extend your app's functionality without managing servers.
6. Hosting: Firebase Hosting provides fast and secure hosting for your web app,
with features like custom domains, SSL support, and continuous deployment.

70
Using Firebase in an Android App:

To use Firebase in an Android app, you need to follow these steps:

1. Set up Firebase in your project: Add Firebase to your Android app by


following the Firebase documentation. This involves adding the Firebase
SDK to your project and configuring your app to use Firebase services.
2. Authentication: Implement Firebase Authentication in your app to enable
user sign-in and sign-up. You can use FirebaseUI to quickly add
authentication UI to your app.
3. Real Time Database or Firestore: Choose between the Firebase Realtime
Database or Firestore for storing and syncing data in real-time. You'll need to
set up your database structure and implement the necessary code to read and
write data.
4. Firebase Storage: Use Firebase Storage to store files like images, videos,
and documents. You'll need to upload files to Firebase Storage and retrieve
them in your app.
5. Cloud Functions (optional): Use Firebase Cloud Functions to run backend
code in response to events triggered by Firebase features or HTTP requests.
This allows you to add server-side logic to your app without managing
servers.
6. Firebase Hosting (optional): If you're building a web app, use Firebase
Hosting to deploy and host your app.

Overall, Firebase provides a comprehensive set of tools and services to help


you build high-quality apps with features like real-time data sync,

71
authentication, and file storage. It's easy to integrate Firebase into your
Android app and leverage its powerful features to enhance your app's
functionality.

72
Chapter 8
CODING

1. Splash Screen:

package com.example.healthdetectiveapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.animation.AnimationUtils
import android.widget.Toast
import
com.example.healthdetectiveapp.databinding.ActivitySplashScreenB
inding
import com.google.firebase.auth.FirebaseAuth

class SplashScreen : AppCompatActivity() {


private lateinit var auth: FirebaseAuth
private val binding:ActivitySplashScreenBinding by lazy {
ActivitySplashScreenBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {

73
super.onCreate(savedInstanceState)
setContentView(binding.root)
auth = FirebaseAuth.getInstance()
val bounce =
AnimationUtils.loadAnimation(this,R.anim.logo_anim)
binding.logoImg.startAnimation(bounce)
val upCome =
AnimationUtils.loadAnimation(this,R.anim.come_up)
binding.hd.startAnimation(upCome)
val leftCome =
AnimationUtils.loadAnimation(this,R.anim.come_left)
binding.hdFull.startAnimation(leftCome)
val rightCome =
AnimationUtils.loadAnimation(this,R.anim.come_right)
binding.slogan.startAnimation(rightCome)
val fade =
AnimationUtils.loadAnimation(this,R.anim.fade_anim)
binding.splashImg.startAnimation(fade)

override fun onStart() {


super.onStart()
if (auth.currentUser!=null){
Handler(Looper.getMainLooper()).postDelayed({
val next = Intent(this,MainActivity::class.java)
74
finish()
startActivity(next)
},4000)
}
else{
Handler(Looper.getMainLooper()).postDelayed({
val next = Intent(this,Login_Activity::class.java)
finish()
startActivity(next)
},4000)
}
}
}

2. Login Screen :
package com.example.healthdetectiveapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.healthdetectiveapp.databinding.ActivityLoginBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth

75
import com.google.firebase.ktx.Firebase

class Login_Activity : AppCompatActivity() {


private val binding:ActivityLoginBinding by lazy {
ActivityLoginBinding.inflate(layoutInflater)
}
private lateinit var email:String
private lateinit var passward:String
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)

// Initializing
auth = Firebase.auth

binding.btnSignup.setOnClickListener {
startActivity(Intent(this,SignUp_Activity::class.java))
}
binding.btnLogin.setOnClickListener {
email = binding.emailLogin.text.toString().trim()
passward = binding.password.text.toString().trim()

if (!email.isEmpty()){
binding.emailLogin.error = null

76
if (email.matches("^[a-zA-Z0-9._-]+@[a-z]+\\.+[a-
z]+".toRegex())){
binding.emailLogin.error = null
if (!passward.isEmpty()){
binding.password.error = null
LoginAccount(email,passward)
}
else{
binding.password.error ="Please Fill Passward"
}
}
else{
binding.emailLogin.error = "Please Fill Valid Email"
}

}
else{
binding.emailLogin.error ="Please Fill Email"
}
}
}

private fun LoginAccount(email: String, passward: String) {

auth.signInWithEmailAndPassword(email,passward).addOnCompleteListen

77
er {
result ->
if (result.isSuccessful){
val user = auth.currentUser
Toast.makeText(this, "Successfully SignIn",
Toast.LENGTH_SHORT).show()
updateUi(user)
}
else{
Toast.makeText(this, "Incorrect Email or Password",
Toast.LENGTH_SHORT).show()
}
}
}

private fun updateUi(user: FirebaseUser?) {


startActivity(Intent(this,MainActivity::class.java))
finish()
}
}

3. SignUp Screen:

package com.example.healthdetectiveapp

78
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import
com.example.healthdetectiveapp.databinding.ActivitySignUpBi
nding
import com.example.healthdetectiveapp.model.UserModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import java.lang.StringBuilder
import java.security.SecureRandom
import java.util.regex.Pattern

class SignUp_Activity : AppCompatActivity() {


private val binding:ActivitySignUpBinding by lazy {
ActivitySignUpBinding.inflate(layoutInflater)
}
private lateinit var username:String
private lateinit var phone:String
private lateinit var email:String
private lateinit var passward:String
private val auth = FirebaseAuth.getInstance()
private val database = FirebaseDatabase.getInstance()

79
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)

binding.btnGotoLogin.setOnClickListener {
startActivity(Intent(this,Login_Activity::class.java))
}
binding.btnRegister.setOnClickListener {
// Geting Values
username = binding.username.text.toString().trim()
phone = binding.phone.text.toString().trim()
email = binding.email.text.toString().trim()
passward = binding.password.text.toString().trim()

// Performing Validation
if (!username.isEmpty()){
binding.username.error = null
if (!phone.isEmpty()){
binding.phone.error = null
if (phone.matches("[1-9][0-9]{9}".toRegex())){
binding.phone.error = null
if (!email.isEmpty()){
binding.email.error = null
if (email.matches("^[a-zA-Z0-9._-]+@[a-
z]+\\.+[a-z]+".toRegex())){

80
binding.email.error = null
if (!passward.isEmpty()){
binding.password.error = null
createAccount(email,passward)
}
else{
binding.password.error ="Please Fill
Passward"
}
}
else{
binding.email.error ="Please Fill Valid Email"
}
}
else{
binding.email.error ="Please Fill Email"
}
}
else{
binding.phone.error = "Please Fill Valid Phone
Number"
}
}
else{
binding.phone.error ="Please Fill Phone Number"

81
}
}
else{
binding.username.error ="Please Fill Username"
}

}
}

private fun createAccount(email: String, password: String) {


auth.createUserWithEmailAndPassword(email,
password).addOnCompleteListener {
if (it.isSuccessful){
saveUserData()
}
else{
Toast.makeText(this, "${it.exception}",
Toast.LENGTH_SHORT).show()
}
}
}

private fun saveUserData() {


val userId = auth.currentUser!!.uid
val readId = generatePassword(15)

82
if (userId!=null){
val userRef =
database.getReference("UsersProfile").child(userId)
val userData = UserModel(key = userId, name =
username, phone = phone, email = email, passward = passward,
readid = readId)
userRef.setValue(userData).addOnSuccessListener {
Toast.makeText(this, "Account Created Successful",
Toast.LENGTH_SHORT).show()
val gotoMain = Intent(this,MainActivity::class.java)
startActivity(gotoMain)
}

}
}

fun generatePassword(length:Int):String{
val charSet = ('a'..'z')+('A'..'Z')+(0..9)+
listOf('!','@','#','$','%','^','&','*','?','+','-','/')
val secureRandom = SecureRandom()
val password = StringBuilder()
repeat(length,{
val charIndex = secureRandom.nextInt(charSet.size)
password.append(charSet[charIndex])
})

83
return password.toString()
}
}

4. Home Screen:
package com.example.healthdetectiveapp.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.denzcoskun.imageslider.constants.AnimationTypes
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.interfaces.ItemClickListener
import com.denzcoskun.imageslider.models.SlideModel
import com.example.healthdetectiveapp.DieasesDiagnoseByImage
import com.example.healthdetectiveapp.Dieases_Detection_Activity
import com.example.healthdetectiveapp.R
import
com.example.healthdetectiveapp.databinding.FragmentHomeBindin
g

84
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {

}
}

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding =
FragmentHomeBinding.inflate(layoutInflater,container,false)
binding.dieasesonsymptoms.setOnClickListener {

startActivity(Intent(requireContext(),Dieases_Detection_Activity::cl
ass.java))
}

binding.brainTumarCard.setOnClickListener {
val brainIntent =
Intent(requireContext(),DieasesDiagnoseByImage::class.java)
brainIntent.putExtra("cardKey",1)
brainIntent.putExtra("disease","Brain Tumar")
85
startActivity(brainIntent)
}
binding.AlzimerCard.setOnClickListener {
val alzimerIntent =
Intent(requireContext(),DieasesDiagnoseByImage::class.java)
alzimerIntent.putExtra("cardKey",2)
alzimerIntent.putExtra("disease","Alzimer")
startActivity(alzimerIntent)
}
binding.LungsCancerCard.setOnClickListener {
val lungsCancerIntent =
Intent(requireContext(),DieasesDiagnoseByImage::class.java)
lungsCancerIntent.putExtra("cardKey",3)
lungsCancerIntent.putExtra("disease","Lungs Cancer")
startActivity(lungsCancerIntent)
}
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState:


Bundle?) {
super.onViewCreated(view, savedInstanceState)
val imageList = ArrayList<SlideModel>()

imageList.add(SlideModel(R.drawable.slider1,
ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.slider2,
86
ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.slider3,
ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.slider4,
ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.slider5,
ScaleTypes.FIT))
imageList.add(SlideModel(R.drawable.slider6,
ScaleTypes.FIT))

val imageSlider = binding.imageSlider


imageSlider.setImageList(imageList)
imageSlider.setImageList(imageList, ScaleTypes.FIT)

imageSlider.setSlideAnimation(AnimationTypes.DEPTH_SLIDE)
}
}

5. Dieases_Detection_Activity:

package com.example.healthdetectiveapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter

87
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import
com.example.healthdetectiveapp.adapter.DieasesAccuracyAdapter
import com.example.healthdetectiveapp.adapter.SymptomsAdapter
import
com.example.healthdetectiveapp.databinding.ActivityDieasesDetecti
onBinding
import com.example.healthdetectiveapp.ml.Dieasesinfloat
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.nio.ByteBuffer
import java.nio.ByteOrder

class Dieases_Detection_Activity : AppCompatActivity() {


private val binding:ActivityDieasesDetectionBinding by lazy {
ActivityDieasesDetectionBinding.inflate(layoutInflater)
}
val symList = mutableListOf("itching", "skin_rash",
"nodal_skin_eruptions", "continuous_sneezing", "shivering",
"chills", "joint_pain", "stomach_pain", "acidity",
"ulcers_on_tongue", "muscle_wasting", "vomiting",
"burning_micturition", "spotting_ urination", "fatigue",
"weight_gain", "anxiety", "cold_hands_and_feets", "mood_swings",
"weight_loss", "restlessness", "lethargy", "patches_in_throat",
"irregular_sugar_level", "cough", "high_fever", "sunken_eyes",
"breathlessness", "sweating", "dehydration", "indigestion",
88
"headache", "yellowish_skin", "dark_urine", "nausea",
"loss_of_appetite", "pain_behind_the_eyes", "back_pain",
"constipation", "abdominal_pain", "diarrhoea", "mild_fever",
"yellow_urine", "yellowing_of_eyes", "acute_liver_failure",
"fluid_overload", "swelling_of_stomach", "swelled_lymph_nodes",
"malaise", "blurred_and_distorted_vision", "phlegm",
"throat_irritation", "redness_of_eyes", "sinus_pressure",
"runny_nose", "congestion", "chest_pain", "weakness_in_limbs",
"fast_heart_rate", "pain_during_bowel_movements",
"pain_in_anal_region", "bloody_stool", "irritation_in_anus",
"neck_pain", "dizziness", "cramps", "bruising", "obesity",
"swollen_legs", "swollen_blood_vessels", "puffy_face_and_eyes",
"enlarged_thyroid", "brittle_nails", "swollen_extremeties",
"excessive_hunger", "extra_marital_contacts",
"drying_and_tingling_lips", "slurred_speech", "knee_pain",
"hip_joint_pain", "muscle_weakness", "stiff_neck",
"swelling_joints", "movement_stiffness", "spinning_movements",
"loss_of_balance", "unsteadiness", "weakness_of_one_body_side",
"loss_of_smell", "bladder_discomfort", "foul_smell_of urine",
"continuous_feel_of_urine", "passage_of_gases", "internal_itching",
"toxic_look_(typhos)", "depression", "irritability", "muscle_pain",
"altered_sensorium", "red_spots_over_body", "belly_pain",
"abnormal_menstruation", "dischromic _patches",
"watering_from_eyes", "increased_appetite", "polyuria",
"family_history", "mucoid_sputum", "rusty_sputum",
"lack_of_concentration", "visual_disturbances",
"receiving_blood_transfusion", "receiving_unsterile_injections",
89
"coma", "stomach_bleeding", "distention_of_abdomen",
"history_of_alcohol_consumption", "fluid_overload.1",
"blood_in_sputum", "prominent_veins_on_calf", "palpitations",
"painful_walking", "pus_filled_pimples", "blackheads", "scurring",
"skin_peeling", "silver_like_dusting", "small_dents_in_nails",
"inflammatory_nails", "blister", "red_sore_around_nose",
"yellow_crust_ooze")
val symListInFloat = mutableListOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val usersymList = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)

binding.btnResult.isEnabled = false
// Fetching dieases from dieaseslabels.txt
val fileName = "dieaseslabels.txt"
val inputString =
application.assets.open(fileName).bufferedReader().use {
it.readText() }
var finalDieases = inputString.split("\n")

// Set AutocompleteTextView
90
val autocompleteAdapter = ArrayAdapter(this,
com.google.android.material.R.layout.support_simple_spinner_drop
down_item,symList)
val autoComplete = binding.autoComplete
autoComplete.setAdapter(autocompleteAdapter)

// Set Symptoms Buttom


binding.btnSymptoms.setOnClickListener {
val symptoms = autoComplete.text.toString().trim()
if (symptoms.equals("")){
Toast.makeText(this, "Please Select Symptoms",
Toast.LENGTH_SHORT).show()
} else{
usersymList.add(symptoms)
setAdapter()
autoComplete.text.clear()
binding.btnResult.isEnabled = true
}
}

// Set Show Result Button


binding.btnResult.setOnClickListener {
if (usersymList.isNotEmpty()){
// Creating Symptoms List
for (k in 0..symList.size-1){
for( z in usersymList){
if(symList[k].equals(z)){
91
symListInFloat[k] = 1
}
}
}
// Put Symptoms List into byteBuffer
var byteBuffer : ByteBuffer =
ByteBuffer.allocateDirect(symListInFloat.size*4)
byteBuffer.order(ByteOrder.nativeOrder())
for (i in symListInFloat){
byteBuffer.putFloat(i.toFloat())
}

// Create Object of Dieasesinfloat TFLite Model


val model = Dieasesinfloat.newInstance(this)

// Creates inputs for reference.


val inputFeature0 =
TensorBuffer.createFixedSize(intArrayOf(1, 132),
DataType.FLOAT32)
inputFeature0.loadBuffer(byteBuffer)

// Runs model inference and gets result.


val outputs = model.process(inputFeature0)
val outputFeature0 =
outputs.outputFeature0AsTensorBuffer.floatArray

val mapKey = outputFeature0.map {


92
"%.2f".format(it*100).toFloat() }
Log.d("Dieases_mapkey","$mapKey")
// Create mapof
val mapResult = mapKey.zip(finalDieases).toMap()
// sorting keys and values
val sortedKeys = mapResult.keys.sortedDescending()
val sortedValues = mutableListOf<String>()
sortedKeys.forEach {key->
sortedValues.add(mapResult[key]!!)
}
Log.d("Dieases_sortedkey","$sortedKeys")
Log.d("Dieases_sortedvalue","$sortedValues")

setAdapterForDieasesAccuracy(sortedKeys,sortedValues)
usersymList.clear()
// Releases model resources if no longer used.
model.close()
for (zero in 0..symListInFloat.size-1){
symListInFloat[zero] = 0
}
}
else{
Toast.makeText(this, "Please Select Symptoms",
Toast.LENGTH_SHORT).show()
}
}
}
93
private fun
setAdapterForDieasesAccuracy(sortedKey:List<Float>,sortedValue:
MutableList<String>) {
binding.rvDieasesAccuracy.layoutManager =
LinearLayoutManager(this)
val dieasesAccuracyAdapter =
DieasesAccuracyAdapter(this,sortedKey,sortedValue)
binding.rvDieasesAccuracy.adapter = dieasesAccuracyAdapter
}

private fun setAdapter() {


val rvSymptoms = binding.rvSymptoms
rvSymptoms.layoutManager =
LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,f
alse)
val symptomsAdapter = SymptomsAdapter(this,usersymList)
rvSymptoms.adapter = symptomsAdapter
symptomsAdapter.notifyDataSetChanged()
}
fun getMax(arr:FloatArray) : Int{
var ind = 0
var max = 0.0f
for(i in 0..arr.size-1){
if(arr[i]>max){
ind = i
max = arr[i]
94
}
}
return ind
}
}

6. DieasesDiagnoseByImage:

package com.example.healthdetectiveapp

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import
com.example.healthdetectiveapp.databinding.ActivityDieasesDiagno
seByImageBinding
import com.example.healthdetectiveapp.ml.BrainTumor
import org.tensorflow.lite.DataType

95
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer

class DieasesDiagnoseByImage : AppCompatActivity() {


private val binding:ActivityDieasesDiagnoseByImageBinding by
lazy {

ActivityDieasesDiagnoseByImageBinding.inflate(layoutInflater)
}
lateinit var bitmap: Bitmap
lateinit var status:String
var classifier: Classifier?=null
private val CAMERA_REQUEST_CODE = 200
private var index:Int?=null
private lateinit var dieases:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)

val cardvalue = intent.getIntExtra("cardKey",0)


dieases = intent.getStringExtra("disease")!!
binding.btnShowResult.isEnabled = false
binding.txtWarning.setText("Please choose ${dieases} Images
for right result otherwise it gives wrong result")
binding.btnGallery.setOnClickListener {
binding.resultContainer.visibility = View.GONE
pickimage.launch("image/*")
96
}

binding.btnShowResult.setOnClickListener {
binding.resultContainer.visibility = View.VISIBLE
when(cardvalue){
1->{
status= classifier!!.brainTumar()
binding.Result.text = status
index = 41
}
2->{
status= classifier!!.alzimerDetection()
binding.Result.text = status
index = 42
}
3->{
status= classifier!!.lungsCancerDetection()
binding.Result.text = status
index = 43
}
}
}
// Set Dieases Url Information
binding.dieasesInfoImage.setOnClickListener {
val braintumarInfoIntent =
Intent(this,DieasesInformation_Activity::class.java)

97
braintumarInfoIntent.putExtra("requestCode","dieasesInformation")
braintumarInfoIntent.putExtra("urlIndex",index)
startActivity(braintumarInfoIntent)
}

binding.doctorAppointmentImage.setOnClickListener {
val appointmentIntent = Intent(this, MainActivity::class.java)

appointmentIntent.putExtra("OpenScreen","doctorAppointment")
appointmentIntent.putExtra("dieases",dieases)
startActivity(appointmentIntent)
}
// set sample image
binding.btnSampleImage.setOnClickListener {
when(cardvalue){
1->{

binding.dieasesImage.setImageResource(R.drawable.brain_tumar)
}
2->{

binding.dieasesImage.setImageResource(R.drawable.alzimer_sampl
e_image)
}
3->{

binding.dieasesImage.setImageResource(R.drawable.lungs_cancer_s
98
ample)
}
}
}

// set Camera Button


binding.btnCamera.setOnClickListener {
capturePhoto()
}
}
// Pick Image From Gallery
val pickimage =
registerForActivityResult(ActivityResultContracts.GetContent()){
uri ->
if (uri!=null){
binding.btnShowResult.isEnabled = true
binding.dieasesImage.setImageURI(uri)
bitmap =
MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
classifier = Classifier(this,bitmap)
}
}
// Take Image From Camera
fun capturePhoto(){
val cameraIntent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)

99
startActivityForResult(cameraIntent,CAMERA_REQUEST_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int,


data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode== RESULT_OK){
if (requestCode==CAMERA_REQUEST_CODE){
binding.btnShowResult.isEnabled = true
bitmap = data?.extras?.get("data") as Bitmap
binding.dieasesImage.setImageBitmap(bitmap)
classifier = Classifier(this,bitmap)
}
}
}
}

7. DieasesInformation_Activity:

package com.example.healthdetectiveapp

import android.app.ProgressDialog
import android.graphics.Bitmap
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

100
import android.util.Log
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.bumptech.glide.Glide
import
com.example.healthdetectiveapp.databinding.ActivityDieasesInform
ationBinding
import java.net.URLEncoder

class DieasesInformation_Activity : AppCompatActivity() {


private val binding:ActivityDieasesInformationBinding by lazy {
ActivityDieasesInformationBinding.inflate(layoutInflater)
}
private lateinit var webview:WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val fileName = "DieasesInfoUrl.txt"
val inputString =
application.assets.open(fileName).bufferedReader().use {
it.readText() }
var dieasesurl = inputString.split("\n")

val request = intent.getStringExtra("requestCode")


webview = binding.webview
101
webview.settings.javaScriptEnabled = true

when(request){
"dieasesInformation" ->{
val index = intent.getIntExtra("urlIndex",5)
var url = dieasesurl[index]
webview.loadUrl("$url")
}
"bmiResultInformation" ->{
var bmiResultUrl = intent.getStringExtra("bmiResultUrl")
webview.loadUrl("$bmiResultUrl")
}
"opendocument" ->{
val fileurl = intent.getStringExtra("fileurl")
val filename = intent.getStringExtra("filename")
val filemime = intent.getStringExtra("mimetype")
if (filemime!!.startsWith("image")){
binding.doctorSearch.visibility = View.GONE
binding.txtSearch.visibility = View.GONE
webview.visibility = View.GONE
binding.webimg.visibility = View.VISIBLE

Glide.with(this).load(Uri.parse(fileurl)).into(binding.webimg)
}
else{
binding.txtSearch.setText("Opening Document...")
binding.webimg.visibility = View.GONE
102
webview.visibility = View.VISIBLE
val url = URLEncoder.encode(fileurl,"UTF-8")

webview.loadUrl("http://docs.google.com/gview?embedded=true&u
rl=" + url)
}
}
}
webview.webViewClient = object : WebViewClient(){
override fun onPageStarted(view: WebView?, url: String?,
favicon: Bitmap?) {
binding.doctorSearch.visibility = View.VISIBLE

super.onPageStarted(view, url, favicon)


}

override fun onPageCommitVisible(view: WebView?, url:


String?) {
binding.doctorSearch.visibility = View.GONE
binding.txtSearch.visibility = View.GONE
binding.webview.visibility = View.VISIBLE
super.onPageCommitVisible(view, url)
}
}

103
override fun onBackPressed() {
if (webview.canGoBack()){
webview.goBack()
}
else{
super.onBackPressed()
}

}
}
8. DoctorAppointmentFragment:

package com.example.healthdetectiveapp.fragment

import android.app.Dialog
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Button
import android.widget.Toast

104
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.healthdetectiveapp.R
import com.example.healthdetectiveapp.adapter.DoctorsListAdapter
import
com.example.healthdetectiveapp.databinding.FragmentDoctorAppoi
ntmentBinding
import com.example.healthdetectiveapp.model.doctors
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class DoctorAppointmentFragment : Fragment() {


private lateinit var binding:FragmentDoctorAppointmentBinding
private var doctorsArrayList : ArrayList<doctors> = ArrayList()
private lateinit var database: FirebaseDatabase
private lateinit var dialog: Dialog
private lateinit var finaldieases:MutableList<String>
private lateinit var specialistList: List<String>
private lateinit var setfilter: Button
private lateinit var dieases: AutoCompleteTextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {

}
105
}

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding =
FragmentDoctorAppointmentBinding.inflate(layoutInflater,container
,false)

// Fetching dieases from dieaseslabels.txt


val fileName = "alldieases.txt"
val inputString =
context?.assets?.open(fileName)?.bufferedReader().use {
it?.readText() }
finaldieases = inputString?.split("\n") as MutableList<String>

val specialist = "allspecialistforfilter.txt"


val specialistInput =
context?.assets?.open(specialist)?.bufferedReader().use {
it?.readText() }
specialistList = specialistInput!!.split("\n")

// Fetching Doctors List


fetchDoctorsList()
Log.d("argument_doctorsList","$doctorsArrayList")
106
// Creating Filter Dialog
dialog = Dialog(requireContext())

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.filter_dialog)
setfilter = dialog.findViewById(R.id.btn_setfilter)
dieases = dialog.findViewById(R.id.autoComplete_filter)

// Show Filter Dialog on the DoctorsList


binding.filter.setOnClickListener {
// Set AutocompleteTextView
val autocompleteAdapter = ArrayAdapter(requireContext(),
com.google.android.material.R.layout.support_simple_spinner_drop
down_item,finaldieases)
dieases.setAdapter(autocompleteAdapter)
dialog.show()
}

// Set Filter Button


setfilter.setOnClickListener {
val dieases_text = dieases.text.toString().trim()
if (dieases_text.isNotEmpty()){
Log.d("check_dieasestext","$dieases_text")
val specialist = dieasesToSpecialist(dieases_text)
Log.d("check_specialist","$specialist")
val list = filterSpecialist(specialist)
107
Log.d("check_list","$list")
setAdapter(list as ArrayList<doctors>)
dieases.text.clear()
dialog.dismiss()
}
else{
dialog.dismiss()
}

}
return binding.root
}

private fun dieasesToSpecialist(dieasesLabel:String):String {


var ind= 0
Log.d("dieasesToSpecialist5","${finaldieases[2]}")
Log.d("dieasesToSpecialist6","${finaldieases[2].length}")
for (i in 0..finaldieases.size-1){
if (finaldieases[i].trim().equals(dieasesLabel.trim())){
ind = i
Log.d("dieasesToSpecialist1","${i}")
}
Log.d("dieasesToSpecialist2","$i")
}
Log.d("dieasesToSpecialist3","${finaldieases[ind]}")
Log.d("dieasesToSpecialist4","${dieasesLabel}")
val specialist = specialistList.get(ind)
108
return specialist
}

fun filterSpecialist(specialist:String):List<doctors> {
val list = doctorsArrayList.filter {
specialist.trim().contains(it.specilist.toString().trim())
}
return list
}

private fun fetchDoctorsList() {


database = FirebaseDatabase.getInstance()
val doctorListRef: DatabaseReference =
database.reference.child("DoctorsList")
doctorListRef.addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
doctorsArrayList.clear()
for (doctorsSnapshot in snapshot.children) {
val eachItem =
doctorsSnapshot.getValue(doctors::class.java)
eachItem?.let { result ->
doctorsArrayList.add(result)
}
}
// Check Bundle Passing
val dieasesLabel =
109
requireArguments().get("dieases").toString()
if (dieasesLabel.equals("null")){
Log.d("argument_if", "$arguments")
setAdapter(doctorsArrayList)
}
else{
Log.d("argument_else", "$arguments")
val specialist = dieasesToSpecialist(dieasesLabel)
val list = filterSpecialist(specialist)
Log.d("argument_dL_length","${dieasesLabel.length}")
Log.d("argument_dieasesLabel", "$dieasesLabel")
Log.d("argument_specialist", "$specialist")
Log.d("argument_list", "$list")
setAdapter(list as ArrayList<doctors>)
}
Log.d("doctorList","${doctorsArrayList}")
}

override fun onCancelled(error: DatabaseError) {


Toast.makeText(requireContext(), "Internet Connection
Failed", Toast.LENGTH_SHORT).show()
}

})
}

private fun setAdapter(docArrayList: ArrayList<doctors>) {


110
binding.rvdoctorlist.layoutManager =
LinearLayoutManager(requireContext())
val doctorListAdapter = DoctorsListAdapter(requireContext(),
docArrayList)
binding.rvdoctorlist.adapter = doctorListAdapter
}

9. Appointment_Status_Fragment:
package com.example.healthdetectiveapp.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.healthdetectiveapp.R
import
com.example.healthdetectiveapp.adapter.AppointmentStatusAdapter
import
com.example.healthdetectiveapp.databinding.FragmentAppointment
StatusBinding

111
import com.example.healthdetectiveapp.model.PatientModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class Appointment_Status_Fragment : Fragment() {


private lateinit var binding:FragmentAppointmentStatusBinding
private lateinit var database: FirebaseDatabase
private var auth = FirebaseAuth.getInstance()
private var patientArrayList:ArrayList<PatientModel> =
ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding =
FragmentAppointmentStatusBinding.inflate(layoutInflater,container,
112
false)
fetchPatientData()
return binding.root
}

private fun fetchPatientData() {


var userId = auth.currentUser!!.uid
database = FirebaseDatabase.getInstance()
val patientListRef:DatabaseReference =
database.reference.child("PatientsList").child(userId)
patientListRef.addValueEventListener(object :
ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
Log.d("patient_snap","$snapshot")
if(snapshot.exists()){
patientArrayList.clear()
for (patientSnapshot in snapshot.children){
var eachValue =
patientSnapshot.getValue(PatientModel::class.java)
eachValue?.let {
patientArrayList.add(it)
}
}
setAdapter(patientArrayList)
}
else{
Toast.makeText(requireContext(), "You have No
113
Appointments", Toast.LENGTH_SHORT).show()
}
}

override fun onCancelled(error: DatabaseError) {


Toast.makeText(requireContext(), "${error.message}",
Toast.LENGTH_SHORT).show()
}

})
}

private fun setAdapter(patientsList: ArrayList<PatientModel>) {


binding.rvAppointmentStatus.layoutManager =
LinearLayoutManager(requireContext())
val appStatusAdapter =
AppointmentStatusAdapter(requireContext(),patientsList)
binding.rvAppointmentStatus.adapter = appStatusAdapter
}
}

10. BMICalculatorFragment:
package com.example.healthdetectiveapp.fragment

import android.content.Intent
import android.os.Bundle

114
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.healthdetectiveapp.BMI_Result_Activity
import
com.example.healthdetectiveapp.DieasesInformation_Activity
import
com.example.healthdetectiveapp.databinding.FragmentBmiCalculat
orBinding

class BMICalculatorFragment : Fragment() {


private lateinit var binding: FragmentBmiCalculatorBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding =
FragmentBmiCalculatorBinding.inflate(layoutInflater)
115
binding.feetpicker.minValue = 2
binding.feetpicker.maxValue = 8

binding.inchpicker.minValue = 0
binding.inchpicker.maxValue = 12

binding.weightpicker2.minValue = 15
binding.weightpicker2.maxValue = 250

binding.calculatebmi.setOnClickListener {
var ft = binding.feetpicker.value.toDouble()
var inc = binding.inchpicker.value.toDouble()
var totalinc = ft*12 + inc
var totalcm = totalinc*2.54
var totalm = totalcm/100
var weight = binding.weightpicker2.value.toDouble()
var bmi = weight/(totalm*totalm)
totalcm = String.format("%.1f",totalcm).toDouble()
bmi = String.format("%.1f",bmi).toDouble()
val bmiResultIntent =
Intent(requireContext(),BMI_Result_Activity::class.java)
bmiResultIntent.putExtra("bmiresult",bmi)
bmiResultIntent.putExtra("height",totalcm)
bmiResultIntent.putExtra("weight",weight)
startActivity(bmiResultIntent)
}
116
binding.whatbmi.setOnClickListener {
val whatbmiIntent = Intent(requireContext(),
DieasesInformation_Activity::class.java)
whatbmiIntent.putExtra("urlIndex",47)

whatbmiIntent.putExtra("requestCode","bmiResultInformation")
startActivity(whatbmiIntent)
}
return binding.root
}
}

11. UploadDataFragment:
package com.example.healthdetectiveapp.fragment

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
117
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.healthdetectiveapp.R
import
com.example.healthdetectiveapp.adapter.UploadFilesAdapter
import
com.example.healthdetectiveapp.databinding.FragmentUploadD
ataBinding
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import android.content.ContentResolver
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
import
com.example.healthdetectiveapp.adapter.PatientsRecordsAdapt
er
import
com.example.healthdetectiveapp.model.FileInformationModel
import

118
com.example.healthdetectiveapp.model.PatientsRecordsModel
import
com.google.android.material.bottomsheet.BottomSheetDialogFr
agment
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener

class UploadDataFragment : Fragment() {


private lateinit var binding: FragmentUploadDataBinding
private val PICK_FILE_REQUEST = 101
private lateinit var files:ArrayList<String>
private lateinit var status:ArrayList<String>
private lateinit var uploadFileAdapter:UploadFilesAdapter
private var fileName:String?=null
private lateinit var imageUri:Uri
val storageReference =
FirebaseStorage.getInstance().reference
val database = FirebaseDatabase.getInstance()
private val auth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
arguments?.let {

119
}
}

override fun onCreateView(


inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentUploadDataBinding.inflate(inflater,
container, false)
// Fetch Patients Records from Firebase
fetchPatientsRecords()
// Shrink Floating Button

binding.rvPatientsrecord.shrinkFabOnScroll(binding.btnFloat)

// Show uploadRecordFragment after clicking Floating


Button
binding.btnFloat.setOnClickListener{
val patientsRecordBS = uploadRecordFragment()

patientsRecordBS.show(parentFragmentManager,"RecordDialo
g")
}

120
return binding.root
}

override fun onCreateOptionsMenu(menu: Menu, inflater:


MenuInflater) {
inflater.inflate(R.menu.option_menu,menu)
super.onCreateOptionsMenu(menu, inflater)
}

override fun onOptionsItemSelected(item: MenuItem):


Boolean {
when(item.itemId){
R.id.fetch_data -> {
val fetchDataBottomSheetFragment =
FetchDataBottomSheetFragment()

fetchDataBottomSheetFragment.setRecyclerView(binding.rvPat
ientsrecord)

fetchDataBottomSheetFragment.show(parentFragmentManager,
"fetchdata")
}
}
return super.onOptionsItemSelected(item)
}

121
private fun fetchPatientsRecords() {
val userid = auth.currentUser!!.uid
val patientsRecordsRef =
database.reference.child("PatientsRecords")
val userIdRef = patientsRecordsRef.child(userid)
userIdRef.addValueEventListener(object :
ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
val
dateFilesList:MutableList<PatientsRecordsModel> =
mutableListOf()
for (dateSnapshot in snapshot.children){
Log.d("exam_dateSnapshot","${dateSnapshot}")
val date = dateSnapshot.key.toString()
Log.d("exam_date","${date}")
val filesList:MutableList<FileInformationModel> =
mutableListOf()
for (fileSnapshot in dateSnapshot.children){
Log.d("exam_fileSnapshot","${fileSnapshot}")
val eachFile =
fileSnapshot.getValue(FileInformationModel::class.java)
Log.d("exam_eachFile","${eachFile}")
eachFile?.let { filesList.add(it) }
}

122
val dateFiles =
PatientsRecordsModel(date,filesList)
dateFilesList.add(dateFiles)
}
setAdapter(dateFilesList)
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}

})
}

private fun setAdapter(dateFilesList:


MutableList<PatientsRecordsModel>) {
binding.rvPatientsrecord.layoutManager =
LinearLayoutManager(requireContext())
val patientsRecordAdapter =
PatientsRecordsAdapter(requireContext(),dateFilesList)
binding.rvPatientsrecord.adapter = patientsRecordAdapter
}

private fun customStatus(s1:String){


Toast.makeText(requireContext(), "${s1}",
Toast.LENGTH_SHORT).show()

123
}
}

12. ProfileFragment:
package com.example.healthdetectiveapp.fragment

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat.getSystemService
import com.bumptech.glide.Glide
import com.example.healthdetectiveapp.R
import
com.example.healthdetectiveapp.databinding.FragmentProfileBindin
g
import com.example.healthdetectiveapp.model.UserModel
import com.google.firebase.auth.FirebaseAuth

124
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import java.lang.StringBuilder
import java.security.SecureRandom

class ProfileFragment : Fragment() {


private lateinit var binding:FragmentProfileBinding
private val auth=FirebaseAuth.getInstance()
private val database=FirebaseDatabase.getInstance()
private lateinit var userRef:DatabaseReference
private var userimage: Uri? =null
private var gellaryImage = false
private val genderList = mutableListOf("Male", "Female",
"Other")
private lateinit var readId:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {

}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
125
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding =
FragmentProfileBinding.inflate(inflater,container,false)

var isVisible=false
val autocompleteAdapter = ArrayAdapter(requireContext(),
com.google.android.material.R.layout.support_simple_spinner_drop
down_item, genderList)
val autoComplete = binding.autocompleteProfile
autoComplete.setAdapter(autocompleteAdapter)

// Set User Data


setUserData()
// Disable EditText
binding.apply {
username.isEnabled = false
age.isEnabled = false
autocompleteProfile.isEnabled = false
address.isEnabled = false
phoneno.isEnabled = false
email.isEnabled = false
passward.isEnabled = false
readid.isEnabled = false
userimage.isEnabled = false
btnUpdateProfile.visibility = View.GONE
126
}
binding.btnEdit.setOnClickListener {
isVisible = !isVisible
binding.apply {
if (isVisible){
binding.btnUpdateProfile.visibility = View.VISIBLE
}
else{
binding.btnUpdateProfile.visibility = View.GONE
}
username.isEnabled = !username.isEnabled
age.isEnabled = !age.isEnabled
autocompleteProfile.isEnabled =
!autocompleteProfile.isEnabled
address.isEnabled = !address.isEnabled
phoneno.isEnabled = !phoneno.isEnabled
email.isEnabled = !email.isEnabled
passward.isEnabled = !passward.isEnabled
userimage.isEnabled = !userimage.isEnabled
readid.isEnabled = !readid.isEnabled
}
}
binding.userimage.setOnClickListener {
pickimage.launch("image/*")
}

// Set Sync Image Button


127
binding.imgbtnSyn.setOnClickListener {
readId = generatePassword(15)
binding.readid.setText(readId)
}

// Set Copy Image Button


binding.imgbtnCopy.setOnClickListener {
copyToClipboard()
Status("Text Copy to Clipboard")
}
binding.btnUpdateProfile.setOnClickListener {
binding.apply {
val name = username.text.toString().trim()
val age = age.text.toString().trim()
val gender = autocompleteProfile.text.toString().trim()
val address = address.text.toString().trim()
val phone = phoneno.text.toString().trim()
val email = email.text.toString().trim()
val passward = passward.text.toString().trim()
val readid = readid.text.toString().trim()

updateUserData(name,age,gender,address,phone,email,passward,rea
did)
}
}
return binding.root
}
128
private fun updateUserData(
name: String,
age: String,
gender: String,
address: String,
phone: String,
email: String,
passward: String,
readid:String
){
// Performing Validation
if (!name.isEmpty()){
binding.username.error = null
if (!phone.isEmpty()){
binding.phoneno.error = null
if (phone.matches("[1-9][0-9]{9}".toRegex())){
binding.phoneno.error = null
if (!email.isEmpty()){
binding.email.error = null
if (email.matches("^[a-zA-Z0-9._-]+@[a-z]+\\.+[a-
z]+".toRegex())){
binding.email.error = null
if (!passward.isEmpty()){
binding.passward.error = null
uploadData(name, age, gender, address, phone,
email, passward,readid)
129
}
else{
binding.passward.error ="Please Fill Passward"
}
}
else{
binding.email.error = "Please Fill Valid Email"
}
}
else{
binding.email.error ="Please Fill Email"
}
}
else{
binding.phoneno.error = "Please Fill Valid Phone
Number"
}
}
else{
binding.phoneno.error ="Please Fill Phone Number"
}
}
else{
binding.username.error ="Please Fill Username"
}
}

130
private fun uploadData(
name: String,
age: String,
gender: String,
address: String,
phone: String,
email: String,
passward: String,
readid: String
){
// Update Data
binding.progressBar.visibility = View.VISIBLE
val userId = auth.currentUser?.uid
userRef =
database.getReference("UsersProfile").child(userId!!)
val storageRef = FirebaseStorage.getInstance().reference
val userImageRef =
storageRef.child("users_images/${userId}.jpg")
if (userimage!=null){
if (gellaryImage){
val uploadImage = userImageRef.putFile(userimage!!)
uploadImage.addOnSuccessListener {
userImageRef.downloadUrl.addOnSuccessListener {
downloadUrl->

// User model
val userData1 = UserModel(userId, name, age,
131
gender, address, phone, email,
passward,readid,downloadUrl.toString())
userRef.setValue(userData1).addOnSuccessListener {
binding.progressBar.visibility = View.GONE
Status("Profile Successfully Update")
}
.addOnFailureListener {
binding.progressBar.visibility = View.GONE
Toast.makeText(requireContext(), "Profile Not
Updated", Toast.LENGTH_SHORT).show()
}
}
}
}
else{
// User model
val userData1 = UserModel(userId, name, age, gender,
address, phone, email, passward,readid,userimage.toString())
userRef.setValue(userData1).addOnSuccessListener {
binding.progressBar.visibility = View.GONE
Status("Profile Successfully Update")
}
.addOnFailureListener {
binding.progressBar.visibility = View.GONE
Toast.makeText(requireContext(), "Profile Not
Updated", Toast.LENGTH_SHORT).show()
}
132
}

}
else{
// User model
val userData2 = UserModel(userId, name, age, gender,
address, phone, email, passward,readid,userimage = null)
userRef.setValue(userData2).addOnSuccessListener {
binding.progressBar.visibility = View.GONE
Status("Profile Successfully Update")
}
.addOnFailureListener {
binding.progressBar.visibility = View.GONE
Toast.makeText(requireContext(), "Profile Not
Updated", Toast.LENGTH_SHORT).show()
}
}
}

private fun setUserData() {


val userId = auth.currentUser?.uid
if (userId!=null){
userRef =
database.getReference("UsersProfile").child(userId)
userRef.addValueEventListener(object :
ValueEventListener{
133
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
val user = snapshot.getValue(UserModel::class.java)
if (user!=null){
if (user.userimage!=null){
userimage = Uri.parse(user.userimage)

Glide.with(binding.userimage.context).load(Uri.parse(user.userimag
e)).into(binding.userimage)
}
else{

binding.userimage.setImageResource(R.drawable.account)
}
if (user.age!=null){
binding.age.setText(user.age)
}
if (user.gender!=null){

binding.autocompleteProfile.setText(user.gender)
}
if (user.address!=null){
binding.address.setText(user.address)
}
binding.username.setText(user.name)
binding.phoneno.setText(user.phone)
binding.email.setText(user.email)
134
binding.passward.setText(user.passward)
binding.readid.setText(user.readid)
}
}
}

override fun onCancelled(error: DatabaseError) {


TODO("Not yet implemented")
}

})
}
}
// Pick Image From Gallery
val pickimage =
registerForActivityResult(ActivityResultContracts.GetContent()){
uri->
if (uri!=null){
binding.userimage.setImageURI(uri)
userimage = uri
gellaryImage = true
}
}
fun Status(s1:String){
Toast.makeText(requireContext(), "${s1}",
Toast.LENGTH_SHORT).show()
}
135
fun generatePassword(length:Int):String{
val charSet = ('a'..'z')+('A'..'Z')+(0..9)+
listOf('!','@','#','$','%','^','&','*','?','+','-','/')
val secureRandom = SecureRandom()
val password = StringBuilder()
repeat(length,{
val charIndex = secureRandom.nextInt(charSet.size)
password.append(charSet[charIndex])
})
return password.toString()
}

fun copyToClipboard(){
val copy =
activity?.getSystemService(Context.CLIPBOARD_SERVICE) as
ClipboardManager
val clip = ClipData.newPlainText("readid",binding.readid.text)
copy.setPrimaryClip(clip)
}
}

136
Chapter 9
TESTING
Testing is a crucial phase in software development that involves evaluating the
functionality, performance, and usability of an application to ensure it meets the
specified requirements and performs as expected. In the context of the Health
Detective App, testing would have involved several key aspects:

1. Unit Testing: This type of testing focuses on individual components or modules of


the app to ensure they work correctly in isolation. In Android development, unit
tests are commonly written using frameworks like JUnit. For the Health Detective
App, unit tests would have been written to test functions and classes responsible
for disease prediction, doctor recommendation, BMI calculation, etc.
Table :Negative test case for phone number insertion

Function Input Expected Error


Name Output
Input 98977 Phonenu Length
phonenu mber ofphonenu
mber isinvalid mber
isnotequalt
o
10
Input 98977agv Phonenu Alphabets
phonenu mber are
mber isinvalid beingtake
n asinput
forphone
number

Table: Positive test case for phone number insertion

137
Function Input Expected Error
Name Output
Input 9897778988 Expected
phonenu output _
mber isseen

Table: Negative test case for email insertion

Function Input Expected Error


Name Output
Inputemail Sai1.in Email Emailisnotinaf
isinvali ormatgiven
d

Table: Positive test case for email insertion

Function Input Expected Error


Name Output
Inputemail aki123@gmail.com Expectedo
utputisseen _

2. Integration Testing: Integration testing verifies that different components of the


app work together correctly. For example, integration tests for the Health Detective
App would have checked that the UI components interact properly with the
Firebase database for storing patient data and with the TensorFlow Lite models for
disease detection.
3. UI Testing: User interface (UI) testing is used to ensure that the app's interface is
user-friendly and functions correctly across different devices and screen sizes.
Espresso is a popular framework for writing UI tests in Android. UI testing for the

138
Health Detective App would have involved checking the layout, navigation, and
user interactions in the app.
4. Performance Testing: Performance testing assesses how well the app performs
under various conditions, such as high user loads or limited network connectivity.
For the Health Detective App, performance testing would have involved measuring
the app's responsiveness, load times, and resource usage to ensure it meets
acceptable performance standards.
5. User Acceptance Testing (UAT): UAT involves testing the app with real users to
validate that it meets their requirements and expectations. This type of testing helps
ensure that the app is user-friendly and meets the needs of its target audience. UAT
for the Health Detective App would have involved gathering feedback from users
on the app's features, usability, and overall experience.

By conducting thorough testing, the development team can identify and fix issues
early in the development process, ensuring that the Health Detective App meets the
highest quality standards and provides a seamless user experience.

139
Chapter 10
Maintenance

1. Introduction

The maintenance phase of the Health Detective App involves ongoing activities to
ensure the app remains functional, up-to-date, and meets user needs. This phase
includes bug fixes, performance optimizations, feature enhancements, and updates
to comply with new Android versions and security standards.

2. Bug Fixing

Regular bug fixing is essential to address issues reported by users or identified


during testing. The development team will prioritize and fix bugs to ensure the
app's stability and usability. Bug fixes may involve code changes, updates to
libraries, or adjustments to server-side components.

3. Performance Optimization

Continuous monitoring and optimization of the app's performance are necessary to


ensure it runs smoothly on a variety of devices and network conditions. This may
involve optimizing code, reducing resource consumption, and improving loading
times and responsiveness.

4. Feature Enhancements

Based on user feedback and market trends, new features and functionalities may be
added to the app to improve user experience and provide additional value. Feature

140
enhancements should be carefully planned and tested to ensure they integrate
seamlessly with existing functionalities.

5. Compatibility Updates

As new versions of Android are released, the app may require updates to maintain
compatibility and take advantage of new features and improvements. Compatibility
updates may involve updating libraries, APIs, and SDKs used in the app, as well as
adapting the app's UI/UX to meet new design guidelines.

6. Security Updates

Regular security updates are critical to protect user data and ensure the app is not
vulnerable to security threats. This includes updating libraries and dependencies to
address known vulnerabilities, implementing secure coding practices, and ensuring
data encryption and secure communication protocols are in place.

7. User Support and Feedback

Providing user support and collecting feedback are essential for maintaining a
positive user experience. The development team should respond to user queries
and feedback promptly and use this information to prioritize future updates and
improvements.

8. Conclusion

The maintenance phase of the Health Detective App is crucial for ensuring the app
remains functional, secure, and competitive in the market. By regularly updating
and enhancing the app, the development team can continue to meet user needs and
provide a valuable tool for health management and healthcare access.

141
Chapter 11
System Security Measures
1. Data Encryption: Encrypt sensitive data such as patient information, user
credentials, and AI model data using strong encryption algorithms. Use HTTPS to
encrypt data transmitted between the app and the server to protect against
eavesdropping.
2. Secure Authentication: Implement secure authentication mechanisms, such as
OAuth or Firebase Authentication, to verify the identity of users accessing the app.
Use strong password policies and consider implementing multi-factor
authentication for added security.
3. Secure Data Storage: Use secure storage mechanisms, such as Firebase Realtime
Database or Firestore, which provide built-in security features like data validation
and access control. Avoid storing sensitive information in local storage or shared
preferences.
4. Secure Communication: Use secure communication protocols, such as TLS/SSL,
to encrypt data transmitted between the app and external servers. Implement
certificate pinning to protect against man-in-the-middle attacks.
5. Secure AI Model Deployment: Ensure that AI models used in the app are secure
and do not expose sensitive information. Use secure deployment practices and
consider obfuscating the model to protect it from reverse engineering.
6. User Permissions: Implement fine-grained permissions to control access to
sensitive features and data within the app. Only request permissions that are
necessary for the app's functionality and provide clear explanations to users about
why each permission is needed.

142
7. Secure Code Practices: Follow secure coding practices to reduce vulnerabilities
in the app's code. This includes input validation, avoiding hardcoded credentials,
and using secure libraries and frameworks.
8. Regular Security Audits: Conduct regular security audits and vulnerability
assessments to identify and mitigate potential security risks. This should include
testing the app for common security vulnerabilities such as SQL injection, cross-
site scripting (XSS), and insecure data storage.
9. User Education: Educate users about best practices for using the app securely,
such as avoiding sharing sensitive information and keeping their devices and apps
updated with the latest security patches.
10.Data Minimization: Minimize the collection and storage of sensitive data to
reduce the risk of data breaches. Only collect data that is necessary for the app's
functionality and ensure that it is stored securely.

Implementing these security measures will help protect the Health Detective App
from security threats and ensure the privacy and security of user data. Regularly
updating the app and its dependencies, monitoring for security vulnerabilities, and
responding promptly to security incidents are also essential for maintaining a
secure app environment.

143
Chapter 12
FUTURE SCOPE OF THE PROJECT
1. Enhanced Disease Detection: Improve the accuracy and capabilities of disease
detection by integrating more advanced AI models and machine learning
algorithms. Explore the use of additional medical imaging techniques and data
sources to enhance disease prediction.
2. Personalized Health Recommendations: Implement personalized health
recommendations based on user data and AI analysis. Provide users with
personalized advice on diet, exercise, and lifestyle changes to improve their overall
health.
3. Telemedicine Integration: Integrate telemedicine features to allow users to
consult with healthcare providers remotely. Provide video consultations, online
prescriptions, and virtual follow-ups to improve access to healthcare services.
4. Health Monitoring Devices Integration: Integrate with health monitoring devices
such as fitness trackers, smart watches, and medical sensors to provide real-time
health data. Use this data to enhance disease prediction and provide personalized
health recommendations.
5. Community Health Tracking: Implement features to allow users to track and
contribute to community health data. Provide insights and trends based on
aggregated data to help communities identify and address health issues.
6. Health Insurance Integration: Integrate with health insurance providers to
provide users with information on insurance coverage, claims, and benefits.
Provide tools to help users understand their insurance policies and make informed
decisions about their healthcare.

144
7. Advanced Data Analytics: Use advanced data analytics techniques to analyze
user data and provide actionable insights. Use machine learning and AI algorithms
to identify patterns and trends in health data and provide personalized
recommendations.
8. Enhanced User Experience: Continuously improve the app's user interface and
user experience based on user feedback and emerging design trends. Provide a
seamless and intuitive user experience across all platforms.
9. Global Expansion: Expand the app's reach to new markets and regions to provide
access to healthcare services to a wider audience. Localize the app to different
languages and cultures to make it more accessible and inclusive.
10.Research Collaboration: Collaborate with healthcare researchers and institutions
to contribute to ongoing research in the field of healthcare. Use the app's data and
insights to support research efforts and improve healthcare outcomes.

Implementing these future scope enhancements will help the Health Detective App
evolve into a comprehensive health management platform that provides
personalized, accessible, and proactive healthcare services to users.

145

You might also like