Mad Practicals Batch 241

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

4351604(MAD) BATCH: A1 226170316013

Diploma Engineering
Laboratory Manual
(Mobile Application Development)
(4351604)

[Diploma Information Technology Semester-5]


Enrolment No 226170316013
Name Bhagora Harshil S.
Branch Information technology
Academic Term 241
Institute GP, Ahmedabad

Directorate Of Technical Education


Gandhinagar - Gujarat

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

DTE’s Vision:
● To provide globally competitive technical education;
● Remove geographical imbalances and inconsistencies;
● Develop student friendly resources with a special focus on girls’ education and support to weaker
sections;

● Develop programs relevant to industry and create a vibrant pool of technical professionals.
DTE’s Mission:
• To provide a conducive learning environment to nurture learners.
• To act as a catalyst for achieving academic excellence by bringing stake holders on same platform.
• To be committed towards continuous improvement and enrichment of learners by a holistic
approach to education so as to enable them to be successful individuals and responsible citizens
of India.

Institute’s Vision:
• To be a leading technical institute that provides transformative education to learners for achieving
competency as per the needs of industry and society, thus contributing to nation building.

Institute’s Mission:

• To provide a conducive learning environment to nurture learners.


• To act as a catalyst for achieving academic excellence by bringing stake holders on same platform.
• To be committed towards continuous improvement and enrichment of learners by a holistic
approach to education so as to enable them to be successful individuals and responsible citizens
of India.

Department’s Vision:

• To acquire quality Education, Research and Development in the field of Information technology
meeting the global standards and comply with the ever-growing technology.

Department’s Mission:

• The graduates of our department will be efficient in technical and ethical responsibilities to
become globally recognized by pursuing opportunities for higher studies and real time problem
solving.
• Students will be competent by learning the principals of Information technology that can match
national and international standards.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Certificate

This is to certify that Mr. Bhagora Harshil S. Enrollment No.


226170316013 of 5th Semester of Diploma in Information Technology
(617) has satisfactorily completed the term work in course Mobile
Application Development (4351604) for the academic year: 2024
Term: 241

Signature of Course Faculty Head of the Department

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as well
as creative ability amongst students to solve real time problems by developing relevant competencies
in psychomotor domain. Keeping in view, GTU has designed competency focused outcome-based
curriculum -2021 (COGC-2021) for Diploma engineering programmes. In this more time is allotted to
practical work than theory. It shows importance of enhancement of skills amongst students and it pays
attention to utilize every second of time allotted for practical amongst Students, Instructors and
Lecturersto achieve relevant outcomes by performing rather than writing practice in study type. It is
essential foreffective implementation of competency focused outcome- based Green curriculum-2021.
Every practical has been keenly designed to serve as a tool to develop & enhance relevant industry
needed competency in each and every student. These psychomotor skills are very difficult to develop
through traditional chalk and board content delivery method in the classroom. Accordingly, this lab
manual hasbeen designed to focus on the industry defined relevant outcomes, rather than old practice
of conductingpractical to prove concept and theory.

By using this lab manual, students can read procedure one day in advance to actual performance
day of practical experiment which generates interest and also, they can have idea of judgement of
magnitude prior to performance. This in turn enhances predetermined outcomes amongst students.
Eachand every Experiment /Practical in this manual begins by competency, industry relevant skills,
course outcomes as well as practical outcomes which serve as a key role for doing the practical. The
students will also have a clear idea of safety and necessary precautions to be taken while performing
experiment.

This manual also provides guidelines to lecturers to facilitate student-centered lab activities
for each practical/experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve outcomes.
It also givesan idea that how students will be assessed by providing Rubrics.

Mobile applications have become an essential component of businesses across industries in


today's technology-driven world. There is a growing demand for skilled Mobile application developers
capable of developing innovative and robust applications that meet the needs of both businesses and
endusers. This course develops necessary skills in students, after learning this course; students will be
ableto develop user-friendly mobile applications.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Programme Outcomes (POs):

1. Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,


science and engineering fundamentals and engineering specialization to solve the
engineering problems.

2. Problem analysis: Identify and analyse well-defined engineering problems using


codified standard methods.

3. Design/ development of solutions: Design solutions for engineering well-defined


technical problems and assist with the design of systems components or processes to
meet specified needs.

4. Engineering Tools, Experimentation and Testing: Apply modern engineering


tools and appropriate technique to conduct standard tests and measurements.

5. Engineering practices for society, sustainability and environment: Apply


appropriate technology in context of society, sustainability, environment and ethical
practices.

6. Project Management: Use engineering management principles individually, as a


team member or a leader to manage projects and effectively communicate about well-
defined engineering activities.

7. Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical Outcome - Course Outcome matrix


Course Outcomes (COs):
a. CO1: Understand the fundamentals of Android app development.
b. CO2: Design Android user interfaces using various layouts, views, and widgets.
c. CO3: Connect an Android app to SQLite, Firebase, and MySQL databases.
d. CO4: Understand the working of APIs in Android app development.
e. CO5: Develop basic mobile applications using the Flutter framework.
f. CO6: Understand the steps involved in publishing an Android app to the Google Play Store.
CO1 CO2 CO3 CO4 CO5 CO6
S. No. Practical Outcome/Title of
experiment

1 Install Android Studio, set up the


Android development environment, √ - - - - -
and create a simple "Hello World"
app.
2 Develop a simple app that √ - - - - -
demonstrates the activity lifecycle.
Develop a simple calculator app that
3 takes user input and performs basic
arithmetic operations, such as √ - - - - -
addition, subtraction, multiplication,
and division.
4 Develop an Android application that
uses LinearLayout to arrange UI - √ - - - -
components vertically or horizontally.
5 Develop an Android application that
uses RelativeLayout to arrange UI - √ - - - -
components relative to each other.
Develop an Android application that
6
uses ScrollView to display a long list - √ - - - -
of items.
7 Develop an Android application that
uses ListView and Custom Adapter to - √ - - - -
display a list of images with text.
8 Develop an Android application that
uses the Navigation Drawer to display - √ - - - -
a side menu.
Develop an Android application that
9
uses the bottom navigation bar to - √ - - - -
switch between different tabs.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

10 Develop an Android application that


uses an Intent to pass data between - √ - - - -
different activities.
11 Develop an Android application that
uses Services to perform background - √ - - - -
tasks.
12 Develop an Android application that
uses Broadcast Receivers to receive - √ - - - -
and handle system-level broadcasts.
13 Develop an Android application that
uses Content Providers to share data
- √ - - - -
between different apps and
components.
14
Develop an Android application that
uses Content Providers to read
- √ - - - -
system-level data, such as contacts
and calendar events.
15
Create an application that creates a
database using SQLiteOpenHelper
- - √ - - -
Class and performs Insert and Read
from the SQLite database.
16
Create an application to Update and
Delete data from the SQLite database - - √ - - -
using SQLiteOpenHelper class.
17
Perform Firebase Integration to your
Android application and store the data - - √ - - -
in the Firebase Database.
18
Create an application to retrieve data
from the Firebase Database and - - √ - - -
display it in the RecyclerView.
19
Connect an Android application to the
MySQL database using PHP, and - - √ - - -
insert the data in the database table.
20
Perform insertion of data to MySQL
database using PHP from an Android - - √ - - -
application.
21
Perform reading of the data from the
MySQL database using PHP in the
- - √ - - -
JSON format and display on the
screen of an Android application.
22
Integrate Google maps API to your
Android application and display your - - - √ - -
current location in the app.
Integrate Google maps API to your
23 - - - √ - -
Android application and find the

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

distance of any nearby location from


your current location and display it.
24
Develop an application which
performs Login using the Google - - - √ - -
account of the user.
25
Install Flutter SDK, configure the
development environment and display
- - - - √ -
“Hello World” in the centre of the
screen.
26
Develop a Flutter app to get two
numbers from the user and display
- - - - √ -
addition on the screen after clicking a
button.
27
Develop a Flutter app for Login using
static data. If the User ID and
Password are correct then clicking a
- - - - √ -
login button should open a new
screen showing Username at the
center of the new screen.
28
Demonstrate publishing an Android
app on the Google Play Store - - - - - √
following the policies and guidelines.

Industry Relevant Skills

The following industry relevant skills are expected to be developed in the students by
performance of experiments of this course.

Develop user-friendly Mobile applications, design intuitive user interfaces, understand


and implement various app components, effectively debug and troubleshoot issues, adapt
to emerging technologies and continuously enhance their skills to meet the demands of the
industry.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Guidelines to Course Faculty


1. Course faculty should demonstrate experiment with all necessary implementation strategies
described in curriculum.
2. Course faculty should explain industrial relevance before starting of each experiment.
3. Course faculty should Involve & give opportunity to all students for hands on experience.
4. Course faculty should ensure mentioned skills are developed in the students by asking.
5. Utilise 2 hrs of lab hours effectively and ensure completion of write up with quiz also.
6. Encourage peer to peer learning by doing same experiment through fast learners.

Instructions for Students


1. Organize the work in the group and make record of all observations.
2. Students shall develop maintenance skill as expected by industries.
3. Student shall attempt to develop related hand-on skills and build confidence.
4. Student shall develop the habits of evolving more ideas, innovations, skills etc.
5. Student shall refer technical magazines and data books.
6. Student has to take print out of the code and attach it with every practical.
7. Student should develop habit to submit the practical on date and time.
8. Student should well prepare while submitting write-up of exercise.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Continuous Assessment Sheet


Enrolment No: 226170316013
Name: Bhagora Harshil S. Term: 241

Sr Practical Outcome/Title of Experiment Marks


Page Date Sign
no (25)

Install Android Studio, set up the Android


1 development environment, and create a simple
"Hello World" app.
2 Develop a simple app that demonstrates the activity
lifecycle.
Develop a simple calculator app that takes user input
and performs basic arithmetic operations like
3
addition, subtraction, multiplication, and division.
Develop an Android application that uses
4 LinearLayout to arrange UI components vertically
or horizontally.
Develop an Android application that uses
5 RelativeLayout to arrange UI components relative to
each other.
6
Develop an Android application that uses
ScrollView to display a long list of items.
Develop an Android application that uses ListView
7 and Custom Adapter to display a list of images with
text.
8 Develop an Android application that uses the
Navigation Drawer to display a side menu.
Develop an Android application that uses the bottom
9 navigation bar to switch between different tabs.

10 Develop an Android application that uses an Intent


to pass data between different activities.
11 Develop an Android application that uses Services
to perform background tasks.
Develop an Android application that uses Broadcast
12 Receivers to receive and handle system-level
broadcasts.
Develop an Android application that uses Content
13 Providers to share data between different apps and
components.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Develop an Android application that uses Content
14 Providers to read system-level data, such as contacts
and calendar events.
Create an application that creates a database using
15 SQLiteOpenHelper Class and performs Insert and
Read from the SQLite database.
Create an application to Update and Delete data
16 from the SQLite database using SQLiteOpenHelper
class.
Perform Firebase Integration to your Android
17 application and store the data in the Firebase
Database.
Create an application to retrieve data from the
18 Firebase Database and display it in the
RecyclerView.
Connect an Android application to the MySQL
19 database using PHP, and insert the data in the
database table.

20 Perform insertion of data to MySQL database using


PHP from an Android application.
Perform reading of the data from the MySQL
21 database using PHP in the JSON format and display
on the screen of an Android application.
Integrate Google maps API to your Android
22 application and display your current location in the
app.
Integrate Google maps API to your Android
23 application and find the distance of any nearby
location from your current location and display it.
24 Develop an application which performs Login using
the Google account of the user.
Install Flutter SDK, configure the development
25 environment and display “Hello World” in the
centre of the screen.
Develop a Flutter app to get two numbers from the
26 user and display addition on the screen after clicking
a button.
Develop a Flutter app for Login using static data. If
27 the User ID and Password are correct then clicking
a login button should open a new screen showing
Username at the center of the new screen.
Demonstrate publishing an Android app on the
28 Google Play Store following the policies and
guidelines.
Total

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical:1

Install Android Studio, set up the Android development environment,and create a simple "Hello World"
app.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 2
Develop a simple app that demonstrates the activity lifecycle.

File-1 : Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
pp="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

File-2 : MainActivity.java
package com.example.lifecycle2;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle; import
android.widget.Toast; import
android.content.Context;
public class MainActivity extends AppCompatActivity {
Context mContext=this;
protected void onCreate(Bundle savedInstanceState)

{super.onCreate(savedInstanceState
setContentView(R.layout.activity_main);
Toast.makeText(mContext, "Create Method Called", Toast.LENGTH_SHORT).show(); }
protected void onStart()

{ super.onStart();

Toast.makeText(mContext,"Start Method Called", Toast.LENGTH_SHORT).show(); } protected


void onResume()
{ super.onResume();

Toast.makeText(mContext,"Resume Method Called", Toast.LENGTH_SHORT).show(); }

protected void onPause()


{ super.onPause();

Toast.makeText(mContext,"Resume Method Called", Toast.LENGTH_SHORT).show(); } protected


void onStop()
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
{
super.onStop();

Toast.makeText(mContext,"Stop Method Called", Toast.LENGTH_SHORT).show(); } protected


void onDestroy()
{

super.onDestroy();

Toast.makeText(mContext,"Destroy Method Called", Toast.LENGTH_SHORT).show(); }

Outp

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 3
Develop a simple calculator app that takes user input and performs basic arithmetic
operations, such as addition, subtraction, multiplication, and division.

File- 1 : Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="First Number"
android:inputType="numberDecimal"
tools:ignore="TouchTargetSizeCheck,SpeakableTextPresentCheck" />
<EditText
android:id="@+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:ems="10" android:hint="Second
Number"
android:inputType="numberDecimal"
tools:ignore="SpeakableTextPresentCheck,TouchTargetSizeCheck" />
<Button
android:id="@+id/btnadd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Add" />

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button
android:id="@+id/btnsubs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"

android:layout_marginRight="20dp"
android:text="Subtract" />

<Button
android:id="@+id/btndiv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Divide" />

<Button
android:id="@+id/btnmult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Multiply" />
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="25dp"
android:layout_marginRight="20dp"
android:text="" />

</LinearLayout>

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

File - 2 : MainAcitivity.java

package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity; import


android.os.Bundle;
import android.view.View; import
android.widget.Toast; import
android.widget.Button; import
android.widget.EditText; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity


{
Button btnadd,btnsubs,btnmult,btndiv;
EditText txt1,txt2;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnadd=findViewById(R.id.btnadd);
btnsubs=findViewById(R.id.btnsubs);
btndiv=findViewById(R.id.btndiv);
btnmult=findViewById(R.id.btnmult);

txt1=findViewById(R.id.txt1);
txt2=findViewById(R.id.txt2);

result=findViewById(R.id.result);
btnadd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// Checking Input First Is Blank Or Not if


(txt1.getText().toString().equals("")) {
// Showing Toast (Message)
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
}
else if (txt2.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter Number",

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Toast.LENGTH_SHORT).show();
}

// Both Inputs Are Not Blank , Starting Calculation else


{
float a, b, c;
a = Float.parseFloat(txt1.getText().toString()); b
= Float.parseFloat(txt2.getText().toString());
c = a + b; // Using Third Variable To Store Output Value
result.setText("The Addition Result Is " + c);

}
}
});

btnsubs.setOnClickListener(new View.OnClickListener()
{@Override
public void onClick(View view) {
// Checking Input First Is Blank Or Not if
(txt1.getText().toString().equals("")) {
// Showing Toast (Message)
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
} else if (txt2.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();

// Both Inputs Are Not Blank , Starting Calculation else


{
float a, b, c;
a = Float.parseFloat(txt1.getText().toString()); b
= Float.parseFloat(txt2.getText().toString());
c = a- b; // Using Third Variable To Store Output Value
result.setText("The Subtraction Result Is " + c);

}
}
});
btnmult.setOnClickListener(new View.OnClickListener()
{@Override
public void onClick(View view) {
// Checking Input First Is Blank Or Not if
(txt1.getText().toString().equals("")) {

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

// Showing Toast (Message)


Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
} else if (txt2.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
// Both Inputs Are Not Blank , Starting Calculation else
{
float a, b, c;
a = Float.parseFloat(txt1.getText().toString()); b
= Float.parseFloat(txt2.getText().toString());
c = a*b; // Using Third Variable To Store Output Value
result.setText("The Multiplication Result Is " + c);

}
}
});

btndiv.setOnClickListener(new View.OnClickListener()
{@Override
public void onClick(View view) {
// Checking Input First Is Blank Or Not if
(txt1.getText().toString().equals("")) {
// Showing Toast (Message)
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
} else if (txt2.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
}

// Both Inputs Are Not Blank , Starting Calculation else


{

float a, b, c;
a = Float.parseFloat(txt1.getText().toString()); b
= Float.parseFloat(txt2.getText().toString());
c = a/b; // Using Third Variable To Store Output Value
result.setText("The Division Result Is " + c);

}
}
});

}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 4
Develop an Android application that uses LinearLayout to arrange UI components vertically or
horizontally.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:text="Button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button2"
android:text="Button2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button3"
android:text="Button3"
android:layout_gravity="center"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

MainAcivity.java
package com.example.linearlayout;

import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public


class MainActivity extends AppCompatActivity {@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);}}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Outpu

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 5
Develop an Android application that uses RelativeLayout to arrange UI
components relative to each other.
File - 1 : Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This the example of Relative Layout!"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:layout_alignParentLeft="true"
android:layout_below="@id/txt1"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:layout_alignParentRight=true"
android:layout_below="@id/txt1"/
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3"
android:layout_centerHorizontal="true"
android:layout_below="@id/button2"/>
</RelativeLayout>

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:layout_alignParentRight="true"
android:layout_below="@id/txt1"/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3"
android:layout_centerHorizontal="true"
android:layout_below="@id/button2"/>
</RelativeLayout>

MainActivity.java
package com.example.relativelayout;

import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public


class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 6
Develop an Android application that uses ScrollView to display a long list of items.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.scrollview3.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Vertical ScrollView example"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<ScrollView android:layout_marginTop="30dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button android:layout_width="fill_parent"

android:layout_height="wrap_content"
android:text="Button 2" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 5" />

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 6" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 7" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 8" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 9" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 10" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 11" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Button 12" />

<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 13" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="Button 14" />


<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 15" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 16" />

</LinearLayout>
</ScrollView>
</RelativeLayout>

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 7
Develop an Android application that uses ListView and Custom Adapter to display a
list of images with text.

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:ems="10">
<requestFocus />
</EditText>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText1"
android:layout_alignLeft="@id/editText1"
android:layout_marginLeft="68dp"
android:layout_marginTop="-171dp"
android:onClick="ShowSecondActivity"
android:text="Click for SecondActivity" />
</RelativeLayout>

MainActivity.java
package com.example.intent;
import androidx.appcompat.app.AppCompatActivity; import
android.view.View;
import android.widget.EditText;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
{@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public void ShowSecondActivity(View v)

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
{EditText edittext1=(EditText) findViewById(R.id.editText1);
String name=edittext1.getText().toString();
Intent i = new Intent(this,activity_second.class);
i.putExtra("name",name);
startActivity(i);

}
}
public class MainActivity extends AppCompatActivity
{@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
public void ShowSecondActivity(View v)
{EditText edittext1=(EditText) findViewById(R.id.editText1);
String name=edittext1.getText().toString();
Intent i = new Intent(this,activity_second.class);
i.putExtra("name",name);
startActivity(i);
}}
activity_second.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView

android:id="@+id/txt2"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:text="This is the second activity" />

</RelativeLayout>

activity_second.java package
com.example.intent;
import androidx.appcompat.app.AppCompatActivity; import
android.content.Intent;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.os.Bundle; import
android.widget.TextView;

public class activity_second extends AppCompatActivity


{@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i =getIntent();
String name= i.getStringExtra("name"); TextView
t1= (TextView) findViewById(R.id.txt2);

t1.setText(name);
}
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 8
Develop an Android application that uses the Navigation Drawer to display a side
menu.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@+id/ll"
tools:context=".MainActivity"
android:orientation="vertical">
</LinearLayout>
File -2 : MainActivity.java
package com.example.pr7;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem; import
android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
{LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ll
= findViewById(R.id.ll);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu, menu); return
true; }

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
switch (item.getItemId())
{ case R.id.red: ll.setBackgroundColor(Color.RED);
break;
case R.id.green:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
ll.setBackgroundColor(Color.GREEN);
break;
case R.id.blue:
ll.setBackgroundColor(Color.BLUE);
break;
}
return true;
}}
File -3 : menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/green" android:title="Green" />
<item android:id="@+id/red" android:title="Red" />
<item android:id="@+id/blue" android:title="Blue" />
</menu>

Output

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 9
Develop an Android application that uses the bottom navigation bar to switch between different
tabs.

File - 1 : Mainactivity.java
package com.example.backgroundservices;
import androidx.appcompat.app.AppCompatActivity; import
android.os.Bundle;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// declaring objects of Button class
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// to the object start
start = (Button) findViewById( R.id.startButton );
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// declaring listeners for the
// buttons to make them respond
// correctly according to the process
start.setOnClickListener( this );
stop.setOnClickListener( this );}
public void onClick(View view) {
// process to be performed
// if start button is clicked
if(view == start){
// starting the service
startService(new Intent( this, NewService.class ) ); }
// process to be performed
// if stop button is clicked
else if (view == stop){
// stopping the service
stopService(new Intent( this, NewService.class ) );
}
}}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

File - 2 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#168BC34A"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:text="heading"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp" android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold" /

<Button
android:id="@+id/startButton"
android:text="StartButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp" android:layout_marginTop="10dp"
android:layout_marginEnd="20dp" android:layout_marginBottom="20dp"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textStyle="bold"
/>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button
android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:text="stopButton"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textStyle="bold" />

</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

File - 3 : NewService.java
package com.example.backgroundservices;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings; import
androidx.annotation.Nullable;
public class NewService extends Service {
// declaring object of MediaPlayer
private MediaPlayer player;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); player.setLooping( true );
// starting the process
player.start();
// returns the status of the program
return START_STICKY;
}
@Override
public void onDestroy()
{super.onDestroy();
player.stop();
}
@Nullable @Override
public IBinder onBind(Intent intent)
{return null;}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
File - 4 : Manifest.java
<service
android:name=".NewService"
android:enabled="true"
android:exported="true" >
</service>
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 10
Develop an Android application that uses an Intent to pass data between different
activities.

File - 1 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="broadcastIntent"
android:text="Broadcast Intent" />
</RelativeLayout>

File - 2 MainActivity.java
package com.example.broadcastreceiver;
import androidx.appcompat.app.AppCompatActivity; import
android.view.View;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void broadcastIntent(View v)
{
Intent intent=new Intent();
intent.setAction("CustomBroadcastIntent");
sendBroadcast(intent);
}

File - 3 : MyReceiver.java
package com.example.broadcastreceiver;
import android.content.BroadcastReceiver;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver
{@Override
public void onReceive(Context context,Intent intent)
{
Toast.makeText(context, "Its a broadcast Intent", Toast.LENGTH_LONG).show();
}
}

(4) Manifest.java
<receiver android:name="com.example.broadcastreceiver.MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="CustomBroadcastIntent" />
</intent-filter>
</receiver>

Output

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical No.11
Develop an Android application that uses Services to perform background tasks.

Activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText android:id="@+id/etNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" android:hint="Enter a
number" />
<Button android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Factorial" />
<TextView android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: " android:textSize="18sp" />
</LinearLayout>
<Button android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Factorial"
android:onClick="calculateFactorial" />
androidmanifest.xml:
<service
android:name=".FactorialService"
android:enabled="true"
android:exported="false" />
MainActivity.java
public class MainActivity extends AppCompatActivity { private
EditText etNumber;
private TextView tvResult;
private FactorialService factorialService;
@Override
protected void onCreate(Bundle savedInstanceState) {

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNumber = findViewById(R.id.etNumber); tvResult =
findViewById(R.id.tvResult);
factorialService = new FactorialService();}
public void calculateFactorial(View view) { String input =
etNumber.getText().toString(); if (!input.isEmpty()) {
int number = Integer.parseInt(input);
int result = factorialService.calculateFactorial(number);
tvResult.setText("Result: " + result);
}}}
FactorialService.java
public class FactorialService extends Service {
@Override
public IBinder onBind(Intent intent) { return
null;
}
public int calculateFactorial(int n) { if (n ==
0 || n == 1) {
return 1;
} else { return n * calculateFactorial(n - 1);
}}}
Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 12
Develop an Android application that uses Broadcast Receivers to receive and handle system-
level broadcasts.

Activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView android:id="@+id/tvStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" />
</LinearLayout>

AndroidManifest.xml:
<receiver android:name=".PowerConnectionReceiver"
android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
SMSReceiver.java
import android.content.BroadcastReceiver; import
android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class PowerConnectionReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) { String action
= intent.getAction();
if (action != null) {

if (action.equals(Intent.ACTION_POWER_CONNECTED)) { Toast.makeText(context, "Power connected!",


Toast.LENGTH_SHORT).show();
} else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) { Toast.makeText(context, "Power
disconnected!", Toast.LENGTH_SHORT).show();
}
}
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
MainActivity.java:
import android.os.Bundle; import
android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { private
TextView tvStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = findViewById(R.id.tvStatus);
}
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 13
Develop an Android application that uses Content Providers to share data between different
apps and components.

Strings.xml
<resources>
<string name="app_name">Content_Provider_In_Android</string>
<string name="hintText">Enter User Name</string>
<string name="heading">Content Provider In Android</string>
<string name="insertButtontext">Insert Data</string>
<string name="loadButtonText">Load Data</string>
</resources>

MyContentProvider.java
package com.example.contentprovidersinandroid; import
android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues; import
android.content.Context; import
android.content.UriMatcher; import
android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteException; import
android.database.sqlite.SQLiteOpenHelper; import
android.database.sqlite.SQLiteQueryBuilder; import
android.net.Uri;
import java.util.HashMap;

public class MyContentProvider extends ContentProvider { public


MyContentProvider() {
}

// defining authority so that other application can access it


static final String PROVIDER_NAME = "com.demo.user.provider";

// defining content URI


static final String URL = "content://" + PROVIDER_NAME + "/users";
static final Uri CONTENT_URI = Uri.parse(URL);

static final String id = "id";


static final String name = "name";

static final int uriCode = 1;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
static final UriMatcher uriMatcher;
private static HashMap<String, String> values; static {
// to match the content URI
// every time user access table under content provider uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// to access whole table uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
// to access a particular row
// of the table
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) { case uriCode:
return "vnd.android.cursor.dir/users"; default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
// creating the database @Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) { case uriCode:
qb.setProjectionMap(values);

break; default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") { sortOrder id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri); return c;
}
// adding data to the database @Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values); if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) { case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs); break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null); return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0;
switch (uriMatcher.match(uri)) { case uriCode:

count = db.delete(TABLE_NAME, selection, selectionArgs); break;


default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null); return count;
}
// creating object of database
// to perform query
private SQLiteDatabase db;
// declaring name of the database
static final String DATABASE_NAME = "UserDB";
// declaring table name of the database
static final String TABLE_NAME = "Users";
// declaring version of the database
static final int DATABASE_VERSION = 1;
// sql query to create the table
static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL);";
// creating a database
private static class DatabaseHelper extends SQLiteOpenHelper {
// defining a constructor DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// creating a table in the database @Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// sql query to drop a table
// having similar name
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#168BC34A" tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.13" tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:fontFamily="@font/roboto"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark" android:textSize="36sp"
android:textStyle="bold" />
<EditText
android:id="@+id/textName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="40dp"

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:fontFamily="@font/roboto"
android:hint="@string/hintText" />
<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickAddDetails"
android:text="@string/insertButtontext"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickShowDetails"
android:text="@string/loadButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />

<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false" android:ems="10"
android:fontFamily="@font/roboto"
android:textColor="@android:color/holo_green_dark" android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@drawable/banner" />

MainActivity.java:
package com.example.contentprovidersinandroid; import
androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues; import
android.content.Context; import
android.database.Cursor; import
android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager; import
android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWin
dow(getCurrentFocus().getWindowToken(), 0); return true;
}
public void onClickAddDetails(View view) {
// class to add values in the database ContentValues values = new
ContentValues();
// fetching text from user values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());
// inserting into database through content URI getContentResolver().insert(MyContentProvider.CONTENT_URI,
values);
// displaying a toast message Toast.makeText(getBaseContext(), "New Record Inserted",
Toast.LENGTH_LONG).show();}
public void onClickShowDetails(View view) {
// inserting complete table details in this text field TextView resultView= (TextView)
findViewById(R.id.res);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
// creating a cursor object of the
// content URI Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null);
// iteration of the cursor
// to print whole table
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();

while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext(
}}}
}else { Text(strBuild)
resultView.se
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.14
Develop an Android application that uses Content Providers to read system- level data, such as
contacts and calendar events.

AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
ActivityMain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button android:id="@+id/btnGetContacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts" />
<Button android:id="@+id/btnGetEvents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Calendar Events" />
</LinearLayout>
MainActivity.java:
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CONTACTS_PERMISSION = 1; private
static final int REQUEST_CALENDAR_PERMISSION = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
setContentView(R.layout.activity_main);
Button btnGetContacts = findViewById(R.id.btnGetContacts); Button
btnGetEvents = findViewById(R.id.btnGetEvents);
btnGetContacts.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
checkContactsPermission();
}
});
btnGetEvents.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
checkCalendarPermission();
}
});
}
private void checkContactsPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) ==
PackageManager.PERMISSION_GRANTED) {
getContacts();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS},
REQUEST_CONTACTS_PERMISSION);
}
}
private void checkCalendarPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) ==
PackageManager.PERMISSION_GRANTED) {
getCalendarEvents();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR},
REQUEST_CALENDAR_PERMISSION);
}
}
private void getContacts() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor
= getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) { String
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_N AME));
String phoneNumber =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Handle the retrieved contact data here (e.g., display in a list)
}
cursor.close();
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
private void getCalendarEvents() {
Uri uri = CalendarContract.Events.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE)); String location =
cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION));
// Handle the retrieved calendar event data here (e.g., display in a list)
}
cursor.close();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode
== REQUEST_CONTACTS_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getContacts();
} else {
Toast.makeText(this, "Contacts permission denied", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_CALENDAR_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getCalendarEvents();
} else {
Toast.makeText(this, "Calendar permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.15
Create an application that creates a database using SQLiteOpenHelper Class and performs
Insert and Read from the SQLite database.

Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button android:id="@+id/btnInsertData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Data" />
<Button android:id="@+id/btnReadData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Data" />
</LinearLayout>
DatabaseHelper.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper { private static
final String DATABASE_NAME = "my_database"; private static final String
TABLE_NAME = "my_table";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
public DatabaseHelper(Context context) { super(context,
DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME +
" (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + "
TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
onCreate(db);
}
public long insertData(String name) { SQLiteDatabase db =
this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
return db.insert(TABLE_NAME, null, contentValues);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
}
MainActivity.java:
import android.database.Cursor;
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);

Button btnInsertData = findViewById(R.id.btnInsertData); Button


btnReadData = findViewById(R.id.btnReadData);

btnInsertData.setOnClickListener(new View.OnClickListener() { @Override


public void onClick(View v) {
long result = databaseHelper.insertData("John Doe"); if (result != -1) {
Toast.makeText(MainActivity.this, "Data inserted
successfully",

Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error inserting data",
Toast.LENGTH_SHORT).show();
}
}
});
btnReadData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Cursor cursor = databaseHelper.getData(); StringBuilder
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
data = new StringBuilder(); while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
data.append("ID: ").append(id).append(", Name: ").append(name).append("\n");

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.16
Create an application to Update and Delete data from the SQLite database using
SQLiteOpenHelper class.

Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity"
<Button android:id="@+id/btnUpdateData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Data" />
<Button android:id="@+id/btnDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
</LinearLayout>
DatabaseHelper.java:
import android.content.ContentValues;
import android.content.Context; import
android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper { private static
final String DATABASE_NAME = "my_database"; private static final String
TABLE_NAME = "my_table";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
public DatabaseHelper(Context context) { super(context,
DATABASE_NAME, null, 1);

}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME +
" (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + "
TEXT)";
db.execSQL(createTableQuery); }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
onCreate(db); }
public long insertData(String name) { SQLiteDatabase db =
this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
return db.insert(TABLE_NAME, null, contentValues);}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}}
MainActivity.java:
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); databaseHelper
= new DatabaseHelper(this);
Button btnUpdateData = findViewById(R.id.btnUpdateData); Button
btnDeleteData = findViewById(R.id.btnDeleteData);
btnUpdateData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
int updatedRows = databaseHelper.updateData(1, "Jane Doe"); if (updatedRows >
0) {
Toast.makeText(MainActivity.this, "Data updated successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error updating data",
Toast.LENGTH_SHORT).show();
} } } );
btnDeleteData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
int deletedRows = databaseHelper.deleteData(1); if (deletedRows
> 0) {
Toast.makeText(MainActivity.this, "Data deleted successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error deleting data",
Toast.LENGTH_SHORT).show();
} } } ); } }

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 17
Perform Firebase Integration to your Android application and store the data in the Firebase
Database.

Set Up Firebase Project:


• Go to the Firebase Console.
• Click "Add Project" and follow the setup instructions.
Add Your App to Firebase:
• After creating your project, click "Add app" and select the Android platform.
• Follow the setup instructions, which typically involve adding your app's package name and a debug signing
• certificate SHA-1 key.
• Download the google-services.json file and place it in your app module's root directory.
Add Firebase SDK to Your Project:
• In your app-level build.gradle file, add the Firebase SDK dependencies:
• // Add these lines to your app-level build.gradle file
• implementation 'com.google.firebase:firebase-database:20.0.0' // Use the latest version
• implementation 'com.google.firebase:firebase-auth:21.0.0' // If you want to use Firebase
Authentication
Initialize Firebase:
• In your Application class or your main activity's onCreate method, initialize Firebase:

Firebase Authentication (Optional):


• If you want to implement user authentication and secure your database, you can also integrate Firebase
• Authentication by following the Firebase Authentication documentation.

Firebase Rules (Security):


• Configure your Firebase Realtime Database rules to secure your data. By default, Firebase rules allow read
and write access to your data for anyone. Update the rules according to your app's requirements.
Testing and Error Handling:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
• Ensure that your Firebase integration works as expected and handle any errors that may occur
during data operations.
Step 1: Create a Firebase Project
1. Go to https://console.firebase.google.com/u/0/
2. Log in to Firebase with your Google account if are not already logged in.
3. Click on create the project.

Step 2: Give a name to the project


1. Write the name.
2. Click on continue.

Step 3: Disable Google Analytics(There is no need to do this for this project)


1. Click on the toggle button.
2. Click Continue.

Firebase will create a project for you and open it for


you. Step 4: Create a Realtime Database:
1. Go to Develop Option on Sidebar.
2. Click on Database.
3. Scroll down in a new screen and click on Create Database on Realtime Database.
4. Start in Test mode (In order to get read and write access to the database).

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Firebase will create a project for you and open it for you.
Step 4: Create a Realtime Database:
5. Go to Develop Option on Sidebar.
6. Click on Database.
7. Scroll down in a new screen and click on Create Database on Realtime Database.
8. Select Start in Test mode (In order to get read and write access to the database).
Click enable

Firebase will create a project for you and open it for you.
Step 4: Create a Realtime Database:
9. Go to Develop Option on Sidebar.
10. Click on Database.
11. Scroll down in a new screen and click on Create Database on Realtime Database.
12. Select Start in Test mode (In order to get read and write access to the database).
Click enable

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical 18
Create an application to retrieve data from the Firebase Database and display it in the
RecyclerView

Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout
>
List_items.xm
l:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/itemText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" android:textStyle="bold"
/>
</LinearLayout>
RecyclerView.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
androidx.recyclerview.widget.LinearLayoutManager; import
androidx.recyclerview.widget.RecyclerView;
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;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
private ArrayList<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize RecyclerView
recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new
LinearLayoutManager(this));
// Initialize data ArrayList
data = new ArrayList<>();
// Initialize Firebase
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("items");

// Read from the database myRef.addValueEventListener(new


ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
data.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) { String
value = snapshot.getValue(String.class); data.add(value);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// Handle error
}
})
;
// Initialize Adapter
adapter = new MyAdapter(this, data);
recyclerView.setAdapter(adapter);
}
}
MainActivity.java:
import android.content.Context;
import
android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.widget.TextView;
import
androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private ArrayList<String> data;
public MyAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
}
@NonN
ull
@Overri
de
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View
view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); return new
ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String item = data.get(position);
holder.itemText.setText(item);
}
@Override
public int getItemCount()
{ return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder
TextView itemText;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemText = itemView.findViewById(R.id.itemText);
}
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical No.19:
Connect an Android application to the MySQL database using PHP.

Set Up Your MySQL Database:


Create a MySQL database if you haven't already.
Note down the database name, username, and password for connecting to the database.
Create a PHP Script for Insertion:
Create a PHP script on your server that will handle the insertion of data into the database. Here's a
simple example (save this script as insert_data.php on your server):
Connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "mad_prcs";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
getData.php:
<?php
include 'connect.php';
$sql = "SELECT * FROM your_table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
} else{
echo "0 results";
}
$conn->close();
?>
HTTP_GET:
URL url = new URL("http://your_server_address/get_data.php"); HttpURLConnection
urlConnection = (HttpURLConnection) url.openConnection(); try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Now, 'result.toString()' will contain the JSON data from your MySQL database
} finally { urlConnection.disconnect();
}
JSONObject:
// Assuming 'result' contains the JSON data try {
JSONArray jsonArray = new JSONArray(result.toString()); for (int i =
0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name"); // Assuming there's a field 'name' in your database table
// Process the data as needed
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical No.20
Perform insertion of data to MySQL database using PHP from an Android application.

Courses.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745";
$conn = new mysqli($servername, $username, $password, $dbname);
$response = array();
if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){
$courseName = $_POST['courseName'];
$courseDuration = $_POST['courseDuration'];
$courseDescription = $_POST['courseDescription'];
$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`,
`courseDescription`) VALUES (?,?,?)");
$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription); if($stmt-
>execute() == TRUE){
$response['error'] = false;
$response['message'] = "course created successfully!";
} else{
$response['error'] = true;
$response['message'] = "failed\n ".$conn->error;
}
}
else
{
$response['error'] = true;
$response['message'] = "Insufficient parameters";
}
// at last we are printing our response which we get. echo
json_encode($response);
?>

Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
tools:context=".MainActivity">
<!--Edit text for getting course Name-->
<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Name"
android:importantForAutofill="no"
android:inputType="text" />
<!--Edittext for getting course Duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Duration in min"
android:importantForAutofill="no"
android:inputType="time" />
<!--Edittext for getting course Description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginStart="10dp"
android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course
Description" android:importantForAutofill="no" android:inputType="text" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnSubmitCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit Course Details"
android:textAllCaps="false" />
</LinearLayout
> MainActivity.java:
import android.os.Bundle; import
android.text.TextUtils; import
android.util.Log; import
android.view.View; import
android.widget.Button;
import android.widget.EditText;

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity; import
com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating variable for button private
Button submitCourseBtn;
// creating a strings for storing our values from edittext fields. private String
courseName, courseDuration, courseDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt =
findViewById(R.id.idEdtCourseDescription); courseDurationEdt =
findViewById(R.id.idEdtCourseDuration); submitCourseBtn =
findViewById(R.id.idBtnSubmitCourse); submitCourseBtn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
// getting data from edittext fields.
courseName = courseNameEdt.getText().toString(); courseDescription =
courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString();
courseDuration);
// validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) {
courseNameEdt.setError("Please enter Course Name");
} else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course
Description");
} else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration");
} else {
// calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription,

}}};}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
}
private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
// url to post our data
String url = "http://localhost/courseApp/addCourses.php";
// creating a new variable for our request queue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// on below line we are calling a string
// request method to post the data to our API
// in this we are calling a post method.
StringRequest request = new StringRequest(Request.Method.POST, url, new
com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) { Log.e("TAG", "RESPONSE IS "
+ response); try {
JSONObject jsonObject = new JSONObject(response);
// on below line we are displaying a success toast message. Toast.makeText(MainActivity.this,
jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) { e.printStackTrace();}
// and setting data to edit text as empty courseNameEdt.setText("");
courseDescriptionEdt.setText("");
courseDurationEdt.setText("");}
}, new com.android.volley.Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
@Override
protected Map<String, String> getParams() {
// below line we are creating a map for storing
// our values in key and value pair.
Map<String, String> params = new HashMap<String, String>();
// on below line we are passing our
// key and value pair to our parameters. params.put("courseName", courseName);
params.put("courseDuration", courseDuration); params.put("courseDescription",
courseDescription);
// at last we are returning our params. return params;}
};
// below line is to make
// a json object request.
queue.add(request);
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 21:
Perform reading of the data from the MySQL database using PHP in the JSON format
and display on the screen of an Android application.

readCourses.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745";
$conn = new mysqli($servername, $username, $password, $dbname);
$response = array();
if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){
$courseName = $_POST['courseName'];
$courseDuration = $_POST['courseDuration'];
$courseDescription = $_POST['courseDescription'];
$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`,
`courseDescription`) VALUES (?,?,?)");
$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription); if($stmt-
>execute() == TRUE){
$response['error'] = false;
$response['message'] = "course created successfully!";
} else{
$response['error'] = true;
$response['message'] = "failed\n ".$conn->error;}
}
else
{
$response['error'] = true;
$response['message'] = "Insufficient parameters"}
// at last we are printing our response which we get.

echo json_encode($response);
?>
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text for getting course Name-->
<EditText

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Name"
android:importantForAutofill="no"
android:inputType="text" />
<!--Edittext for getting course Duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Duration in min"
android:importantForAutofill="no"
android:inputType="time" />
<!--Edittext for getting course Description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"

android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Description"
android:importantForAutofill="no"
android:inputType="text" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnSubmitCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit Course Details"
android:textAllCaps="false" />
</LinearLayout>

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
MainActivity.java:
import android.os.Bundle; import
android.text.TextUtils; import
android.util.Log; import
android.view.View; import
android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity; import
com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating variable for button private
Button submitCourseBtn;
// creating a strings for storing our values from edittext fields. private String
courseName, courseDuration, courseDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt =
findViewById(R.id.idEdtCourseDescription);

courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn =


findViewById(R.id.idBtnSubmitCourse); submitCourseBtn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
// getting data from edittext fields.
courseName = courseNameEdt.getText().toString(); courseDescription =
courseDescriptionEdt.getText().toString(); courseDuration =
courseDurationEdt.getText().toString();
// validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) {
courseNameEdt.setError("Please enter Course Name");
} else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Description");
} else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration");
} else {
// calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription,
}
}
};
}
private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
// url to post our data
String url = "http://localhost/courseApp/addCourses.php";
// creating a new variable for our request queue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// on below line we are calling a string
// request method to post the data to our API
// in this we are calling a post method.
StringRequest request = new StringRequest(Request.Method.POST, url, new
com.android.volley.Response.Listener<String>() {
@Override

public void onResponse(String response) { Log.e("TAG", "RESPONSE IS " +


response); try {
JSONObject jsonObject = new JSONObject(response);
// on below line we are displaying a success toast message. Toast.makeText(MainActivity.this,
jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) { e.printStackTrace();
}
// and setting data to edit text as empty courseNameEdt.setText("");
courseDescriptionEdt.setText(""); courseDurationEdt.setText("");
}
}, new com.android.volley.Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
@Override
public String getBodyContentType() {
// as we are passing data in the form of url encoded
// so we are passing the content type below
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
protected Map<String, String> getParams() {
// below line we are creating a map for storing
// our values in key and value pair.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Map<String, String> params = new HashMap<String, String>();
// on below line we are passing our
// key and value pair to our parameters. params.put("courseName", courseName);
params.put("courseDuration", courseDuration); params.put("courseDescription",
courseDescription);

// at last we are returning our params. return params;


}
};
// below line is to make
// a json object request.
queue.add(request);
}
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.22:
Integrate Google maps API to your Android application and display your current
location in the app.

AndroidManifest.xml:
<meta-data
android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"
/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY" android:value="ENTER API_KEY " />
manifest.xml:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
Activity_Main.xml:
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java:
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import androidx.appcompat.app.AppCompatActivity;
public class MapsMarkerActivity extends AppCompatActivity implements OnMapReadyCallback {
// onCreate method is called when the activity is first created @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.ActivityMain);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// This method is called when the map is ready to be used. @Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
// and move the map's camera to the same location.
LatLng myPos = new LatLng(Location.getLatitude(), Location.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPos));
}
}

OUTPUT :

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.23
Integrate Google maps API to your Android application and find the distance of any nearby
location from your current location and display it.
AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Activity_Main.xml:
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent" android:layout_height="match_parent" />
MainActivity.java:
import android.Manifest;

import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import
com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback; import
com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {


private GoogleMap googleMap;

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;


@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override

public void onMapReady(GoogleMap map) {


googleMap = map;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
} else {

ActivityCompat.requestPermissions(this,

new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);


}

}
@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]


grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); if
(requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{ googleMap.setMyLocationEnabled(true);

}}}}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.24
Develop an application which performs Login using the Google account of the user.
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#ffffff">
<!--Imageview for Google logo image-->

<ImageView

android:id="@+id/imgGLogo"
android:layout_width="160dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp" android:padding="4dp"
android:src="@drawable/google_logo" />
<!--Textview to display a message "Sign In"-->

<TextView
android:id="@+id/txtSignIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgGLogo"
android:layout_centerHorizontal="true"
android:padding="6dp
android:text="Sign In"
android:textColor="#000000"
android:textSize="24sp"
android:textStyle="bold" />

<TextView

android:id="@+id/txtUseAccount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtSignIn"
android:layout_centerHorizontal="true"
android:padding="4dp" android:text="with your Google
account" android:textColor="#000000" />
<!--EditText for user name or email address-->

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<EditText

android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/txtUseAccount"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp" android:hint="Username or
Email" android:inputType="textEmailAddress"
android:maxLines="1"
android:padding="10dp"
android:textColor="#000000" /

<TextView

android:id="@+id/txtForgotEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etEmail"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:padding="10dp" android:text="Forgot
Email?" android:textColor="#2196f3"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginBottom="15dp"
android:padding="10dp" android:text="Create Account"
android:textColor="#2196f3" android:textStyle="bold" />

<!-- Login Button for Google Sign In-->

<Button

android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="15dp"

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:backgroundTint="#2196f3" android:elevation="6dp"
android:padding="10dp" android:text="Next"
android:textColor="@android:color/white"
android:textSize="14sp" android:textStyle="bold" />
</RelativeLayout>
Colors.xml:

<?xml version="1.0" encoding="utf-8"?>


<resources>

<color name="purple_200">#ffffff</color>

<color name="purple_500">#2196f3</color>
<color name="purple_700">#2196f3</color>

<color name="teal_200">#2196f3</color>
<color name="teal_700">#2196f3</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>

</resources>
MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
+Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.25
Install Flutter SDK, configure the development environment and display “Hello World” in the
centre of the screen.

Code :-

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Practical No.26
Develop a Flutter app to get two numbers from the user and display addition on the
screen after clicking a button.

import 'package:flutter/material.dart'; void


main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) { final
appTitle = 'Add Two Numbers';

return MaterialApp(
title: appTitle, home:
Scaffold( appBar:
AppBar(
title: Text(appTitle),
),
body: AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
@override
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = new TextEditingController();
TextEditingController num2controller = new TextEditingController(); String
result = "0";
@override
Widget build(BuildContext context) {
return Container(
child: Column( children:
<Widget>[ Row(
children: <Widget>[
Text("Number 1:"), new
Flexible(
child: new TextField(
keyboardType: TextInputType.number, controller:
num1controller,
),
),
],

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
),
Row(
children: <Widget>[
Text("Number 2:"), new
Flexible(
child: new TextField(
keyboardType: TextInputType.number, controller:
num2controller,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children:
<Widget>[
RaisedButton( child:
Text("Add"), onPressed :
() {
setState(() {
int sum = int.parse(num1controller.text) + int.parse(num2controller.text); result =
sum.toString();
});
},
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children:
<Widget>[
Text("Result:", style:
TextStyle( fontSize:
30,
),),
Text(result, style:
TextStyle( fontSize:
30,
),
),
],
),
],
),
);
}
}

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.27
Develop a Flutter app for Login using static data. If the User ID and Password are correct then
clicking a login button should open a new screen showing Username at the center of the new
screen.

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:form_field_validator/form_field_validator.dart';
class Login extends StatefulWidget { const
Login({Key? key}) : super(key: key);
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
Map userData = {};
final _formkey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'), centerTitle:
true,
),
body: SingleChildScrollView( child:
Column( children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 30.0), child: Center(
child: Container( width: 120,
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40), border: Border.all(color: Colors.blueGrey)),
child: Image.asset('assets/logo.png'),
),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 15), child: Padding(
padding: const EdgeInsets.all(12.0), child: Form(
key: _formkey, child: Column(
crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0), child: TextFormField(
validator: MultiValidator([ RequiredValidator(
errorText: 'Enter email address'), EmailValidator(

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
errorText:
'Please correct email filled'),
]),
decoration: InputDecoration( hintText: 'Email', labelText: 'Email', prefixIcon: Icon(
Icons.email,
//color: Colors.green,
Padding(),
errorStyle: TextStyle(fontSize: 18.0), border: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red), borderRadius: BorderRadius.all(
Radius.circular(9.0)))))),
padding: const EdgeInsets.all(12.0), child: TextFormField(
validator: MultiValidator([ RequiredValidator(
errorText: 'Please enter Password'), MinLengthValidator(8,
errorText:
'Password must be atlist 8 digit'), PatternValidator(r'(?=.?[#!@$%^&-])',
special character')
]),
errorText:
'Password must be atlist one
decoration: InputDecoration( hintText: 'Password', labelText: 'Password', prefixIcon: Icon( Icons.key,
color: Colors.green,
),
errorStyle: TextStyle(fontSize: 18.0), border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red), borderRadius:
BorderRadius.all(Radius.circular(9.0))),
),
),
),
Container(
margin: EdgeInsets.fromLTRB(180, 0, 0, 0), child: Text('Forget Password!'),
),
Padding(
padding: const EdgeInsets.all(28.0), child: Container(
child: RaisedButton(
child: Text( 'Login',
style: TextStyle(
color: Colors.white, fontSize: 22),
),
onPressed: () {
if (_formkey.currentState!.validate()) { print('form submiitted');
}
},
shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30)),
color: Colors.blue,
),

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
width: MediaQuery.of(context).size.width, height: 50,
),
),
Center(
child: Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 0), child: Center(
child: Text(
'Or Sign In Using!', style: TextStyle(
fontSize: 18, color: Colors.black),
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children: [
Padding(
padding: EdgeInsets.fromLTRB(0, 20, 0, 0), child: Row(
children: [
Container(
height: 40,
width: 40,
child: Image.asset( 'assets/social.jpg', fit: BoxFit.cover,
)),
Container( height: 70,
width: 70,
child: Image.asset(
'assets/vishal.png', fit: BoxFit.cover,
),
),
Container( height: 40,
width: 40,
child: Image.asset(
'assets/google.png', fit: BoxFit.cover,
),
),
],
),
),
],
),
Center(
child: Container(
padding: EdgeInsets.only(top: 50), child: Text(
'SIGN UP!',
style: TextStyle( fontSize: 20,
fontWeight: FontWeight.w700, color: Colors.lightBlue,

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
),
)),
),
],
),
),
);
}
}

Output:

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.28
Demonstrate publishing an Android app on the Google Play Store following the policies and
guidelines.

Step 1: Create a Google Developer Account


- Create a Google Developer account to publish your Android app on the Play Market.
- Use an existing Google account or create a new one.
- The registration process includes signing the Google Play Developer distribution agreement, adding personal
information, and paying a one-time registration fee of $25.
- Approval from Google usually takes up to two days.

Step 2: Add a Merchant Account


- Create a Google Merchant Account if you plan to sell paid apps or in-app purchases.
- The developer account gets automatically linked to the Merchant profile.
Step 3: Prepare The Documents
- Start preparing the End User License Agreement (EULA) and Privacy Policy in advance.
- EULA defines what users can and can't do with the app, licensing fees, intellectual property
information, etc.
- Include Privacy Policy with information about data collection, technical details, legal information,
subscription terms, and more.
Step 4: Study Google Developer Policies
- Ensure that your app aligns with Google Developer Policies to avoid rejection, blocking, or deletion.
- Policies cover restricted content, app store listing, impersonation, monetization, privacy, security,
deception regulation, and more.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Step 5: Technical Requirements
- Check unique Bundle ID (package name) for your app and ensure it's suitable for the app's lifetime.
- Sign the app release with a signing certificate to identify the author.
- Verify app size, file format, and consider using app bundles.
- Learn more about app file technical requirements in the Developer Documents.
Step 6: Creating The App On The Google Console
- Create a new app in your Developer Account by specifying the default language and adding a brief app
description.
Step 7: Store Listing
- Prepare the Store listing, including product description, screenshots, icon, feature graphic, promo video,
tags, localization, application type, and categorization.
- Provide contact details and link to your Privacy Policy.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013

Step 8: Content Rating


- Complete the rating questionnaire accurately to avoid being marked as an Unrated App.
- Click "Save Questionnaire," "Calculate Rating," and "Apply Rating" to confirm your app's rating.
Step 9: Pricing The Application
- Specify whether your app is free or paid.
- Select the countries where your app will be available.
- Choose device compatibility, age suitability, and indicate if the app contains ads.

Step 10: Upload APK & Send It For Review


- Upload your Android app file in the App Releases section.
- Consider starting with Alpha or Beta versions for pre-release testing.
- Follow the steps to upload the APK, add release information, and send your app for review.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
- The review process typically takes up to 2 days, but Google mentions it could take longer.

Basic Policy and Requirements for Publishing:


- Restricted Content: Google bans apps with sexually explicit, violent, threatening, bullying, or illegal content.
Real-money and gambling games must comply with local regulations.
- Intellectual Property: Unauthorized use of copyright content or trademarks is not allowed.
- Impersonation: Apps shouldn't mislead users by impersonating other companies, brands, or
developers.
- Privacy and Security: Misuse of user data, unrelated permission requests, and malicious software are
prohibited.
- Monetization and Advertising: Disruptive and deceptive ads are not allowed, and they should be served only
within the app.
- Spam and Minimum Functionality: Apps must provide value and avoid being low-quality, crashing, or serving
solely for advertising purposes.
- Apps for Families and Children: Apps for families and children must comply with specific requirements
for content, monetization, ads, functionality, and data.

Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Assessment-Rubrics { MAD-4351604}

Performance Program Coding User Interface Testing & Submission


Total
Indicators Correctness technology (UI) Design Debugging in Time

Weightage in % 25 25 20 15 15 100
Marks 0-5 0-5 0-5 0-5 0-5 25
Sr No. Practical No.

1 Practical 1
2 Practical 2
3 Practical 3
4 Practical 4
5 Practical 5
6 Practical 6
7 Practical 7
8 Practical 8
9 Practical 9
10 Practical 10
11 Practical 11
12 Practical 12
13 Practical 13
14 Practical 14
15 Practical 15
16 Practical 16
17 Practical 17
18 Practical 18
19 Practical 19
20 Practical 20
21 Practical 21
22 Practical 22
23 Practical 23
24 Practical 24
25 Practical 25
26 Practical 26
27 Practical 27
28 Practical 28

Faculty Sign

Harshil Bhagora

You might also like