Mad Practicals Himanshu

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 126

4351604(MAD)

DiplomaEngineering
Laboratory Manual
(MobileApplicationDevelopment)(43516
04)
[Diploma InformationTechnology Semester-5]
Enrolment No 226170316109
Name | Prajapati Himanshu K.
Branch Information technology
AcademicTerm 241
Institute GP, Ahmedabad

Directorate Of Technical
EducationGandhinagar-Gujarat
4351604(MAD)

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.
4351604(MAD)
• Students will be competent by learning the principals of Information technology that can match
national and international standards.
Certificate

This is to certify that Mr. Prajapati Himanshu Kalpesh Bhai


Enrollment No. 226170316109 of 5thSemester 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

Preface
Theprimaryaimofanylaboratory/Practical/fieldworkisenhancementofrequiredskillsaswellascre
ativeabilityamongststudentstosolverealtimeproblemsbydevelopingrelevantcompetenciesinpsychomo
tordomain.Keepinginview,GTUhasdesignedcompetencyfocusedoutcome-basedcurriculum -2021
(COGC-2021) for Diploma engineering programmes. In this more time is allotted topractical work than
theory. It shows importance of enhancement of skills amongst students and it
paysattentiontoutilizeeverysecondoftimeallottedforpracticalamongstStudents,InstructorsandLecturer
4351604(MAD)
sto achieve relevant outcomes by performing rather than writing practice in study type. It is essential
foreffectiveimplementationofcompetencyfocusedoutcome-basedGreencurriculum-
2021.Everypractical has been keenly designed to serve as a tool to develop & enhance relevant
industry neededcompetency in each and every student. These psychomotor skills are very difficult to
develop throughtraditional chalk and board content delivery method in the classroom. Accordingly,
this lab manual
hasbeendesignedtofocusontheindustrydefinedrelevantoutcomes,ratherthanoldpracticeofconducting
practicalto prove conceptand theory.

Byusingthislabmanual,studentscanreadprocedureonedayinadvancetoactualperformanceday
of practical experiment which generates interest and also, they can have idea of judgement
ofmagnitudepriortoperformance.Thisinturnenhancespredeterminedoutcomesamongststudents.Each
and every Experiment /Practical in this manual begins by competency, industry relevant skills,
courseoutcomes as well as practical outcomes which serve as a key role for doing the practical. The
studentswillalsohaveaclearideaofsafetyandnecessaryprecautionstobetakenwhileperformingexperime
nt.

This manual also provides guidelines to lecturers to facilitate student-centered lab activities
foreach practical/experiment by arranging and managing necessary resources in order that the
studentsfollowtheprocedureswithrequiredsafetyandnecessaryprecautionstoachieveoutcomes.Italsogi
vesanidea thathowstudents willbeassessed by providingRubrics.

Mobile applications have become an essential component of businesses across industries


intoday's technology-driven world. There is a growing demand for skilled Mobile application
developerscapableofdevelopinginnovativeandrobustapplicationsthatmeettheneedsofbothbusinesses
andendusers. This course develops necessary skills in students, after learning this course; students will
be abletodevelop user-friendlymobileapplications.

ProgrammeOutcomes(POs):

1. Basic and Discipline specific knowledge: Apply knowledge of


basic
mathematics,scienceandengineeringfundamentalsandengineeringspecializationtosolv
et heengineeringproblems.
4351604(MAD)
2. Problem analysis: Identify and analyse well-defined engineering problems
usingcodifiedstandard methods.

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


definedtechnical problems and assist with the design of systems components or
processes tomeetspecified needs.

4. EngineeringTools,ExperimentationandTesting:Applymodernengineering
toolsandappropriatetechniqueto conductstandardtestsandmeasurements.

5. Engineeringpracticesforsociety,sustainabilityandenvironment:Applyappropriate
technology in context of society, sustainability, environment and ethicalpractices.

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


ateam member or a leader to manage projects and effectively communicate about
well- definedengineering activities.

7. Life-
longlearning:Abilitytoanalyzeindividualneedsandengageinupdatinginthecontextoftech
nological changesin field of engineering.

PracticalOutcome-CourseOutcomematrix

CourseOutcomes(COs):
a. CO1:Understandthefundamentalsof Androidappdevelopment.
b. CO2:DesignAndroiduserinterfacesusingvariouslayouts,views,andwidgets.
c. CO3:Connect anAndroidapptoSQLite, Firebase,andMySQLdatabases.

d. CO4:Understandtheworking of APIsin Androidappdevelopment.


e. CO5:DevelopbasicmobileapplicationsusingtheFlutterframework.
f. CO6:UnderstandthestepsinvolvedinpublishinganAndroid appto theGooglePlayStore.
S.No. CO1 CO2 CO3 CO4 CO5 CO6
Practical Outcome/Title ofexperiment

1 Install Android Studio, set up √


theAndroiddevelopmentenvironme - - - - -
nt,and create a simple "Hello
World"app.
4351604(MAD)
2 Develop a simple app √ - - - - -
thatdemonstratestheactivitylifecyc le.

3 Developasimplecalculatorappthattak
es user input and performs

basicarithmeticoperations, suchas - - - - -
addition, subtraction,
multiplication,anddivision.
4 Develop an Android application
thatuses LinearLayout to arrange - √ - - - -
UIcomponentsverticallyorhorizontall
y.
5 Develop an Android application
thatuses RelativeLayout to arrange - √ - - - -
UIcomponentsrelativetoeachother.
6 Develop an Android application
thatusesScrollViewtodisplayalonglist - √ - - - -
ofitems.
7 Develop an Android application
thatusesListViewandCustomAdaptert - √ - - - -
odisplayalist ofimages with text.
8 Develop an Android application
thatuses the Navigation Drawer to - √ - - - -
displayaside menu.
9 Develop an Android application
thatuses the bottom navigation bar - √ - - - -
toswitchbetween differenttabs.

10 Develop an Android application


thatuses an Intent to pass data - √ - - - -
betweendifferentactivities.
11 Develop an Android application
thatuses Services to perform - √ - - - -
backgroundtasks.
12 Develop an Android application
thatuses Broadcast Receivers to - √ - - - -
receiveandhandlesystem-
levelbroadcasts.
13 Develop an Android application - √ - - - -
thatuses Content Providers to share
databetweendifferent apps and
components.
4351604(MAD)
14 Develop an Android application - √ - - - -
thatuses Content Providers to
readsystem-level data, such as
contactsandcalendar events.
15 Create an application that creates - - √ - - -
adatabase using
SQLiteOpenHelperClass and
performs Insert and
ReadfromtheSQLitedatabase.
16 Create an application to Update - - - -
andDeletedatafromtheSQLitedatabas √ -
e usingSQLiteOpenHelperclass.
17 Perform Firebase Integration to - - - -
yourAndroidapplicationandstoretheda √ -
taintheFirebaseDatabase.
18 Createanapplicationtoretrievedatafro - - - -
m the Firebase Database anddisplayit √ -
intheRecyclerView.
19 Connect an Android application to - - - -
theMySQL database using PHP, √ -
andinsertthedatain thedatabasetable.
20 Perform insertion of data to - - - -
MySQLdatabaseusingPHPfromanAn √ -
droid application.
21 PerformreadingofthedatafromtheMy - - √ - - -
SQL database using PHP in
theJSON format and display on
thescreenofan Androidapplication.
22 Integrate Google maps API to - - - -
yourAndroid application and display √ -
yourcurrentlocation in theapp.
IntegrateGooglemapsAPItoyourAn
23 - - - √ - -
droidapplicationandfindthe
distanceofanynearbylocationfromy
ourcurrentlocationanddisplayit.
24 Developan
applicationwhichperforms Login
using the Googleaccountof - - - √ - -
theuser.
25 Install Flutter SDK, configure
thedevelopment environment and
4351604(MAD)
display“Hello World” in the centre - - - - √ -
of thescreen.
26 Develop a Flutter app to get
twonumbers from the user and - - - √ -
displayadditiononthescreenaftercli -
ckinga button.

27 Develop a Flutter app for Login


usingstatic data. If the User ID
andPassword are correct then
clicking aloginbuttonshouldopen - - - - √ -
anewscreen showing Username at
thecenterof thenew screen.
28 Demonstrate publishing an
Androidapp on the Google Play
Storefollowingthepoliciesandguide - - - - - √
lines.

IndustryRelevantSkills

Thefollowingindustryrelevantskillsareexpectedtobedevelopedinthestudentsbyperformanceo
fexperiments ofthis course.

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


implement various app components, effectively debug and troubleshoot issues,
adapttoemergingtechnologiesandcontinuouslyenhancetheirskillstomeetthedemandsofth
eindustry.
4351604(MAD)
GuidelinestoCourseFaculty
1. Course faculty should demonstrate experiment with all necessary implementation strategiesdescribedin
curriculum.
2. Coursefacultyshouldexplainindustrial relevancebeforestartingofeachexperiment.
3. CoursefacultyshouldInvolve& giveopportunity toallstudentsforhandsonexperience.
4. Coursefacultyshouldensure mentionedskillsaredeveloped inthestudentsbyasking.
5. Utilise2hrsoflabhourseffectivelyandensurecompletionofwriteupwithquizalso.
6. Encouragepeertopeerlearningbydoingsameexperiment throughfastlearners.

InstructionsforStudents
1. Organizetheworkinthegroupandmakerecordofallobservations.
2. Studentsshall developmaintenanceskillasexpectedbyindustries.
3. Student shall attemptto developrelatedhand-on skillsandbuildconfidence.
4. Studentshalldevelopthehabitsofevolvingmoreideas,innovations,skillsetc.
5. Studentshall refertechnical magazinesanddatabooks.
6. Student hasto takeprintout ofthecodeandattachitwithevery practical.
7. Studentshoulddevelophabitto submitthepracticalondateandtime.
8. Studentshouldwell preparewhilesubmittingwrite-upofexercise.
4351604(MAD)
4351604(MAD)
ContinuousAssessmentSheet
EnrolmentNo:226170316109

Sr Name: Prajapati Himanshu Kalpesh Bhai


PracticalOutcome/TitleofExperiment Term: 241 Date Marks Sign
no Page
(25)
Install Android Studio, set up the
1 Androiddevelopmentenvironment,andcreat
easimple
"HelloWorld"app.
Develop a simple app that demonstrates the
2
activitylifecycle.
Developasimplecalculatorappthattakesuserinputand
3 performsbasicarithmeticoperationslikeaddition,subt
raction,multiplication,anddivision.
DevelopanAndroidapplicationthatusesLinearLayout
4 to arrange UI components verticallyorhorizontally.

Develop an Android application


5 that
usesRelativeLayouttoarrangeUIcompone
ntsrelativeto eachother.
6 Develop an Android application
that usesScrollViewto display along
list of
items.
7 Develop an Android application
that uses
ListViewandCustomAdaptertodisplayalistofimages
withtext.
8 DevelopanAndroidapplicationthatusestheNavigatio
nDrawer to display aside menu.
DevelopanAndroidapplicationthatusesthebottomnavigati
9 onbarto switchbetween differenttabs.
DevelopanAndroidapplicationthatusesanIntenttopas
10
s data between differentactivities.
DevelopanAndroidapplicationthatusesServicestoper
11
form background tasks.
DevelopanAndroidapplicationthatusesBroadcastRe
12 ceiverstoreceiveandhandlesystem-levelbroadcasts.

Develop an Android application that uses


13 ContentProviders to share data between different
apps andcomponents.
DevelopanAndroidapplicationthatusesContent
14 Providerstoreadsystem-
leveldata,suchascontactsandcalendar events.
Create an application that creates a database
15 usingSQLiteOpenHelper Class and performs Insert
4351604(MAD)
andReadfrom theSQLitedatabase.
Create an application to Update and Delete
16 datafrom the SQLite database using
SQLiteOpenHelperclass.
PerformFirebaseIntegrationtoyourAndroidapplicati
17 onandstorethedataintheFirebaseDatabase.

Createanapplicationtoretrievedatafromthe
18 Firebase Database and display
it in theRecyclerView.
ConnectanAndroidapplicationtotheMySQLdatabas
19 eusingPHP,andinsertthedatainthedatabasetable.

Perform insertion of data to MySQL database


20
usingPHPfrom an Android application.
PerformreadingofthedatafromtheMySQLdatabaseus
21 ingPHPintheJSONformatanddisplayonthe screen
ofanAndroid application.
IntegrateGooglemapsAPItoyourAndroidapplication
22 and display your current location in theapp.

IntegrateGooglemapsAPItoyourAndroidapplication
23 andfindthedistanceofanynearbylocationfromyourcu
rrentlocation anddisplayit.
DevelopanapplicationwhichperformsLoginusingthe
24
Google account of theuser.
InstallFlutterSDK,configurethedevelopmentenviron
25 mentanddisplay“HelloWorld”inthecentreof
thescreen.
DevelopaFlutterapptogettwonumbersfromthe
26 useranddisplayadditiononthescreenafterclickingabu
tton.
Develop a Flutter app for Login using static data.
27 Ifthe User ID and Password are correct then
clickinga login button should open a new screen
showingUsername at thecenterof thenewscreen.
DemonstratepublishinganAndroidappontheGoogleP
28 layStorefollowingthepoliciesandguidelines.

Total
4351604(MAD)
Practical:1

Install Android Studio, set up theAndroiddevelopmentenvironment,and create a simple "Hello


World"app.
4351604(MAD)
4351604(MAD)
4351604(MAD)
4351604(MAD)
4351604(MAD)
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();


4351604(MAD)
Toast.makeText(mContext,"Resume Method Called", Toast.LENGTH_SHORT).show(); } protected void
onStop()
{
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(); }

Output:
4351604(MAD)
4351604(MAD)

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" />
<Buttonandroid:id="@+id/btns ubs"
android:layout_width="match_parent"
android:layout_height="wrap_content
4351604(MAD)
" 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>

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;
4351604(MAD)
@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",

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("")) {
4351604(MAD)
// 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("")) {

// 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("")) {
4351604(MAD)
// Showing Toast (Message)
Toast.makeText(MainActivity.this,"PleaseEnterNumber", 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);

}
}
});

}
}
4351604(MAD)
Output:
4351604(MAD)
4351604(MAD)
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:lay
out_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);}}
4351604(MAD)
4351604(MAD)
Output:
4351604(MAD)
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>
4351604(MAD)
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);

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"?>
4351604(MAD)
<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" />
<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" />
4351604(MAD)
<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>
4351604(MAD)
Output:
4351604(MAD)
4351604(MAD)
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)
{EditText edittext1=(EditText) findViewById(R.id.editText1);
4351604(MAD)
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;
import android.os.Bundle; import android.widget.TextView;

public class activity_second extends AppCompatActivity


4351604(MAD)
{@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:
4351604(MAD)
4351604(MAD)
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:
ll.setBackgroundColor(Color.GREEN); break;
case R.id.blue:
ll.setBackgroundColor(Color.BLUE); break;
}
return true;
4351604(MAD)
}}
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
4351604(MAD)

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 ) );
}
4351604(MAD)
}}

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" />
<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"
4351604(MAD)
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;}
File - 4 : Manifest.java
<service
android:name=".NewService"
android:enabled="true"
android:exported="true" >
</service>
}

Output:
4351604(MAD)

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; import
android.content.Context; import
4351604(MAD)
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
4351604(MAD)

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) {
4351604(MAD)
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:

Practical 12
Develop an Android application that uses Broadcast
Receivers to receive and handle system- level
broadcasts.

Activitymain.xml:
<LinearLayout
xmlns:android="http://sch emas.android.com/apk/res/android"
xmlns:app="http://schem as.android.com/apk/res-auto"
xmlns:tools="http:// schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
4351604(MAD)
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();
}
}
}
}
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);
}
4351604(MAD)
}
4351604(MAD)

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;
static final UriMatcher uriMatcher;
4351604(MAD)
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;
4351604(MAD)
}
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);
}
@Override
4351604(MAD)
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"
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"
4351604(MAD)
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>
<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" />
4351604(MAD)
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);
// creating a cursor object of the
4351604(MAD)
// 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(strBurields)ultView.s e
}

Output:
4351604(MAD)
4351604(MAD)
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);
setContentView(R.layout.activity_main);
Button btnGetContacts = findViewById(R.id.btnGetContacts); Button btnGetEvents
= findViewById(R.id.btnGetEvents);
4351604(MAD)
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();
}
}
private void getCalendarEvents() {
4351604(MAD)
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();
}
}
}
}

Output:
4351604(MAD)
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);
4351604(MAD)
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
4351604(MAD)
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:
4351604(MAD)
4351604(MAD)
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);
onCreate(db);}
public long insertData(String name) { SQLiteDatabase db = this.getWritableDatabase();
4351604(MAD)
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();
}}});}}
4351604(MAD)
Output:
4351604(MAD)
4351604(MAD)
4351604(MAD)
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):


4351604(MAD)
• 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:
• 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.
4351604(MAD)
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).

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
4351604(MAD)

Output:
4351604(MAD)
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;
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);
4351604(MAD)
// 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;
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;
}
4351604(MAD)
@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);
}
}
}
4351604(MAD)
4351604(MAD)
Output:
4351604(MAD)

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
4351604(MAD)
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
4351604(MAD)

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"
4351604(MAD)
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;
import android.widget.Toast; import
androidx.appcompat.app.AppCompatActivity; import
com.android.volley.Request; import
com.android.volley.RequestQueue; import
4351604(MAD)
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,

}}};}
}
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
4351604(MAD)
// 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);
}
}
4351604(MAD)
4351604(MAD)
Output:
4351604(MAD)
4351604(MAD)
4351604(MAD)
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
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
4351604(MAD)
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;
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
4351604(MAD)
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
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
4351604(MAD)
// 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.
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;


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

Output:
4351604(MAD)
4351604(MAD)
4351604(MAD)
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,
// and move the map's camera to the same location.
LatLng myPos = new LatLng(Location.getLatitude(), Location.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPos));
4351604(MAD)
}
}

OUTPUT :
4351604(MAD)
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) ==
PackageManager.PERMISSION_GRANTED) { googleMap.setMyLocationEnabled(true);
} else {
4351604(MAD)
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:
4351604(MAD)
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-->
<EditText
4351604(MAD)
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"
android:backgroundTint="#2196f3" android:elevation="6dp"
android:padding="10dp" android:text="Next"
4351604(MAD)
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)
}
}
4351604(MAD)
Output:
4351604(MAD) Practical No.25
Install Flutter SDK, configure the development environment and display “Hello World” in the
centre of the screen.

Code :-
4351604(MAD)

Output:
4351604(MAD)

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,
),
4351604(MAD)
),
],
),
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,
),
),
], ),
],
),
);
}
}
4351604(MAD)

Output:
4351604(MAD)
4351604(MAD)
4351604(MAD)
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( errorText:
'Please correct email filled'),
4351604(MAD)
]),
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,
),
width: MediaQuery.of(context).size.width, height: 50,
),
),
4351604(MAD)
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,
),
)),
4351604(MAD)
), ],
),
), )
;
}
}
4351604(MAD)
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.
4351604(MAD)
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.
4351604(MAD)

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.
4351604(MAD)
- 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.
4351604(MAD)

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

You might also like