Mad Practicals Himanshu
Mad Practicals Himanshu
Mad Practicals Himanshu
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:
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
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.
ProgrammeOutcomes(POs):
4. EngineeringTools,ExperimentationandTesting:Applymodernengineering
toolsandappropriatetechniqueto conductstandardtestsandmeasurements.
5. Engineeringpracticesforsociety,sustainabilityandenvironment:Applyappropriate
technology in context of society, sustainability, environment and ethicalpractices.
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.
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.
IndustryRelevantSkills
Thefollowingindustryrelevantskillsareexpectedtobedevelopedinthestudentsbyperformanceo
fexperiments ofthis course.
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
Createanapplicationtoretrievedatafromthe
18 Firebase Database and display
it in theRecyclerView.
ConnectanAndroidapplicationtotheMySQLdatabas
19 eusingPHP,andinsertthedatainthedatabasetable.
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
File-1 : Activity_main.xml
<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();
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
<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;
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) {
Toast.LENGTH_SHORT).show();
}
}
}
});
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();
}
}
});
btnmult.setOnClickListener(new View.OnClickListener()
{@Override
public void onClick(View view) {
// Checking Input First Is Blank Or Not if
(txt1.getText().toString().equals("")) {
}
}
});
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();
}
}
}
});
}
}
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;
<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;
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"
</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
<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;
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" /
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Output:
4351604(MAD)
Practical 10
Develop an Android application that uses an Intent to pass data between different activities.
File - 1 : activity_main.xml
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) {
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;
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:
<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);
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.
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");
Practical No.19:
Connect an Android application to the MySQL database using PHP.
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
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;
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" />
<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() {
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.
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.
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