Mad Practicals Batch 241
Mad Practicals Batch 241
Mad Practicals Batch 241
Diploma Engineering
Laboratory Manual
(Mobile Application Development)
(4351604)
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
DTE’s Vision:
● To provide globally competitive technical education;
● Remove geographical imbalances and inconsistencies;
● Develop student friendly resources with a special focus on girls’ education and support to weaker
sections;
● Develop programs relevant to industry and create a vibrant pool of technical professionals.
DTE’s Mission:
• To provide a conducive learning environment to nurture learners.
• To act as a catalyst for achieving academic excellence by bringing stake holders on same platform.
• To be committed towards continuous improvement and enrichment of learners by a holistic
approach to education so as to enable them to be successful individuals and responsible citizens
of India.
Institute’s Vision:
• To be a leading technical institute that provides transformative education to learners for achieving
competency as per the needs of industry and society, thus contributing to nation building.
Institute’s Mission:
Department’s Vision:
• To acquire quality Education, Research and Development in the field of Information technology
meeting the global standards and comply with the ever-growing technology.
Department’s Mission:
• The graduates of our department will be efficient in technical and ethical responsibilities to
become globally recognized by pursuing opportunities for higher studies and real time problem
solving.
• Students will be competent by learning the principals of Information technology that can match
national and international standards.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Certificate
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as well
as creative ability amongst students to solve real time problems by developing relevant competencies
in psychomotor domain. Keeping in view, GTU has designed competency focused outcome-based
curriculum -2021 (COGC-2021) for Diploma engineering programmes. In this more time is allotted to
practical work than theory. It shows importance of enhancement of skills amongst students and it pays
attention to utilize every second of time allotted for practical amongst Students, Instructors and
Lecturersto achieve relevant outcomes by performing rather than writing practice in study type. It is
essential foreffective implementation of competency focused outcome- based Green curriculum-2021.
Every practical has been keenly designed to serve as a tool to develop & enhance relevant industry
needed competency in each and every student. These psychomotor skills are very difficult to develop
through traditional chalk and board content delivery method in the classroom. Accordingly, this lab
manual hasbeen designed to focus on the industry defined relevant outcomes, rather than old practice
of conductingpractical to prove concept and theory.
By using this lab manual, students can read procedure one day in advance to actual performance
day of practical experiment which generates interest and also, they can have idea of judgement of
magnitude prior to performance. This in turn enhances predetermined outcomes amongst students.
Eachand every Experiment /Practical in this manual begins by competency, industry relevant skills,
course outcomes as well as practical outcomes which serve as a key role for doing the practical. The
students will also have a clear idea of safety and necessary precautions to be taken while performing
experiment.
This manual also provides guidelines to lecturers to facilitate student-centered lab activities
for each practical/experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve outcomes.
It also givesan idea that how students will be assessed by providing Rubrics.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
7. Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
The following industry relevant skills are expected to be developed in the students by
performance of experiments of this course.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Develop an Android application that uses Content
14 Providers to read system-level data, such as contacts
and calendar events.
Create an application that creates a database using
15 SQLiteOpenHelper Class and performs Insert and
Read from the SQLite database.
Create an application to Update and Delete data
16 from the SQLite database using SQLiteOpenHelper
class.
Perform Firebase Integration to your Android
17 application and store the data in the Firebase
Database.
Create an application to retrieve data from the
18 Firebase Database and display it in the
RecyclerView.
Connect an Android application to the MySQL
19 database using PHP, and insert the data in the
database table.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical:1
Install Android Studio, set up the Android development environment,and create a simple "Hello World"
app.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 2
Develop a simple app that demonstrates the activity lifecycle.
File-1 : Activity_main.xml
<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();
super.onDestroy();
Outp
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 3
Develop a simple calculator app that takes user input and performs basic arithmetic
operations, such as addition, subtraction, multiplication, and division.
File- 1 : Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="First Number"
android:inputType="numberDecimal"
tools:ignore="TouchTargetSizeCheck,SpeakableTextPresentCheck" />
<EditText
android:id="@+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:ems="10" android:hint="Second
Number"
android:inputType="numberDecimal"
tools:ignore="SpeakableTextPresentCheck,TouchTargetSizeCheck" />
<Button
android:id="@+id/btnadd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Add" />
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button
android:id="@+id/btnsubs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Subtract" />
<Button
android:id="@+id/btndiv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Divide" />
<Button
android:id="@+id/btnmult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:text="Multiply" />
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="25dp"
android:layout_marginRight="20dp"
android:text="" />
</LinearLayout>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
File - 2 : MainAcitivity.java
package com.example.calculator;
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) {
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
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("")) {
// 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("")) {
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
}
}
});
btndiv.setOnClickListener(new View.OnClickListener()
{@Override
public void onClick(View view) {
// Checking Input First Is Blank Or Not if
(txt1.getText().toString().equals("")) {
// Showing Toast (Message)
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
} else if (txt2.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter Number", Toast.LENGTH_SHORT).show();
}
float a, b, c;
a = Float.parseFloat(txt1.getText().toString()); b
= Float.parseFloat(txt2.getText().toString());
c = a/b; // Using Third Variable To Store Output Value
result.setText("The Division Result Is " + c);
}
}
});
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 4
Develop an Android application that uses LinearLayout to arrange UI components vertically or
horizontally.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:text="Button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button2"
android:text="Button2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button3"
android:text="Button3"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainAcivity.java
package com.example.linearlayout;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Outpu
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 5
Develop an Android application that uses RelativeLayout to arrange UI
components relative to each other.
File - 1 : Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This the example of Relative Layout!"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:layout_alignParentLeft="true"
android:layout_below="@id/txt1"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:layout_alignParentRight=true"
android:layout_below="@id/txt1"/
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3"
android:layout_centerHorizontal="true"
android:layout_below="@id/button2"/>
</RelativeLayout>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:layout_alignParentRight="true"
android:layout_below="@id/txt1"/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3"
android:layout_centerHorizontal="true"
android:layout_below="@id/button2"/>
</RelativeLayout>
MainActivity.java
package com.example.relativelayout;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 6
Develop an Android application that uses ScrollView to display a long list of items.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.scrollview3.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Vertical ScrollView example"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<ScrollView android:layout_marginTop="30dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 5" />
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 6" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 7" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 8" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 9" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 10" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 11" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
<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>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 7
Develop an Android application that uses ListView and Custom Adapter to display a
list of images with text.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:ems="10">
<requestFocus />
</EditText>
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText1"
android:layout_alignLeft="@id/editText1"
android:layout_marginLeft="68dp"
android:layout_marginTop="-171dp"
android:onClick="ShowSecondActivity"
android:text="Click for SecondActivity" />
</RelativeLayout>
MainActivity.java
package com.example.intent;
import androidx.appcompat.app.AppCompatActivity; import
android.view.View;
import android.widget.EditText;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
{@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public void ShowSecondActivity(View v)
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
{EditText edittext1=(EditText) findViewById(R.id.editText1);
String name=edittext1.getText().toString();
Intent i = new Intent(this,activity_second.class);
i.putExtra("name",name);
startActivity(i);
}
}
public class MainActivity extends AppCompatActivity
{@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
}
public void ShowSecondActivity(View v)
{EditText edittext1=(EditText) findViewById(R.id.editText1);
String name=edittext1.getText().toString();
Intent i = new Intent(this,activity_second.class);
i.putExtra("name",name);
startActivity(i);
}}
activity_second.xml
<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:text="This is the second activity" />
</RelativeLayout>
activity_second.java package
com.example.intent;
import androidx.appcompat.app.AppCompatActivity; import
android.content.Intent;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.os.Bundle; import
android.widget.TextView;
t1.setText(name);
}
}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 8
Develop an Android application that uses the Navigation Drawer to display a side
menu.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@+id/ll"
tools:context=".MainActivity"
android:orientation="vertical">
</LinearLayout>
File -2 : MainActivity.java
package com.example.pr7;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem; import
android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
{LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ll
= findViewById(R.id.ll);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu, menu); return
true; }
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
switch (item.getItemId())
{ case R.id.red: ll.setBackgroundColor(Color.RED);
break;
case R.id.green:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
ll.setBackgroundColor(Color.GREEN);
break;
case R.id.blue:
ll.setBackgroundColor(Color.BLUE);
break;
}
return true;
}}
File -3 : menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/green" android:title="Green" />
<item android:id="@+id/red" android:title="Red" />
<item android:id="@+id/blue" android:title="Blue" />
</menu>
Output
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 9
Develop an Android application that uses the bottom navigation bar to switch between different
tabs.
File - 1 : Mainactivity.java
package com.example.backgroundservices;
import androidx.appcompat.app.AppCompatActivity; import
android.os.Bundle;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// declaring objects of Button class
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// to the object start
start = (Button) findViewById( R.id.startButton );
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// declaring listeners for the
// buttons to make them respond
// correctly according to the process
start.setOnClickListener( this );
stop.setOnClickListener( this );}
public void onClick(View view) {
// process to be performed
// if start button is clicked
if(view == start){
// starting the service
startService(new Intent( this, NewService.class ) ); }
// process to be performed
// if stop button is clicked
else if (view == stop){
// stopping the service
stopService(new Intent( this, NewService.class ) );
}
}}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
File - 2 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#168BC34A"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:text="heading"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp" android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold" /
<Button
android:id="@+id/startButton"
android:text="StartButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp" android:layout_marginTop="10dp"
android:layout_marginEnd="20dp" android:layout_marginBottom="20dp"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textStyle="bold"
/>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<Button
android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:text="stopButton"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:textStyle="bold" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
File - 3 : NewService.java
package com.example.backgroundservices;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings; import
androidx.annotation.Nullable;
public class NewService extends Service {
// declaring object of MediaPlayer
private MediaPlayer player;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); player.setLooping( true );
// starting the process
player.start();
// returns the status of the program
return START_STICKY;
}
@Override
public void onDestroy()
{super.onDestroy();
player.stop();
}
@Nullable @Override
public IBinder onBind(Intent intent)
{return null;}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
File - 4 : Manifest.java
<service
android:name=".NewService"
android:enabled="true"
android:exported="true" >
</service>
}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 10
Develop an Android application that uses an Intent to pass data between different
activities.
File - 1 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="broadcastIntent"
android:text="Broadcast Intent" />
</RelativeLayout>
File - 2 MainActivity.java
package com.example.broadcastreceiver;
import androidx.appcompat.app.AppCompatActivity; import
android.view.View;
import android.content.Intent;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void broadcastIntent(View v)
{
Intent intent=new Intent();
intent.setAction("CustomBroadcastIntent");
sendBroadcast(intent);
}
File - 3 : MyReceiver.java
package com.example.broadcastreceiver;
import android.content.BroadcastReceiver;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver
{@Override
public void onReceive(Context context,Intent intent)
{
Toast.makeText(context, "Its a broadcast Intent", Toast.LENGTH_LONG).show();
}
}
(4) Manifest.java
<receiver android:name="com.example.broadcastreceiver.MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="CustomBroadcastIntent" />
</intent-filter>
</receiver>
Output
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.11
Develop an Android application that uses Services to perform background tasks.
Activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText android:id="@+id/etNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" android:hint="Enter a
number" />
<Button android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Factorial" />
<TextView android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Result: " android:textSize="18sp" />
</LinearLayout>
<Button android:id="@+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Factorial"
android:onClick="calculateFactorial" />
androidmanifest.xml:
<service
android:name=".FactorialService"
android:enabled="true"
android:exported="false" />
MainActivity.java
public class MainActivity extends AppCompatActivity { private
EditText etNumber;
private TextView tvResult;
private FactorialService factorialService;
@Override
protected void onCreate(Bundle savedInstanceState) {
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNumber = findViewById(R.id.etNumber); tvResult =
findViewById(R.id.tvResult);
factorialService = new FactorialService();}
public void calculateFactorial(View view) { String input =
etNumber.getText().toString(); if (!input.isEmpty()) {
int number = Integer.parseInt(input);
int result = factorialService.calculateFactorial(number);
tvResult.setText("Result: " + result);
}}}
FactorialService.java
public class FactorialService extends Service {
@Override
public IBinder onBind(Intent intent) { return
null;
}
public int calculateFactorial(int n) { if (n ==
0 || n == 1) {
return 1;
} else { return n * calculateFactorial(n - 1);
}}}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 12
Develop an Android application that uses Broadcast Receivers to receive and handle system-
level broadcasts.
Activitymain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView android:id="@+id/tvStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" />
</LinearLayout>
AndroidManifest.xml:
<receiver android:name=".PowerConnectionReceiver"
android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
SMSReceiver.java
import android.content.BroadcastReceiver; import
android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class PowerConnectionReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) { String action
= intent.getAction();
if (action != null) {
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
MainActivity.java:
import android.os.Bundle; import
android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { private
TextView tvStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = findViewById(R.id.tvStatus);
}
}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 13
Develop an Android application that uses Content Providers to share data between different
apps and components.
Strings.xml
<resources>
<string name="app_name">Content_Provider_In_Android</string>
<string name="hintText">Enter User Name</string>
<string name="heading">Content Provider In Android</string>
<string name="insertButtontext">Insert Data</string>
<string name="loadButtonText">Load Data</string>
</resources>
MyContentProvider.java
package com.example.contentprovidersinandroid; import
android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues; import
android.content.Context; import
android.content.UriMatcher; import
android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteException; import
android.database.sqlite.SQLiteOpenHelper; import
android.database.sqlite.SQLiteQueryBuilder; import
android.net.Uri;
import java.util.HashMap;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
static final UriMatcher uriMatcher;
private static HashMap<String, String> values; static {
// to match the content URI
// every time user access table under content provider uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// to access whole table uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
// to access a particular row
// of the table
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) { case uriCode:
return "vnd.android.cursor.dir/users"; default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
// creating the database @Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) { case uriCode:
qb.setProjectionMap(values);
break; default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") { sortOrder id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri); return c;
}
// adding data to the database @Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values); if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) { case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs); break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null); return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) { int count = 0;
switch (uriMatcher.match(uri)) { case uriCode:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// sql query to drop a table
// having similar name
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#168BC34A" tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.13" tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:fontFamily="@font/roboto"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark" android:textSize="36sp"
android:textStyle="bold" />
<EditText
android:id="@+id/textName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="40dp"
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:fontFamily="@font/roboto"
android:hint="@string/hintText" />
<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickAddDetails"
android:text="@string/insertButtontext"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="onClickShowDetails"
android:text="@string/loadButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false" android:ems="10"
android:fontFamily="@font/roboto"
android:textColor="@android:color/holo_green_dark" android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@drawable/banner" />
MainActivity.java:
package com.example.contentprovidersinandroid; import
androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues; import
android.content.Context; import
android.database.Cursor; import
android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager; import
android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWin
dow(getCurrentFocus().getWindowToken(), 0); return true;
}
public void onClickAddDetails(View view) {
// class to add values in the database ContentValues values = new
ContentValues();
// fetching text from user values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());
// inserting into database through content URI getContentResolver().insert(MyContentProvider.CONTENT_URI,
values);
// displaying a toast message Toast.makeText(getBaseContext(), "New Record Inserted",
Toast.LENGTH_LONG).show();}
public void onClickShowDetails(View view) {
// inserting complete table details in this text field TextView resultView= (TextView)
findViewById(R.id.res);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
// creating a cursor object of the
// content URI Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null, null, null);
// iteration of the cursor
// to print whole table
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext(
}}}
}else { Text(strBuild)
resultView.se
}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.14
Develop an Android application that uses Content Providers to read system- level data, such as
contacts and calendar events.
AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
ActivityMain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button android:id="@+id/btnGetContacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Contacts" />
<Button android:id="@+id/btnGetEvents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Calendar Events" />
</LinearLayout>
MainActivity.java:
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CONTACTS_PERMISSION = 1; private
static final int REQUEST_CALENDAR_PERMISSION = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
setContentView(R.layout.activity_main);
Button btnGetContacts = findViewById(R.id.btnGetContacts); Button
btnGetEvents = findViewById(R.id.btnGetEvents);
btnGetContacts.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
checkContactsPermission();
}
});
btnGetEvents.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
checkCalendarPermission();
}
});
}
private void checkContactsPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) ==
PackageManager.PERMISSION_GRANTED) {
getContacts();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS},
REQUEST_CONTACTS_PERMISSION);
}
}
private void checkCalendarPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) ==
PackageManager.PERMISSION_GRANTED) {
getCalendarEvents();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR},
REQUEST_CALENDAR_PERMISSION);
}
}
private void getContacts() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor
= getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) { String
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_N AME));
String phoneNumber =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Handle the retrieved contact data here (e.g., display in a list)
}
cursor.close();
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
private void getCalendarEvents() {
Uri uri = CalendarContract.Events.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE)); String location =
cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION));
// Handle the retrieved calendar event data here (e.g., display in a list)
}
cursor.close();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode
== REQUEST_CONTACTS_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getContacts();
} else {
Toast.makeText(this, "Contacts permission denied", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_CALENDAR_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getCalendarEvents();
} else {
Toast.makeText(this, "Calendar permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.15
Create an application that creates a database using SQLiteOpenHelper Class and performs
Insert and Read from the SQLite database.
Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button android:id="@+id/btnInsertData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Data" />
<Button android:id="@+id/btnReadData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Data" />
</LinearLayout>
DatabaseHelper.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper { private static
final String DATABASE_NAME = "my_database"; private static final String
TABLE_NAME = "my_table";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
public DatabaseHelper(Context context) { super(context,
DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME +
" (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + "
TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
onCreate(db);
}
public long insertData(String name) { SQLiteDatabase db =
this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
return db.insert(TABLE_NAME, null, contentValues);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
}
MainActivity.java:
import android.database.Cursor;
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error inserting data",
Toast.LENGTH_SHORT).show();
}
}
});
btnReadData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Cursor cursor = databaseHelper.getData(); StringBuilder
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
data = new StringBuilder(); while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
data.append("ID: ").append(id).append(", Name: ").append(name).append("\n");
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.16
Create an application to Update and Delete data from the SQLite database using
SQLiteOpenHelper class.
Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity"
<Button android:id="@+id/btnUpdateData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Data" />
<Button android:id="@+id/btnDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
</LinearLayout>
DatabaseHelper.java:
import android.content.ContentValues;
import android.content.Context; import
android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper { private static
final String DATABASE_NAME = "my_database"; private static final String
TABLE_NAME = "my_table";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
public DatabaseHelper(Context context) { super(context,
DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME +
" (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + "
TEXT)";
db.execSQL(createTableQuery); }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
onCreate(db); }
public long insertData(String name) { SQLiteDatabase db =
this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
return db.insert(TABLE_NAME, null, contentValues);}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}}
MainActivity.java:
import android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); databaseHelper
= new DatabaseHelper(this);
Button btnUpdateData = findViewById(R.id.btnUpdateData); Button
btnDeleteData = findViewById(R.id.btnDeleteData);
btnUpdateData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
int updatedRows = databaseHelper.updateData(1, "Jane Doe"); if (updatedRows >
0) {
Toast.makeText(MainActivity.this, "Data updated successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error updating data",
Toast.LENGTH_SHORT).show();
} } } );
btnDeleteData.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
int deletedRows = databaseHelper.deleteData(1); if (deletedRows
> 0) {
Toast.makeText(MainActivity.this, "Data deleted successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Error deleting data",
Toast.LENGTH_SHORT).show();
} } } ); } }
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 17
Perform Firebase Integration to your Android application and store the data in the Firebase
Database.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
• Ensure that your Firebase integration works as expected and handle any errors that may occur
during data operations.
Step 1: Create a Firebase Project
1. Go to https://console.firebase.google.com/u/0/
2. Log in to Firebase with your Google account if are not already logged in.
3. Click on create the project.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Firebase will create a project for you and open it for you.
Step 4: Create a Realtime Database:
5. Go to Develop Option on Sidebar.
6. Click on Database.
7. Scroll down in a new screen and click on Create Database on Realtime Database.
8. Select Start in Test mode (In order to get read and write access to the database).
Click enable
Firebase will create a project for you and open it for you.
Step 4: Create a Realtime Database:
9. Go to Develop Option on Sidebar.
10. Click on Database.
11. Scroll down in a new screen and click on Create Database on Realtime Database.
12. Select Start in Test mode (In order to get read and write access to the database).
Click enable
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 18
Create an application to retrieve data from the Firebase Database and display it in the
RecyclerView
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout
>
List_items.xm
l:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/itemText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" android:textStyle="bold"
/>
</LinearLayout>
RecyclerView.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import
androidx.recyclerview.widget.LinearLayoutManager; import
androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
private ArrayList<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize RecyclerView
recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new
LinearLayoutManager(this));
// Initialize data ArrayList
data = new ArrayList<>();
// Initialize Firebase
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("items");
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.widget.TextView;
import
androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context context;
private ArrayList<String> data;
public MyAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.data = data;
}
@NonN
ull
@Overri
de
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View
view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); return new
ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String item = data.get(position);
holder.itemText.setText(item);
}
@Override
public int getItemCount()
{ return data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder
TextView itemText;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemText = itemView.findViewById(R.id.itemText);
}
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.19:
Connect an Android application to the MySQL database using PHP.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Now, 'result.toString()' will contain the JSON data from your MySQL database
} finally { urlConnection.disconnect();
}
JSONObject:
// Assuming 'result' contains the JSON data try {
JSONArray jsonArray = new JSONArray(result.toString()); for (int i =
0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name"); // Assuming there's a field 'name' in your database table
// Process the data as needed
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.20
Perform insertion of data to MySQL database using PHP from an Android application.
Courses.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745";
$conn = new mysqli($servername, $username, $password, $dbname);
$response = array();
if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){
$courseName = $_POST['courseName'];
$courseDuration = $_POST['courseDuration'];
$courseDescription = $_POST['courseDescription'];
$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`,
`courseDescription`) VALUES (?,?,?)");
$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription); if($stmt-
>execute() == TRUE){
$response['error'] = false;
$response['message'] = "course created successfully!";
} else{
$response['error'] = true;
$response['message'] = "failed\n ".$conn->error;
}
}
else
{
$response['error'] = true;
$response['message'] = "Insufficient parameters";
}
// at last we are printing our response which we get. echo
json_encode($response);
?>
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
tools:context=".MainActivity">
<!--Edit text for getting course Name-->
<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Name"
android:importantForAutofill="no"
android:inputType="text" />
<!--Edittext for getting course Duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Duration in min"
android:importantForAutofill="no"
android:inputType="time" />
<!--Edittext for getting course Description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginStart="10dp"
android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course
Description" android:importantForAutofill="no" android:inputType="text" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnSubmitCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit Course Details"
android:textAllCaps="false" />
</LinearLayout
> MainActivity.java:
import android.os.Bundle; import
android.text.TextUtils; import
android.util.Log; import
android.view.View; import
android.widget.Button;
import android.widget.EditText;
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity; import
com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating variable for button private
Button submitCourseBtn;
// creating a strings for storing our values from edittext fields. private String
courseName, courseDuration, courseDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt =
findViewById(R.id.idEdtCourseDescription); courseDurationEdt =
findViewById(R.id.idEdtCourseDuration); submitCourseBtn =
findViewById(R.id.idBtnSubmitCourse); submitCourseBtn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
// getting data from edittext fields.
courseName = courseNameEdt.getText().toString(); courseDescription =
courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString();
courseDuration);
// validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) {
courseNameEdt.setError("Please enter Course Name");
} else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course
Description");
} else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration");
} else {
// calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription,
}}};}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
}
private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
// url to post our data
String url = "http://localhost/courseApp/addCourses.php";
// creating a new variable for our request queue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// on below line we are calling a string
// request method to post the data to our API
// in this we are calling a post method.
StringRequest request = new StringRequest(Request.Method.POST, url, new
com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) { Log.e("TAG", "RESPONSE IS "
+ response); try {
JSONObject jsonObject = new JSONObject(response);
// on below line we are displaying a success toast message. Toast.makeText(MainActivity.this,
jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) { e.printStackTrace();}
// and setting data to edit text as empty courseNameEdt.setText("");
courseDescriptionEdt.setText("");
courseDurationEdt.setText("");}
}, new com.android.volley.Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
@Override
protected Map<String, String> getParams() {
// below line we are creating a map for storing
// our values in key and value pair.
Map<String, String> params = new HashMap<String, String>();
// on below line we are passing our
// key and value pair to our parameters. params.put("courseName", courseName);
params.put("courseDuration", courseDuration); params.put("courseDescription",
courseDescription);
// at last we are returning our params. return params;}
};
// below line is to make
// a json object request.
queue.add(request);
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical 21:
Perform reading of the data from the MySQL database using PHP in the JSON format
and display on the screen of an Android application.
readCourses.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745";
$conn = new mysqli($servername, $username, $password, $dbname);
$response = array();
if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){
$courseName = $_POST['courseName'];
$courseDuration = $_POST['courseDuration'];
$courseDescription = $_POST['courseDescription'];
$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`,
`courseDescription`) VALUES (?,?,?)");
$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription); if($stmt-
>execute() == TRUE){
$response['error'] = false;
$response['message'] = "course created successfully!";
} else{
$response['error'] = true;
$response['message'] = "failed\n ".$conn->error;}
}
else
{
$response['error'] = true;
$response['message'] = "Insufficient parameters"}
// at last we are printing our response which we get.
echo json_encode($response);
?>
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text for getting course Name-->
<EditText
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Name"
android:importantForAutofill="no"
android:inputType="text" />
<!--Edittext for getting course Duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Duration in min"
android:importantForAutofill="no"
android:inputType="time" />
<!--Edittext for getting course Description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Description"
android:importantForAutofill="no"
android:inputType="text" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnSubmitCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit Course Details"
android:textAllCaps="false" />
</LinearLayout>
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
MainActivity.java:
import android.os.Bundle; import
android.text.TextUtils; import
android.util.Log; import
android.view.View; import
android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity; import
com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating variable for button private
Button submitCourseBtn;
// creating a strings for storing our values from edittext fields. private String
courseName, courseDuration, courseDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt =
findViewById(R.id.idEdtCourseDescription);
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Description");
} else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration");
} else {
// calling method to add data to Firebase Firestore. addDataToDatabase(courseName, courseDescription,
}
}
};
}
private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
// url to post our data
String url = "http://localhost/courseApp/addCourses.php";
// creating a new variable for our request queue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
// on below line we are calling a string
// request method to post the data to our API
// in this we are calling a post method.
StringRequest request = new StringRequest(Request.Method.POST, url, new
com.android.volley.Response.Listener<String>() {
@Override
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.22:
Integrate Google maps API to your Android application and display your current
location in the app.
AndroidManifest.xml:
<meta-data
android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"
/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY" android:value="ENTER API_KEY " />
manifest.xml:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
Activity_Main.xml:
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.java:
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import androidx.appcompat.app.AppCompatActivity;
public class MapsMarkerActivity extends AppCompatActivity implements OnMapReadyCallback {
// onCreate method is called when the activity is first created @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.ActivityMain);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// This method is called when the map is ready to be used. @Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
// and move the map's camera to the same location.
LatLng myPos = new LatLng(Location.getLatitude(), Location.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPos));
}
}
OUTPUT :
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.23
Integrate Google maps API to your Android application and find the distance of any nearby
location from your current location and display it.
AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Activity_Main.xml:
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent" android:layout_height="match_parent" />
MainActivity.java:
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import
com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback; import
com.google.android.gms.maps.SupportMapFragment;
ActivityCompat.requestPermissions(this,
}
@Override
}}}}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.24
Develop an application which performs Login using the Google account of the user.
Activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#ffffff">
<!--Imageview for Google logo image-->
<ImageView
android:id="@+id/imgGLogo"
android:layout_width="160dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp" android:padding="4dp"
android:src="@drawable/google_logo" />
<!--Textview to display a message "Sign In"-->
<TextView
android:id="@+id/txtSignIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgGLogo"
android:layout_centerHorizontal="true"
android:padding="6dp
android:text="Sign In"
android:textColor="#000000"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/txtUseAccount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtSignIn"
android:layout_centerHorizontal="true"
android:padding="4dp" android:text="with your Google
account" android:textColor="#000000" />
<!--EditText for user name or email address-->
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
<EditText
android:id="@+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/txtUseAccount"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp" android:hint="Username or
Email" android:inputType="textEmailAddress"
android:maxLines="1"
android:padding="10dp"
android:textColor="#000000" /
<TextView
android:id="@+id/txtForgotEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etEmail"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:padding="10dp" android:text="Forgot
Email?" android:textColor="#2196f3"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginBottom="15dp"
android:padding="10dp" android:text="Create Account"
android:textColor="#2196f3" android:textStyle="bold" />
<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="15dp"
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
android:backgroundTint="#2196f3" android:elevation="6dp"
android:padding="10dp" android:text="Next"
android:textColor="@android:color/white"
android:textSize="14sp" android:textStyle="bold" />
</RelativeLayout>
Colors.xml:
<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() {
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
+Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.25
Install Flutter SDK, configure the development environment and display “Hello World” in the
centre of the screen.
Code :-
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.26
Develop a Flutter app to get two numbers from the user and display addition on the
screen after clicking a button.
return MaterialApp(
title: appTitle, home:
Scaffold( appBar:
AppBar(
title: Text(appTitle),
),
body: AddTwoNumbers(),
),
);
}
}
class AddTwoNumbers extends StatefulWidget {
@override
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}
class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = new TextEditingController();
TextEditingController num2controller = new TextEditingController(); String
result = "0";
@override
Widget build(BuildContext context) {
return Container(
child: Column( children:
<Widget>[ Row(
children: <Widget>[
Text("Number 1:"), new
Flexible(
child: new TextField(
keyboardType: TextInputType.number, controller:
num1controller,
),
),
],
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
),
Row(
children: <Widget>[
Text("Number 2:"), new
Flexible(
child: new TextField(
keyboardType: TextInputType.number, controller:
num2controller,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children:
<Widget>[
RaisedButton( child:
Text("Add"), onPressed :
() {
setState(() {
int sum = int.parse(num1controller.text) + int.parse(num2controller.text); result =
sum.toString();
});
},
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children:
<Widget>[
Text("Result:", style:
TextStyle( fontSize:
30,
),),
Text(result, style:
TextStyle( fontSize:
30,
),
),
],
),
],
),
);
}
}
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.27
Develop a Flutter app for Login using static data. If the User ID and Password are correct then
clicking a login button should open a new screen showing Username at the center of the new
screen.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:form_field_validator/form_field_validator.dart';
class Login extends StatefulWidget { const
Login({Key? key}) : super(key: key);
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
Map userData = {};
final _formkey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'), centerTitle:
true,
),
body: SingleChildScrollView( child:
Column( children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 30.0), child: Center(
child: Container( width: 120,
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40), border: Border.all(color: Colors.blueGrey)),
child: Image.asset('assets/logo.png'),
),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 15), child: Padding(
padding: const EdgeInsets.all(12.0), child: Form(
key: _formkey, child: Column(
crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0), child: TextFormField(
validator: MultiValidator([ RequiredValidator(
errorText: 'Enter email address'), EmailValidator(
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
errorText:
'Please correct email filled'),
]),
decoration: InputDecoration( hintText: 'Email', labelText: 'Email', prefixIcon: Icon(
Icons.email,
//color: Colors.green,
Padding(),
errorStyle: TextStyle(fontSize: 18.0), border: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red), borderRadius: BorderRadius.all(
Radius.circular(9.0)))))),
padding: const EdgeInsets.all(12.0), child: TextFormField(
validator: MultiValidator([ RequiredValidator(
errorText: 'Please enter Password'), MinLengthValidator(8,
errorText:
'Password must be atlist 8 digit'), PatternValidator(r'(?=.?[#!@$%^&-])',
special character')
]),
errorText:
'Password must be atlist one
decoration: InputDecoration( hintText: 'Password', labelText: 'Password', prefixIcon: Icon( Icons.key,
color: Colors.green,
),
errorStyle: TextStyle(fontSize: 18.0), border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red), borderRadius:
BorderRadius.all(Radius.circular(9.0))),
),
),
),
Container(
margin: EdgeInsets.fromLTRB(180, 0, 0, 0), child: Text('Forget Password!'),
),
Padding(
padding: const EdgeInsets.all(28.0), child: Container(
child: RaisedButton(
child: Text( 'Login',
style: TextStyle(
color: Colors.white, fontSize: 22),
),
onPressed: () {
if (_formkey.currentState!.validate()) { print('form submiitted');
}
},
shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30)),
color: Colors.blue,
),
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
width: MediaQuery.of(context).size.width, height: 50,
),
),
Center(
child: Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 0), child: Center(
child: Text(
'Or Sign In Using!', style: TextStyle(
fontSize: 18, color: Colors.black),
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center, children: [
Padding(
padding: EdgeInsets.fromLTRB(0, 20, 0, 0), child: Row(
children: [
Container(
height: 40,
width: 40,
child: Image.asset( 'assets/social.jpg', fit: BoxFit.cover,
)),
Container( height: 70,
width: 70,
child: Image.asset(
'assets/vishal.png', fit: BoxFit.cover,
),
),
Container( height: 40,
width: 40,
child: Image.asset(
'assets/google.png', fit: BoxFit.cover,
),
),
],
),
),
],
),
Center(
child: Container(
padding: EdgeInsets.only(top: 50), child: Text(
'SIGN UP!',
style: TextStyle( fontSize: 20,
fontWeight: FontWeight.w700, color: Colors.lightBlue,
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
),
)),
),
],
),
),
);
}
}
Output:
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Practical No.28
Demonstrate publishing an Android app on the Google Play Store following the policies and
guidelines.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Step 5: Technical Requirements
- Check unique Bundle ID (package name) for your app and ensure it's suitable for the app's lifetime.
- Sign the app release with a signing certificate to identify the author.
- Verify app size, file format, and consider using app bundles.
- Learn more about app file technical requirements in the Developer Documents.
Step 6: Creating The App On The Google Console
- Create a new app in your Developer Account by specifying the default language and adding a brief app
description.
Step 7: Store Listing
- Prepare the Store listing, including product description, screenshots, icon, feature graphic, promo video,
tags, localization, application type, and categorization.
- Provide contact details and link to your Privacy Policy.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
- The review process typically takes up to 2 days, but Google mentions it could take longer.
Harshil Bhagora
4351604(MAD) BATCH: A1 226170316013
Assessment-Rubrics { MAD-4351604}
Weightage in % 25 25 20 15 15 100
Marks 0-5 0-5 0-5 0-5 0-5 25
Sr No. Practical No.
1 Practical 1
2 Practical 2
3 Practical 3
4 Practical 4
5 Practical 5
6 Practical 6
7 Practical 7
8 Practical 8
9 Practical 9
10 Practical 10
11 Practical 11
12 Practical 12
13 Practical 13
14 Practical 14
15 Practical 15
16 Practical 16
17 Practical 17
18 Practical 18
19 Practical 19
20 Practical 20
21 Practical 21
22 Practical 22
23 Practical 23
24 Practical 24
25 Practical 25
26 Practical 26
27 Practical 27
28 Practical 28
Faculty Sign
Harshil Bhagora