0% found this document useful (0 votes)
37 views77 pages

Manikandan Development Manual

This document describes developing an Android application to demonstrate simple event handling. It discusses event listeners, handlers, and registration. Key event listeners include OnClickListener(), OnLongClickListener(), OnMenuItemClickListener(), and OnTouch(). The code sample shows setting an OnClickListener for a button. When clicked, it will call the onClick method. This provides a simple example of handling user interaction events in Android.

Uploaded by

Srisanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views77 pages

Manikandan Development Manual

This document describes developing an Android application to demonstrate simple event handling. It discusses event listeners, handlers, and registration. Key event listeners include OnClickListener(), OnLongClickListener(), OnMenuItemClickListener(), and OnTouch(). The code sample shows setting an OnClickListener for a button. When clicked, it will call the onClick method. This provides a simple example of handling user interaction events in Android.

Uploaded by

Srisanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

SETHU INSTITUTE OF TECHNOLOGY

(An Autonomous Institution | Accredited with ‘A’ Grade by NAAC)


PULLOOR, KARIAPATTI - 626 115

DEPARTMENT OF INFORMATION TECHNOLOGY

RECORD

SEMESTER: V

21UCS509
MOBILE APPLICATIONS DESIGN AND
DEVELOPMENT LABORATORY

NAME:

ROLL No.

REG. No.

DEPT.
SETHU INSTITUTE OF TECHNOLOGY
PULLOOR-626 115, KARIAPATTI
TALUK.VIRUDHUNAGAR DISTRICT

DEPARTMENT OF INFORMATION TECHNOLOGY

PRACTICAL RECORD

BONAFIDE CERTIFICATE

Certified that this the bonafide record of work done by


………………………………………………………………………………………
in the ………………………………………………………………………………...
Laboratory during the year……………………

Faculty In-charge Head of the Department

Reg.No:

Submitted for the Practical Examination held on


…………………………….

Internal Examiner External Examiner


TABLE OF CONTENTS

MARK SIGNATURE
EX.NO DATE TITLE OF THE
. EXPERIMENT
1. 04-07-23 Android Application that uses GUI
components, Font and Colors
2. 18-07-23 Develop an android application to
demonstrate simple event handling.
3. 01-08-23 Develop an android application to
implement Menus.
4. 22-08-23 Develop an android application to
implement Fragments.
5. 29-08-23 Develop an android application
customized Sending Email, Sending
SMS and Phone Calls using Intent
and intent filter

6. 05-09-23 Develop an android application to


implement a Location Based Services

7. 12-09-23 Develop an application to capture


image using built in camera

8. 19-09-23 Develop a simple Video player like


application using video view and
video Recorder.

9. 26-09-23 Develop an application that creates an


alert upon receiving a message and
call.

10. 03-10-23 Develop an android application to


demonstrate Firebase Database.
Ex No: 1 Android Application that uses GUI components, Font and Colors Date:

Aim:

To develop a Simple Android Application that uses GUI components, Font and Colors.

Procedure:
1 .Start the program .
2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Creating a New project:


▪ Open Android Stdio and then click on File -> New -> New project.

▪ Then type the Application name as “ex.no.1″ and click Next.

▪ Then select the Minimum SDK as shown below and click Next.
▪ Then select the Empty Activity and click Next.

▪ Finally click Finish.


▪ It will take some time to build and load the project.
▪ After completion it will look as given below.

Designing layout for the Android Application:


▪ Click on app -> res -> layout -> activity_main.xml.
▪ Now click on Text as shown below.

▪ Then delete the code which is there and type the code as given below.

Code for Activity_main.xml:

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#F09011">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="HELLO!!!! MOUNT ZION"
android:textSize="20sp"
android:fontFamily="sans-serif-medium"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="21IT048 "
android:textSize="20sp"
android:fontFamily="sans-serif-medium"
android:textStyle="bold" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change font size"
android:textSize="20sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change color"
android:textSize="20sp" />
</LinearLayout>

Code for MainActivity.java :

package com.example.exp1;

import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
float font =24;
int i=1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t1=(TextView)
findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
t1.setTextSize(font);
font=font+4;
if(font==40)
font=20;
}
});
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
switch(i)
{
case 1:
t1.setTextColor(Color.parseColor("#0000FF"));
break;
case 2:
t1.setTextColor(Color.parseColor("#00FF00"));
break;
case 3:
t1.setTextColor(Color.parseColor("#FF0000"));
break;
case 4:
t1.setTextColor(Color.parseColor("#800000"));
break;
}
i++;
if(i==5)
i=1;
}
});
}
}

Output:

Result:
Thus the given program To develop a Simple Android Application that uses GUI components, Font and
Colors output is verified and executed successfully .
EX No: 2 Develop an android application to demonstrate simple event handling. Date:

Events are the actions performed by the user in order to interact with the application, for e.g.
pressing a button or touching the screen. The events are managed by the android framework in
the FIFO manner i.e. First In – First Out. Handling such actions or events by performing the
desired task is called Event Handling.
Overview of the input event management
• Event Listeners: It is an interface in the View class. It contains a single callback method.
Once the view to which the listener is associated is triggered due to user interaction, the
callback methods are called.
• Event Handlers: It is responsible for dealing with the event that the event listeners
registered for and performing the desired action for that respective event.
• Event Listeners Registration: Event Registration is the process in which an Event
Handler gets associated with an Event Listener so that this handler is called when the
respective Event Listener fires the event.
• Touch Mode: When using an app with physical keys it becomes necessary to give focus to
buttons on which the user wants to perform the action but if the device is touch-enabled
and the user interacts with the interface by touching it, then it is no longer necessary to
highlight items or give focus to particular View. In such cases, the device enters touch
mode and in such scenarios, only those views for which the is Focusable InTouchMode() is
true will be focusable, e.g. plain text widget.
For e.g. if a button is pressed then this action or event gets registered by the event listener
and then the task to be performed by that button press is handled by the event handler, it can
be anything like changing the color of the text on a button press or changing the text itself, etc.
Event Listeners and their respective event handlers
• OnClickListener() – This method is called when the user clicks, touches, or focuses on
any view (widget) like Button, ImageButton, Image, etc. Event handler used for this is
onClick().
• OnLongClickListener() – This method is called when the user presses and holds a
particular widget for one or more seconds. Event handler used for this is onLongClick().
• OnMenuItemClickListener() – This method is called when the user selects a menu
item. Event handler used for this is onMenuItemClick().
• OnTouch() – This method is called either for a movement gesture on the screen or a press
and release of an on-screen key. Event handler used for this is onTouch().
There are various other event listeners available which can be used for different requirements
and can be found in the official documentation.

Aim :

To Develop an android application to demonstrate simple event handling


Procedure :

1 .Start the program .


2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .
Code for MainActivity.java:

package com.example.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {


private ProgressDialog progress;
Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);

b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});

b2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
}
Code for 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="21IT048 "
android:textSize="20sp"
android:fontFamily="sans-serif-medium"
android:textStyle="bold" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"

android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />

</RelativeLayout>
Sample Output :

Result :
Thus the given program To Develop an android application to demonstrate simple event handling
output is verified and executed successfully .
Ex No: 3 Develop an android application to implement Menus. Date:

In Android apps, you can make use of three standard menus supported within the platform: the
context menu, the options menu, and submenus. This is a common feature in almost all apps, so
your users will be used to the menu appearing in this way
To implement an options menu for an Activity in an Android app, a few fairly straightforward
steps are required.
Step 1: Open an Activity Class
Select your application package and choose “File”, “New”, then “Class” and enter a name of your
choice. Remember to make your class extend the Activity class and add it to the application
Manifest.
Step 2: Create a Resources Folder
The “res” folder holds all of your application resources. To create a menu, you need a menu
folder, so create one inside the “res” folder by selecting it and choosing “File”, “New”, then
“Folder” and entering “menu” as the name.

Your new folder will appear within the “res” directory:


Step 3: Create a Menu XML File
Choose the folder and create a new file by selecting “File”, “New”, then “File” and entering a
name. You can choose any filename you like, for example “my_options_menu.xml”.
<menu xmlns:android=”http://schemas.android.com/apk/res/android">
</menu>

Step 4: Add Items to Your Menu


You can add one or more items to your options menu depending on the needs of your own
project. Add an item for each menu option using the following syntax:
<item android: id=”@+id/about”
android: title=”About” />
<item android: id=”@+id/help”
android: title=”Help” />
Step 5: Create Icons for Your Menu Items
Once you have your icons in their folders, you can alter your menu item XML to include them as
follows:
<item android: id=”@+id/about”
android: icon=”@drawable/about”
android: title=”About” />
<item android:id=”@+id/help”
android:icon=”@drawable/help”
android: title=”Help” />
Step 6: Inflate Your Menu Resource
Add the following method to your Java code, inside the class declaration and after the “onCreate”
method:
public boolean onCreateOptionsMenu (Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate (R.menu.my_options_menu, menu);
return true;
}

Step 7: Detect User Interaction


Add the following method outline after the “onCreateOptionsMenu” method:
public boolean onOptionsItemSelected(MenuItem item) {
//respond to menu item selection
}

Step 8: Respond to Menu Item Selection


Add a switch statement to your method using the following sample syntax:
switch (item.getItemId()) {
case R.id.about:
StartActivity(new Intent(this, About.class));
return true;
case R.id.help:
startActivity(new Intent(this, Help.class));
return true;
default:
return super.onOptionsItemSelected(item);
}

Aim :

To Develop an android application to implement Menus.

Procedure :

1 .Start the program .


2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Code for Activity_main.xml:

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


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/search_item"
android:title="Search" />
<item android:id="@+id/upload_item"
android:title="Upload" />
<item android:id="@+id/copy_item"
android:title="Copy" />
<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" />
</menu>
Code for Main activity.java :

package com.example.optionsmenu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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 onCreateOptionsMenu(Menu menu) {
getMenuInflater()
.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
switch (item.getItemId()) {
case R.id.search_item:
return true;
case R.id.upload_item:
return true;
case R.id.copy_item:
return true;
case R.id.print_item:
return true;
case R.id.share_item:
return true;
case R.id.bookmark_item:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Output :

Result :
Thus the given program To Develop an android application to implement Menus output is verified
and executed successfully .
Ex No: 4 Develop an android application to implement Fragments. Date:

Android Fragment is the part of activity, it is also known as sub-activity. There can be more
than one fragment in an activity. Fragments represent multiple screen inside one activity.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment objects.

Android Fragment Lifecycle


The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.

Android Fragment Lifecycle Methods


No. Method Description

1) onAttach(Activity) it is called only once when it is attached with


activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate()


method.

5) onViewStateRestored(Bundle) It provides information to the fragment that all


the saved state of fragment view hierarchy has
been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

11) onDestroy() allows the fragment to do final clean up of


fragment state.
12) onDetach() It is called immediately prior to the fragment no
longer being associated with its activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.

activity_main.xml :

<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"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20sp"

android:gravity="center"

android:text="21IT048 "

android:textSize="20sp"

android:fontFamily="sans-serif-medium"

android:textStyle="bold" />

<!-- display two Button's and a FrameLayout to replace the Fragment's -->

<Button
android:id="@+id/firstFragment"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@color/button_background_color"

android:text="First Fragment"

android:textColor="@color/white"

android:textSize="20sp" />

<Button

android:id="@+id/secondFragment"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:background="@color/button_background_color"

android:text="Second Fragment"

android:textColor="@color/white"

android:textSize="20sp" />

<FrameLayout

android:id="@+id/frameLayout"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginTop="10dp" />

</LinearLayout>
MainActivity class :
package com.android.fragmentexample;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button firstFragment, secondFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);

// perform setOnClickListener event on First Button


firstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});

private void loadFragment(Fragment fragment) {


// create a FragmentManager
FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit(); // save the changes
}
}
Output:

Result :

Thus the given program To Develop an android application to demonstrate simple event handling
output is verified and executed successfully .
Ex No: 5 Develop an android application customized Sending Email, Sending SMS and Phone
Calls using Intent and intent filter.
Date:

An Intent is a messaging object you can use to request an action from another app component.
Although intents facilitate communication between components in several ways, there are three
fundamental use cases:
• Starting an activity
An Activity represents a single screen in an app. You can start a new instance of an Activity by
passing an Intent to startActivity(). The Intent describes the activity to start and carries any
necessary data.
If you want to receive a result from the activity when it finishes, call startActivityForResult().
Your activity receives the result as a separate Intent object in your
activity's onActivityResult() callback. For more information, see the Activities guide.
• Starting a service
A Service is a component that performs operations in the background without a user interface.
With Android 5.0 (API level 21) and later, you can start a service with JobScheduler. For more
information about JobScheduler, see its API-reference documentation.
For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of
the Service class. You can start a service to perform a one-time operation (such as downloading a
file) by passing an Intent to startService(). The Intent describes the service to start and carries
any necessary data.
If the service is designed with a client-server interface, you can bind to the service from another
component by passing an Intent to bindService(). For more information, see the Services guide.
• Delivering a broadcast
A broadcast is a message that any app can receive. The system delivers various broadcasts for
system events, such as when the system boots up or the device starts charging. You can deliver a
broadcast to other apps by passing an Intent to sendBroadcast() or sendOrderedBroadcast().
The rest of this page explains how intents work and how to use them. For related information,
see Interacting with Other Apps and Sharing Content.
Intent types
There are two types of intents:
• Explicit intents specify which application will satisfy the intent, by supplying either the target
app's package name or a fully-qualified component class name. You'll typically use an explicit
intent to start a component in your own app, because you know the class name of the activity or
service you want to start. For example, you might start a new activity within your app in
response to a user action, or start a service to download a file in the background.
• Implicit intents do not name a specific component, but instead declare a general action to
perform, which allows a component from another app to handle it. For example, if you want to
show the user a location on a map, you can use an implicit intent to request that another capable
app show a specified location on a map.
Figure 1 shows how an intent is used when starting an activity. When the Intent object names a
specific activity component explicitly, the system immediately starts that component.

Aim:
To Develop an android application customized Sending Email, Sending SMS and Phone
Calls using Intent and intent filter.
Procedure:
1 .Start the program .
2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Code for activity_main.xml :

<?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="match_parent"

android:paddingLeft="20dp"

android:paddingRight="20dp"

android:orientation="vertical" >

<EditText

android:id="@+id/txtTo"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="To"/>

<EditText

android:id="@+id/txtSub"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Subject"/>

<EditText

android:id="@+id/txtMsg"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"
android:gravity="top"

android:hint="Message"/>

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20sp"

android:gravity="center"

android:text="21IT048 "

android:textSize="20sp"

android:fontFamily="sans-serif-medium"

android:textStyle="bold" />

<Button

android:layout_width="100dp"

android:layout_height="wrap_content"

android:layout_gravity="right"

android:text="Send"

android:id="@+id/btnSend"/>

</LinearLayout>

Code for MainActivity.java:

package com.sendmailexample;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

private EditText eTo;

private EditText eSubject;

private EditText eMsg;

private Button btn;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

eTo = (EditText)findViewById(R.id.txtTo);

eSubject = (EditText)findViewById(R.id.txtSub);

eMsg = (EditText)findViewById(R.id.txtMsg);

btn = (Button)findViewById(R.id.btnSend);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent it = new Intent(Intent.ACTION_SEND);

it.putExtra(Intent.EXTRA_EMAIL, new String[]{eTo.getText().toString()});

it.putExtra(Intent.EXTRA_SUBJECT,eSubject.getText().toString());

it.putExtra(Intent.EXTRA_TEXT,eMsg.getText());

it.setType("message/rfc822");

startActivity(Intent.createChooser(it,"Choose Mail App"));

});

}
Output :

Result :
Thus the given program To Develop an android application customized Sending
Email,Sending SMS and Phone Calls using Intent and intent filter output is verified and executed
successfully .
Ex No: 6 Develop an android application to implement a Location Based Services. Date:

Android location APIs make it easy for you to build location-aware applications, without
needing to focus on the details of the underlying location technology.
This becomes possible with the help of Google Play services, which facilitates adding location
awareness to your app with automated location tracking, geofencing, and activity recognition.
This tutorial shows you how to use Location Services in your APP to get the current location, get
periodic location updates, look up addresses etc.
The Location Object
The Location object represents a geographic location which can consist of a latitude, longitude,
time stamp, and other information such as bearing, altitude and velocity. There are following
important methods which you can use with Location object to get location specific information −
Sr.No. Method & Description

1 float distanceTo(Location dest)


Returns the approximate distance in meters between this location and the given
location.

2 float getAccuracy()
Get the estimated accuracy of this location, in meters.

3 double getAltitude()
Get the altitude if available, in meters above sea level.

4 float getBearing()
Get the bearing, in degrees.

5 double getLatitude()
Get the latitude, in degrees.

6 double getLongitude()
Get the longitude, in degrees.

7 float getSpeed()
Get the speed if it is available, in meters/second over ground.

8 boolean hasAccuracy()
True if this location has an accuracy.

9 boolean hasAltitude()
True if this location has an altitude.

10 boolean hasBearing()
True if this location has a bearing.
11 boolean hasSpeed()
True if this location has a speed.

12 void reset()
Clears the contents of the location.

13 void setAccuracy(float accuracy)


Set the estimated accuracy of this location, meters.

14 void setAltitude(double altitude)


Set the altitude, in meters above sea level.

15 void setBearing(float bearing)


Set the bearing, in degrees.

16 void setLatitude(double latitude)


Set the latitude, in degrees.

17 void setLongitude(double longitude)


Set the longitude, in degrees.

18 void setSpeed(float speed)


Set the speed, in meters/second over ground.

19 String toString()
Returns a string containing a concise, human-readable description of this object.

Get the Current Location


To get the current location, create a location client which is LocationClient object, connect it to
Location Services using connect() method, and then call its getLastLocation() method. This
method returns the most recent location in the form of Location object that contains latitude and
longitude coordinates and other information as explained above. To have location based
functionality in your activity, you will have to implement two interfaces −
• GooglePlayServicesClient.ConnectionCallbacks
• GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to implement in
your activity class −
Sr.No. Callback Methods & Description

1 abstract void onConnected(Bundle connectionHint)


This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.

2 abstract void onDisconnected()


This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.

3 abstract void onConnectionFailed(ConnectionResult result)


This callback method is called when there was an error connecting the client to the
service.
You should create the location client in onCreate() method of your activity class, then connect it
in onStart(), so that Location Services maintains the current location while your activity is fully
visible. You should disconnect the client in onStop() method, so that when your app is not
visible, Location Services is not maintaining the current location. This helps in saving battery
power up-to a large extent.

Get the Updated Location


If you are willing to have location updates, then apart from above mentioned interfaces, you will
need to implement LocationListener interface as well. This interface provide following callback
method, which you need to implement in your activity class −
Sr.No. Callback Method & Description

1 abstract void onLocationChanged(Location location)


This callback method is used for receiving notifications from the LocationClient when
the location has changed.
Location Quality of Service
The LocationRequest object is used to request a quality of service (QoS) for location updates
from the LocationClient. There are following useful setter methods which you can use to handle
QoS. There are equivalent getter methods available which you can check in Android official
documentation.
Sr.No. Method & Description

1 setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.

2 setExpirationTime(long millis)
Set the request expiration time, in millisecond since boot.

3 setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.

4 setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.

5 setNumUpdates(int numUpdates)
Set the number of location updates.
6 setPriority(int priority)
Set the priority of the request.
Now for example, if your application wants high accuracy location it should create a location
request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5
seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER
for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for
"block" level accuracy.
Activities should strongly consider removing all location request when entering the background
(for example at onPause()), or at least swap the request to a larger interval and lower quality to
save power consumption.
Displaying a Location Address
Once you have Location object, you can use Geocoder.getFromLocation() method to get an
address for a given latitude and longitude. This method is synchronous, and may take a long time
to do its work, so you should call the method from the doInBackground() method of
an AsyncTask class.
The AsyncTask must be subclassed to be used and the subclass will
override doInBackground(Params...) method to perform a task in the background
and onPostExecute(Result) method is invoked on the UI thread after the background
computation finishes and at the time to display the result. There is one more important method
available in AyncTask which is execute(Params... params), this method executes the task with
the specified parameters.
Example
Following example shows you in practical how to to use Location Services in your app to get the
current location and its equivalent addresses etc.

AIM :

To Develop an android application to implement a Location Based Services .

PROCEDURE :

1 .Start the program .


2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Code for Activity_main.xml:


<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="21IT048 "
android:textSize="20sp"
android:fontFamily="sans-serif-medium"
android:textStyle="bold" />

<Button
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>

</LinearLayout>

Code forMainActivity.java:

package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{mPermission},


REQUEST_CODE_PERMISSION);

// If any permission above not allowed by user, this condition will


execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

btnShowLocation = (Button) findViewById(R.id.button);

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}
}

Output :

Result :
Thus the given program To Develop an android application to implement a Location Based Services
output is verified and executed successfully .
Ex No : 7 Develop an application to capture image using built in camera Date:

These are the following two ways, in which you can use camera in your application
• Using existing android camera application in our application
• Directly using Camera API provided by android in our application

Using existing android camera application in our application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above, there are other available Intents provided by MediaStore. They are listed
as follows
Sr.No Intent type and description

ACTION_IMAGE_CAPTURE_SECURE
1
It returns the image captured from the camera , when the device is secured

ACTION_VIDEO_CAPTURE
2
It calls the existing video application in android to capture video

EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape

EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage

INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode

EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There
are methods defined in the activity class that does the same job , but used when you are not
calling from the activity but from somewhere else. They are listed below
Sr.No Activity function description

startActivityForResult(Intent intent, int requestCode, Bundle options)


1
It starts an activity , but can take extra bundle of options with it

startActivityFromChild(Activity child, Intent intent, int requestCode)


2
It launch the activity when your activity is child of any other activity
startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle
3 options)
It work same as above , but it can take extra values in the shape of bundle with it

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)


4
It launches activity from the fragment you are currently inside

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode,


5 Bundle options)
It not only launches the activity from the fragment , but can take extra values with it
No matter which function you used to launch the activity , they all return the result. The result
can be obtained by overriding the function onActivityResult.

Aim:
To Develop an application to capture image using built in camera .
Procedure:
1 .Start the program .
2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Code for 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=".MainActivity">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20sp"

android:gravity="center"

android:text="21IT048 "

android:textSize="20sp"
android:fontFamily="sans-serif-medium"

android:textStyle="bold" />

<!-- add Camera Button to open the Camera -->

<Button

android:id="@+id/camera_button"

android:layout_width="100dp"

android:layout_height="50dp"

android:layout_marginStart="150dp"

android:text="Camera" />

<!-- add ImageView to display the captured image -->

<ImageView

android:id="@+id/click_image"

android:layout_width="350dp"

android:layout_height="450dp"

android:layout_marginStart="30dp"

android:layout_marginTop="70dp"

android:layout_marginBottom="10dp" />

</RelativeLayout>

Code for MainActivity.java :

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// Define the pic id


private static final int pic_id = 123;
// Define the button and imageview type variable
Button camera_open_id;
ImageView click_image_id;

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

// By ID we can get each component which id is assigned in XML file get Buttons and
imageview.
camera_open_id = findViewById(R.id.camera_button);
click_image_id = findViewById(R.id.click_image);

// Camera_open button is for open the camera and add the setOnClickListener in this button
camera_open_id.setOnClickListener(v -> {
// Create the camera_intent ACTION_IMAGE_CAPTURE it will open the camera for
capture the image
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Start the activity with camera_intent, and request pic id
startActivityForResult(camera_intent, pic_id);
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pic_id) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
click_image_id.setImageBitmap(photo);
}
}
}

Output :

Result :
Thus the given program To Develop an application to capture image using built in camera
output is verified and executed successfully .
Ex No : 8 Develop a simple Video player like application using video view and
videoRecorder. Date:

By the help of MediaController and VideoView classes, we can play the video files in android.
MediaController class
The android.widget.MediaController is a view that contains media controls like play/pause,
previous, next, fast-forward, rewind etc.
VideoView class
The android.widget.VideoView class provides methods to play and control the video player.
The commonly used methods of VideoView class are as follows:
Method Description

public void sets the media controller


setMediaController(MediaController to the video view.
controller)

public void setVideoURI (Uri uri) sets the URI of the video
file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time


in miliseconds.

Aim:

To Develop a simple Video player like application using video view and videoRecorder.

Procedure:

1 .Start the program .

2. Importing necessary packages .

3. Then develop and design XML file and JAVA file .

4. Run the program in android studio and display the output .

5. Stop .
Code for activity_main.xml :

<RelativeLayout xmlns:androclass="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=".MainActivity" >

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20sp"

android:gravity="center"

android:text="21IT048 "

android:textSize="20sp"

android:fontFamily="sans-serif-medium"

android:textStyle="bold" />

<VideoView

android:id="@+id/videoView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_centerVertical="true" />

</RelativeLayout>
Code for MainActivity.java:

package com.example.videoplayerexample;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

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

VideoView videoView =(VideoView)findViewById(R.id.videoView1);

//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);

//specify the location of media file


Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");

//Setting MediaController and URI, then starting the videoView


videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
Output :

Result :

Thus the given program Develop a simple Video player like application using video view
and videoRecorder output is verified and executed successfully .
Ex No: 9 Develop an application that creates an alert upon receiving a message and
call.
Date:

Android Application that creates an alert upon receiving a message


Creating a New project:
▪ Open Android Studio and then click on File -> New -> New project.

▪ Then type the Application name as “ex.no.10″ and click Next.

▪ Then select the Minimum SDK as shown below and click Next.
▪ Then select the Empty Activity and click Next.

▪ Finally click Finish.


▪ It will take some time to build and load the project.
▪ After completion it will look as given below.

Creating Second Activity for the Android Application:


▪ Click on File -> New -> Activity -> Empty Activity.
▪ Type the Activity Name as Second Activity and click Finish button.

▪ Thus Second Activity For the application is created.


Designing layout for the Android Application:
▪ Click on app -> res -> layout -> activity_main.xml.
▪ Now click on Text as shown below.

Aim:
To Develop an application that creates an alert upon receiving a message and call.

Procedure:

1 .Start the program .

2. Importing necessary packages .

3. Then develop and design XML file and JAVA file .

4. Run the program in android studio and display the output .

5. Stop .
Code for activity_main.xml :

<?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="match_parent"

android:layout_margin="10dp"

android:orientation="vertical">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="20sp"

android:gravity="center"

android:text="21IT048 "

android:textSize="20sp"

android:fontFamily="sans-serif-medium"

android:textStyle="bold" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Message"

android:textSize="30sp" />

<EditText

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:singleLine="true"

android:textSize="30sp" />

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="30dp"

android:layout_gravity="center"

android:text="Notify"

android:textSize="30sp"/>

</LinearLayout>

Code for MainActivity.java:

package com.example.exno10;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;
public class MainActivity extends AppCompatActivity

Button notify;

EditText e;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

notify= (Button) findViewById(R.id.button);

e= (EditText) findViewById(R.id.editText);

notify.setOnClickListener(new View.OnClickListener()

@Override

public void onClick(View v)

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

PendingIntent pending = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

Notification noti = new Notification.Builder(MainActivity.this).setContentTitle("New


Message").setContentText(e.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pen
ding).build();

NotificationManager manager = (NotificationManager)


getSystemService(NOTIFICATION_SERVICE);

noti.flags |= Notification.FLAG_AUTO_CANCEL;

manager.notify(0, noti);

});

}}
Output :

Result :
Thus the given program To Develop an application that creates an alert
upon receiving a message and call output is verified and executed successfully .
Ex No: 10 Develop an android application to demonstrate Firebase Database. Date:

Firebase: Real-time database setup and configuration


In our previous section, we learned about the Firebase Real-time database, its key capabilities,
and alternatives. Now, we will discuss how we set up and configure an Android application with
Firebase to use the Real-time database in Firebase. The starting step will be the same, but in this
section, we will use Kotlin rather than Java. So let's start with the starting steps and elaborate on
each step, which is performed to set up and configure the application to use a Real-time database
in Firebase.
Step 1:
In the first step, we will create a new Android Studio project with an empty activity and Kotlin
language and give it name FirebaseRealtimeDatabaseExample.

Step 2:
Firebase either from Firebase Assistant or manually using console. After that, we will add all the
required libraries and plugin to our app.gradle file. And we will also add mavenLocal() as our
repository and all projects.

Step 3:
In the next step, we will go to the Firebase console and look at the Real-time database. In
Developers-> Database, there will be two options, i.e., cloud Firestore and Real-time database.

Step 4:
In the next step, we will create a database by clicking on the Create database. After clicking on
Create database, a popup box is open where we actually create a database with specific rules. We
will talk about these rules later in this section. But for now, we will select start in test mode
where anybody can access our data, and later we change these rules. And last we select on
Enable.

Step 5:
After clicking on Enable, the real-time database will be enabled with a database by default. Here,
we have Data, Rules, Backups, and, Usage for data storing, security rules, backups, and usage,
respectively.

Before understanding the next steps, we will talk about the Firebase Database Rules.
The Real-time database provides a declarative rules language. It defines how our data should be
structured, how it should be indexed, and when our data can be read from and written to. By
default, read and write access to our database is restricted, so only authenticated users can read or
write data.
To get started without setting up Authentication, we can configure our rules for public access.
These rules make our database open to anyone, even people not using our app, read and write
access to our database.
{
"rules": {
".read": true,
".write": true
}
}
If we want to allow authenticated users for accessing read and write to our database, then we will
use the following rules:
{
"rules": {
".read": "auth!=null",
".write": "auth!=null"
}
}
This will make sure that user only who have been authenticated using firebase can read and write
to our database.
Step 6:
In the next step, we will go to the console and go to database rules and modify these rules to
authenticated users.

After performing the required changes in the rules, we will publish them.

Now, our database is set with specific rules, and we can use it now. In the next section, we will
learn how we perform read and write operations in a Real-time database.

Aim:

To Develop an android application to demonstrate Firebase Database .

Procedure:
1 .Start the program .
2. Importing necessary packages .
3. Then develop and design XML file and JAVA file .
4. Run the program in android studio and display the output .
5. Stop .

Code for 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=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="21IT048 "
android:textSize="20sp"
android:fontFamily="sans-serif-medium"
android:textStyle="bold" />

<!--EditText for adding employee name-->


<EditText
android:id="@+id/idEdtEmployeeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:hint="Enter Employee Name"
android:importantForAutofill="no"
android:inputType="textPersonName" />

<!--EditText for adding employee phone-->


<EditText
android:id="@+id/idEdtEmployeePhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeName"
android:layout_margin="10dp"
android:hint="Enter employee phone number"
android:importantForAutofill="no"
android:inputType="phone" />

<!--EditText for adding employee address-->


<EditText
android:id="@+id/idEdtEmployeeAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeePhoneNumber"

android:layout_margin="10dp"
android:hint="Enter employee address"
android:inputType="textPostalAddress" />

<!--Button for adding data to Firebase-->


<Button
android:id="@+id/idBtnSendData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeAddress"
android:layout_margin="10dp"
android:text="Add employee details"
android:textAllCaps="false" />

</RelativeLayout>

Code for MainActivity.java:

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

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;

public class MainActivity extends AppCompatActivity {

// creating variables for

// EditText and buttons.

private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;

private Button sendDatabtn;

// creating a variable for our

// Firebase Database.

FirebaseDatabase firebaseDatabase;

// creating a variable for our Database

// Reference for Firebase.

DatabaseReference databaseReference;

// creating a variable for

// our object class

EmployeeInfo employeeInfo;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// initializing our edittext and button

employeeNameEdt = findViewById(R.id.idEdtEmployeeName);

employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);
employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);

// below line is used to get the

// instance of our FIrebase database.

firebaseDatabase = FirebaseDatabase.getInstance();

// below line is used to get reference for our database.

databaseReference = firebaseDatabase.getReference("EmployeeInfo");

// initializing our object

// class variable.

employeeInfo = new EmployeeInfo();

sendDatabtn = findViewById(R.id.idBtnSendData);

// adding on click listener for our button.

sendDatabtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// getting text from our edittext fields.

String name = employeeNameEdt.getText().toString();

String phone = employeePhoneEdt.getText().toString();

String address = employeeAddressEdt.getText().toString();

// below line is for checking whether the

// edittext fields are empty or not.

if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) &&


TextUtils.isEmpty(address)) {
// if the text fields are empty

// then show the below message.

Toast.makeText(MainActivity.this, "Please add some data.",


Toast.LENGTH_SHORT).show();

} else {

// else call the method to add

// data to our database.

addDatatoFirebase(name, phone, address);

});

private void addDatatoFirebase(String name, String phone, String address) {

// below 3 lines of code is used to set

// data in our object class.

employeeInfo.setEmployeeName(name);

employeeInfo.setEmployeeContactNumber(phone);

employeeInfo.setEmployeeAddress(address);

// we are use add value event listener method

// which is called with database reference.

databaseReference.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

// inside the method of on Data change we are setting

// our object class to our database reference.

// data base reference will sends data to firebase.


databaseReference.setValue(employeeInfo);

// after adding this data we are showing toast message.

Toast.makeText(MainActivity.this, "data added",


Toast.LENGTH_SHORT).show();

@Override

public void onCancelled(@NonNull DatabaseError error) {

// if the data is not added or it is cancelled then

// we are displaying a failure toast message.

Toast.makeText(MainActivity.this, "Fail to add data " + error,


Toast.LENGTH_SHORT).show();

});

}
Output :

Result :
Thus the given program To Develop an android application to demonstrate Firebase Database
output is verified and executed successfully .

You might also like