Mobile App Development Question Bank

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

MOBILE APP DEVELOPMENT QUESTION BANK

Q1 2 MARKS QUESTIONS.
.

1. State android ECO system


Android ecosystem is nothing but the inter-dependence between users, developers and
equipment makers.
One cannot exists without the other.
The main building block of android ecosystem is :
1. Android User.
2. Equipment Makers for android.
3. Developer.

2. List all tools and softwares required for developing an android application.
Tools :
1. Android Studio
2. Eclipse IDE

Software Required :
1. Java JDK5 or Latest version.
2. Android Studio.

3. List various layouts used in android UI design.


1. Linear Layout
2. Absolute Layout
3. Table Layout
4. Frame Layout
5. Relative Layout

4. Name any four attributes of Edit Text control


1. android:autoText
2. android:drawableBottom
3. android:drawableRight
4. android:text
5. android:editable

5. State the use of fragments in android App development.


To improve the flexibility of our app UI and make it easier to adjust our app design based
on the device size we use fragments.

6. Define SMS service in android application development.

7. List different types of sensors used in android.


1. Motion Sensor.
2. Environmental Sensor.
3. Position Sensor.

8. Define emulator
Android emulator simulates android devices on your computer so that you can test your
applications on a variety of devices and android api levels without needing to have each
physical device. The emulator provides almost all the capabilities of a real android device.
9. List any four attributes of layout.
1. android:id
2. android:layout_x
3. android:layout_y
4. android:gravity
5. android:divider
6. android:orientation

10. Define Geocoding and Reverse Geocoding.


Finding the geographical cooridinates of a given address or location is called geocoding and
where a pair of longitude and latitude is converted into an address or location is called as
reverse geocoding.

11. State intent. List types of intent.


An intent is a messaging object used to request an action from another app component via
the android system.
An intent is a description of an operation to be performed.
Types :
1. Implicit Intent.
2. Explicit Intent.

12. Write difference between toggle button and radio button.


Toggle button displays checked/unchecked states as a button. It basically an on or off
button with a light indicator.
Were radio button has 2 states either checked or unchecked. This allows user to select one
option from a set.

13. Define :
i) Fragment
ii) Broadcast receiver
Fragments are the modular section of an activity design. Fragments are used to represent
the behaviour of user interface in an activity. We can build multiple fragments in an single
activity. And also use same fragments in the multiple activity. Fragments has its own life
cycle.

A broadcast receiver is an Android component that allows an application to respond to


messages that are broadcast by the Android operating system or by an application.

14. Define OHA and state goal of OHA


OHA is a business alliance that was created for the purpose of developing open mobile
device standards.

The Open Handset Alliance (OHA) is an association whose goal is to develop open
standards for mobile devices, promote innovation in mobile phones and provide a better
experience for consumers at a lower cost.

15. Define Android Virtual Devices


Android virtual device is a configuration that defines the charactersistics of an android
phone , table , wear os , android tv , or automotive os device that you want to simulate in
the android emulator.
The avd manager is an interface you can launch from android studio that helps you create
and mange AVDs.
16. State how the APK files are built?
To make an APK file, a program for Android is first compiled using a tool such as Android
Studio or Visual Studio and then all of its parts are packaged into one container file.

17. Enlist the elements of UI


Elements of UI.
EditText
TextView
ListView
GridView
ScrollView
ImageView
ToggleButton
CheckBox
RadioButton

OR

Components of UI
Menu Bar
Toolbar
Navigation Bar
Editor Tabs
Editor
Project Explorer
Status Bar
Tool Buttons

18. State the uses of Intent in Android


Android uses intent for communicating between the components of an application and
also from one application to another application it also provides the connectivity between
two apps

19. Name any four methods to get location data in android.


getLatitude() : Get the latitude in degrees.
getLongitude() : Get the longitude in degress.
distanceTo(Location dest) : Provides the app distance in meters
between the location.
getAccuracy() : Get the istimated accuracy of this location in meters.
getSpeed(): Get the speed if available in meters/second over ground.
Reset() : Clears the content of the location.

20. Explain significance of content provider.


1. Separates data from the app interface code.
2. Provides standard way of accessing data.
3. Make it possible for apps to share data with other apps
4. Content Providers are good.
5. Content providers are useful for the apps.

21. List any four features of Android operating system.


1. Beautiful UI
2. Connectivity
3. Storage
4. Multi Tough
5. Custom Roms
6. Automation
7. Widgets
8. Multi Language

22. Define Dalvik Virtual Machine (DVM)


The Dalvik Virtual Machine is an android virtual machine optimized for mobile devices.
It optimizes the virtual machine for memory, battery life, and performance.It is register
based.

23. List any four folders from directory structure of Android project and elaborate in one line.

24. List any four attributes of check box.


1.android:autoText
2.android:drawableBottom
3.android:drawableRight
4.android:text
5.android:editable

25. State syntax to display built in zoom control.


Built in Zoom control in Google map can be displayed with :
UiSettings.setZoomControlsEnabled(true);

26. Name two classes used to play audio and video in Android.
1.android.media.MediaPlayer class
2.android.widget.MediaController

Q2 4 MARKS QUESTION Q2

1. Describe android and importance of OHA


Google developed a mobile operating system based on Linux kernel called an Android
Operating System its designed for smartphones.
Android is an open source operating system and freely available those who wants to write
a code and build the operating system from it.

Importance of OHA is to develop open mobile device standards with the help of more than
80 companies including google , dell , Intel ,etc.

2. Explain Dalvik Virtual Machine and state it’s importance.


The Dalvik virtual machine (DVM) is an android virtual machine optimized for mobile
devices.
It optimizes the virtual machine for memory, battery life and performance.
The dex compiler converts the class file into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.
The javc tool compiles the java scource file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file.
Importance :
Importance of DVM is It optimizes the virtual machine for memory, battery life and
performance.

3. Describe process of getting the map API Key.


Visit the google cloud platform console.
Click the project drop down and create or select project for which you want to add an API
key.
Click the menu button and select APIs and Sevices Credentials
Create Credentials > Api Key //Api key will be displayed here.
Close

4. Explain multimedia framework in android


Android includes, a media playback engine at the native level that has built-in software-
based codecs for popular media formats

Audio and video playback features include integration with OpenMAX codecs, session
management, time- synchronized rendering, transport control, and DRM.

Stagefright also supports integration with custom hardware codecs provided by you. To set
a hardware path to encode and decode media, you must implement a hardware-based
codec as an OpenMax IL (Integration Layer) component.

5. Explain relative layout with all its attributes.


Android Relative Layout enables you to specify how child views are positioned relative to
each other. The position of each view can be specified as relative to sibling elements or
relative to the parent.
It can be declared like this :
<RelativeLayout
android:id="@+id/RLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
</RelativeLayout>

Relative Layout Attributes :


1. Android:id - This is the id which uniquely identifies the layout.
2. Android:gravity - This specifies how an object should position its content,
3. Android:ignoreGravity - This indicates what view should not be affected by gravity
4. Android:layout_above - Position the bottom edge of this view above the given anchor
view Id and must be a refference to another resource.
5. Android:layout_alignParentLeft - If true makes the left edge of this view match the left
edge of the parent.
6. Android:layout_alignParentRight - If true makes the left edge of this view match the
right edge of the parent.

6. Explore all steps to install Android studio and SDK.


Step 1 : System Requirement and java jdk5 or latest verison , jre 6 , android studio
softwares downloaded.
Step 2 : Setup android studio , for installation launch Android Studio.exe before launching
our machine should require installed java jdk.
Step 3 : Once you launched Android studio its time to mention JDK7 path or later version in
android studio installer.
Step 4 : After selecting jdk location then check the componets you want to install like
android sdk , android virtual device , performance , etc.
Step 5 : Need to specify the location of local machine path for android studio and android
sdk.
Step 6 : Need to specify ram space for android emulator by default it would take 512mb of
local machine RAM.
Step 7 : At final stage it would extract SDK packages into our local machine it will take time
and 2+gb space.
Step 8 : Finish.

7. Explain the need of Android Operating System. Also describe any four features of android.
Need of android operating system is :
1. Android market : Android market is the techno based and fastest growing market in the
world. You can effortlessly get almost any software you wish for in the android market.
2. Customization : Android offers the best in terms of end user experience mainly because
of the extent that one can customize his phone. Android is open source software.This
means anybody with programming skills can create applications for android device.
3. Rooting : Expansion of the scope of functionality of your phone and boosts its
performance multiple times over. By rooting devices makes it possible for you to change
system files in your devices and customize your device.
4. The android community : This is one of the major reason which define need of android is
the best decision you will ever make. The larger android comunnity provides you with the
necessary help and support for your device.

Features :
1) Beautiful UI : Android os basic screen provides a beautiful and intutive user interface.
2) Connectivity : WIFI , LTE , Bluetooth , CMDA , IDEN
3) Storage : SQLite a light weight relational database is used for data storage purpose.
4) Custom Roms : As android is open source developers can tweak the current os and
build their own versions.
5) Multi Language : Supports single direction and bi directional text.
8. Develop a program to add “Hello World” marker at (10,10) co-ordinates. Write only . java
file
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
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 com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

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

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
LatLng location = new LatLng(10, 10);
googleMap.addMarker(new MarkerOptions().position(location).title("Hello World"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
}
}

9. Explain features of Android SDK.


Android SDK is a collection of libraries and Software Development tools that are essential
for Developing Android Applications. Whenever Google releases a new version or update
of Android Software, a corresponding SDK also releases with it. In the updated or new
version of SDK, some more features are included which are not present in the previous
version. Android SDK consists of some tools which are very essential for the development
of Android Application.
1. Android Tool: This tool helps in managing the Android Virtual Device projects as well as
the installed components of the software development kit.
2. Emulator Tool: It helps us in testing the applications without the need of using the
application on an actual device.
3. Dalvik Debug Monitor Server(DDMS): DDMS is very useful for debugging the Android
Application.
4. Android Debug Bridge (ADB): It is a very versatile command-line tool and is helpful for
the communication between the developer and the Emulator or the Android device that is
Connected.

10. Explain the Android security model.


1. The Android security model is primarily based on a sandbox and permission
mechanism.
2. Each application is running in a specific Dalvik virtual machine with a unique user ID
assigned to it.Therefore, one application has not granted access to other applications’
files.
3. Android application has been signed with a certificate with a private key Know the
owner of the application is unique.
4. This allows the author of the application will be identified if needed.
5. This user ID is permanent on which devices and applications with the same user ID are
allowed to run in a single process.
Declaring and Using Permissions :

1. The purpose of a permission is to protect the privacy of an Android user. Android apps
must request permission to access sensitive user data (such as contacts and SMS), as well
as certain system features (such as camera and internet).
2. Depending on the feature, the system might grant the permission automatically or might
prompt the user to approve the request.

There are 3 types of permissions :


1. Normal permissions: Normal permissions cover areas where your app needs to access
data or resources outside the app’s sandbox, but where there’s very little risk to the user’s
privacy or the operation of other apps.
2. Signature permissions: The system grants these app permissions at install time, but only
when the app that attempts to use permission is signed by the same certificate as the app
that defines the permission.
3. Dangerous permissions: Dangerous permissions cover areas where the app wants data
or resources that involve the user’s private information, or could potentially affect the
user’s stored data or the operation of other apps.

11. Elaborate the need of permissions in Android. Explain the permissions to set system
functionalitics like SEND-SMS, bluetooth.
The purpose of a permission is to protect the privacy of an Android user. Android apps
must request permission to access sensitive user data (such as contacts and SMS), as well
as certain system features (such as camera and internet). Depending on the feature, the
system might grant the permission automatically or might prompt the user to approve the
request.

android. permission. SEND_SMS


Allows the app to send SMS messages. This may result in unexpected charges.
Malicious apps may cost you money by sending messages without your confirmation.

Following is the code snippet to set SEND_SMS permissions in manifest file.


<uses-permission android: name="android.permission.SEND_SMS"/>

android. permission. BLUETOOTH


You need to provide following permissions in AndroidManifest.xml file.
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

12. Describe Android architecture with diagram.


Pg no 1.6

13. Differentiate between DVM and JVM.


14. List and elaborate steps to deploy an Android application on Google play store.
Steps to deploy and Android Application on Google Play Store:

Step 1: Make a Developer Account : Before you can publish any app on Google Play, you
need to create a Developer Account. You can easily sign up for one using your existing
Google Account. You’ll need to pay a one-time registration fee of $25 using your
international credit or debit card.

Step 2: Plan to Sell? Link Your Merchant Account : If you want to publish a paid app or plan
to sell in-app purchases, you need to create a payments center profile, i.e. a merchant
account. A merchant account will let you manage your app sales and monthly payouts, as
well as analyze your sales reports right in your Play Console

Step 3: Create an App : Now you have create an application by clicking on 'Create
Application'.
Step 4: Prepare Store Listing : Before you can publish your app, you need to prepare its
store listing. These are all the details that will show up to customers on your app’s listing
on Google Play.

Step 5: Upload APK to an App Release : Finally upload your app, by uploading APK file.
Before you upload APK, you need to create an app release. You need to select the type of
release you want to upload your first app version to. You can choose between an internal
test, a closed test, an open test, and a production release. The first three releases allow
you to test out your app among a select group of users before you make it go live for
everyone to access.

Step 6: Provide an Appropriate Content Rating : If you don’t assign a rating to your app, it
will be listed as ‘Unrated’. Apps that are ‘Unrated’ may get removed from Google Play.

Step 7: Set Up Pricing & Distribution : Before you can fill out the details required in this
step, you need to determine your app’s monetization strategy. Once you know how your
app is going to make money, you can go ahead and set up your app as free or paid.

Step 8: Rollout Release to Publish Your App : The final step involves reviewing and rolling
out your release after making sure you’ve taken care of everything else. Before you review
and rollout your release, make sure the store listing, content rating, and pricing and
distribution sections of your app each have a green check mark next to them.

15. Describe with example, how to create a simple database in SQLite (Assume suitable data).
This procedure is by openOrCreateDatabase()
1. The package imported into the application is android.database.sqlite.SQLiteDatabase.
2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the database is
openOrCreateDatabse() method.

Program:

activity_main.xml

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="Create SQLite Database"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:id="@+id/button" />
</RelativeLayout>

MainActivity.java
package in.edu.vpt.insertusingasync;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabaseObj;
Button EnterData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createData = (Button)findViewById(R.id.button);
createData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
} });
}

16. State syntax to create Text View and Image button with any two attributes of each.
Text View:
Syntax :
<TextView
android:id="@+id/textView1"
android:layout_width="<width value>”
android:layout_height="<height_value>"
android:text="<text to be displayed>"/>

Attributes/Properties of TextView:
1. text: text attribute is used to set the text in a text view. We can set the text in xml as
well as in the java class.
2. textColor: textColor attribute is used to set the text color of a text view.
3. textSize: textSize attribute is used to set the size of text of a text view.
4. background: background attribute is used to set the background of a text view.
5. id: Supply an identifier name of this view, to later retrieve it with View.findViewByID()
or Activity.findViewById()
6. auto link: Controls whether links such as urls and email addresses are automatically
found and converted to clickable links.[flag]

ImageButton:
Syntax :
<ImageButton
android:id="@+id/imageButton"
android:layout_width="<width value>"
android:layout_height="<height value>"
app:srcCompat="<image source from drawable folder "/>

Attributes/Properties of ImageButton:
1. id: id is an attribute used to uniquely identify a image button.
2. src: src is an attribute used to set a source file of image
3. background: background attribute is used to set the background of an image button.
4. padding: padding attribute is used to set the padding from left, right, top or bottom of
the
ImageButton.

17. Describe Android service life cycle along with diagram.


The lifecycle of a service is simpler than that of an activity. Because a service has no UI,
services can continue to run in the background with no way for the user to know, even if
the user switches to another application. This consumes resources and drains battery.
Services are used for repetitive and potentially long running operations
Service can either be started or bound we just need to call either startService() or
bindService() from any of our android components.
1. Started : A service is started when an application component, such as an activity, starts it
by calling startService().
2. Bound : A service is bound when an application component binds to it by calling
bindService()
3. onCreate(): This is the first callback which will be invoked when any component starts
the service. If the same service is called again while it is still running this method wont be
invoked.
4. onStartCommand() /startSetvice() : This callback is invoked when service is started by
any component by calling startService().
5. onBind(): To provide binding for a service, you must implement the onBind() callback
method.
6. onUnbind() This is invoked when all the clients are disconnected from the service.
7. onRebind() This is invoked when new clients are connected to the service. It is called
after onRebind
8. onDestroy() This is a final clean up call from the system. This is invoked just before the
service is being destroyed.

18. State and elaborate the syntax of required class and methods for Geocoding.
Geocoder: A class for handling geocoding and reverse geocoding.
Finding the geographical cooridinates of a given address or location is called geocoding
And where a pair of longitude and latitude is converted into an address or location is called
as reverse geocoding.
The Geocoder class requires a backend service that is not included in the core android
framework

Syntax :
Geocoder (Context context)
Constructs a Geocoder localized for the default locale.
Geocoder(Context context, Locale locale)
Constructs a Geocoder localized for the given locale.

Methods with Syntax :

1. getFromLocation :
Syntax
public List<Address> getFromLocation (double latitude, double longitude, int
maxResults)

public void getFromLocation (double latitude, double longitude, int maxResults,


Geocoder.GeocodeListener listener)

This method returns an array of Addresses that attempt to describe the area
immediately surrounding the given latitude and longitude.

2. getFromLocationName :
Syntax :
public void getFromLocationName (String locationName, int maxResults,
Geocoder.GeocodeListener listener)

public List<Address> getFromLocationName (String locationName, int maxResults)

Returns an array of Addresses that attempt to describe the named location, which may
be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre
Parkway, Mountain View, CA", an airport code such as "SFO", The returned addresses
should be localized for the locale provided to this class's constructor.

3. isPresent
Syntax :

public static boolean isPresent ()

Returns true if there is a geocoder implementation present that may return results. If
true,
there is still no guarantee that any individual geocoding attempt will succeed.

19. Explain data and time picker with its method.


Date Picker:
In Android, DatePicker is a widget used to select a date. It allows to select date by day,
month
and year in our custom UI (user interface). If we need to show this view as a dialog then
we
have to use a DatePickerDialog class.
1. getDayOfMonth(): This method is used to get the selected day of the month from a date
picker. This method returns an integer value. DatePicker simpleDatePicker = (DatePicker)
findViewById(R.id.simpleDatePicker); int day = simpleDatePicker.getDayOfMonth();
2. getMonth(): This method is used to get the selected month from a date picker. This
method returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); int
month = simpleDatePicker.getMonth();

3. getYear(): This method is used to get the selected year from a date picker. This method
returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); int year =
simpleDatePicker.getYear();

4. getFirstDayOfWeek(): This method is used to get the first day of the week. This method
returns an integer value.
DatePicker simpleDatePicker = (DatePicker)findViewBy

TimePicker: In Android, TimePicker is a widget used for selecting the time of the day in
either AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and
clock format. If we need to show this view as a Dialog then we have to use a
TimePickerDialog class.

setCurrentHour(Integer currentHour): This method is used to set the current hours in a


time picker.

setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour). In this method there is only one parameter
of
integer type which is used to set the value for hours.
TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker);
simpleTimePicker.setCurrentHour(5);
simpleTimePicker.setHour(5);

getCurrentMinute(): This method is used to get the current minutes from a time picker.
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use getMinute(). This method returns an integer value.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
int minutes = simpleTimePicker.getCurrentMinute();
int minutes = simpleTimePicker.getMinute();

is24HourView(): This method is used to check the current mode of the time picker. This
method returns true if its 24 hour mode or false if AM/PM mode is set.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker);
Boolean mode=simpleTimePicker.is24HourView();

20. Explain the activity life cycle.


onCreate (): Called then the activity is created. Used to initialize the activity, for
example create the user interface.
onStart ():called when activity is becoming visible to the user.
onResume (): Called if the activity get visible again and the user starts interacting
with the activity again. Used to initialize fields, register listeners, bindto services, etc.
onPause (): Called once another activity gets into the foreground. Always called
before the activity is not visible anymore. Used to release resources or save application
data.
onStop (): Called once the activity is no longer visible. Time or CPU intensive shutdown
operations, such as writing information to a database should be down in the onStop()
method.
This method is guaranteed to be called as of API 11.
onDestroy (): called before the activity is destroyed.

21. Write an xml file to create login page using Table Layout
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<TableRow>
<EditText
android:id="@+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
</TableRow>

<TableRow>
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
</TableRow>

<TableRow>
<Button
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />
</TableRow>

</TableLayout>

22. Develop an application to display analog Time Picker. Also display the selected time. (Write
only . java file)
import android.app.Activity;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends Activity {

private TextView timeTextView;

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

timeTextView = findViewById(R.id.timeTextView);
Button pickTimeButton = findViewById(R.id.pickTimeButton);

pickTimeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get current time
final Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
int minute = currentTime.get(Calendar.MINUTE);

// Create a TimePickerDialog
TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int selectedHour, int
selectedMinute) {
// Display selected time
timeTextView.setText("Selected Time: " + selectedHour + ":" +
selectedMinute);
}
}, hour, minute, true);

// Show the TimePickerDialog


timePickerDialog.show();
}
});
}
}

23. Explain Gridview with its attributes with suitable example.


A GridView is a layout structure that allows you to arrange items in a grid-like fashion. Each
item in the grid is typically a view like an image, text, or even another layout.
The grid items are not necessarily predetermined but they automatically inserted to the
layout using a list adapter.
Grid view is the subclass of the AdapterView and they can be populated by binding them to
an adapter.

Attributes :

android:numColumns: This attribute specifies the number of columns in the grid.

android:columnWidth: Sets the width for each column in the grid.

android:verticalSpacing: Defines the vertical space between each grid item.

android:horizontalSpacing: Defines the horizontal space between each grid item.

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth" />

24. Explain text to speech conversion technique in android


In android, by using TextToSpeech class we can easily convert our text into voice and it
supports different type speaking languages. We can choose the speaking language based
on our requirements in android application.
Generally, the android Text To Speech instance can only be used to synthesize text once it
has completed its initialization so implement Text To Speech.
During the initialization, we can set the audio pitch rate, audio speed, type of language to
speak, etc. based on our requirements.

public class MainActivity extends AppCompatActivity implements TextToSpeech.


OnInitListener {

sem TextToSpeech textToSpeech;

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

int result = textToSpeech.setLanguage(Locale.US);

String text = speakText.getText().toString();

textToSpeech.speak (text,TextToSpeech.QUEUE_FLUSH, null, null);

}
}
.....
}

25. Develop an android application for Date and Time Picker.


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"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/btnPickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Date" />

<Button
android:id="@+id/btnPickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Time" />

<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Selected Date: " />

<TextView
android:id="@+id/tvTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Selected Time: " />

</LinearLayout>

JAVA :

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TextView tvDate, tvTime;

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

tvDate = findViewById(R.id.tvDate);
tvTime = findViewById(R.id.tvTime);

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


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

btnPickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickDate();
}
});

btnPickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pickTime();
}
});
}

private void pickDate() {


final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(this,


new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String date = dayOfMonth + "/" + (month + 1) + "/" + year;
tvDate.setText("Selected Date: " + date);
}
}, year, month, day);
datePickerDialog.show();
}

private void pickTime() {


final Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

TimePickerDialog timePickerDialog = new TimePickerDialog(this,


new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String time = hourOfDay + ":" + minute;
tvTime.setText("Selected Time: " + time);
}
}, hour, minute, true);
timePickerDialog.show();
}
}

27. Describe directory structure and its components


An android project is a combination of require files and folders which futher build a
directory to complete any android application.
The directory structure is a foundation of an android projects.
It acts like a container which holds the necessary logics , images , customization in its real
form.

Components :

1. /src : This is the most common folder in any android project. It contains our java source
code for android application.
2. /gen : This folder is created by IDE for configuration purpose. Under this folder we can
find 2 java files both files are auto generated.
3. /libs : This folder contains private libraries.
4. /res : This folder contains lots of required sub folder for the project.
5. /menu : For xml files that defines application menus.
6. /drawable : Under this folder we can store images for our project
7. /bin : this is the most imp folder in our directory structure as it contains
androidManifest.xml file.

28. Explain property animation method to animate the properties of view object with example.

29. Describe permissions required for android application development.


Skip : Skip : Skip
Normal Permissions: These permissions, like accessing the internet or controlling vibration,
are automatically granted upon installation. They pose minimal risk to user privacy or
device security.

Dangerous Permissions: These permissions, such as accessing location data or reading


contacts, require explicit user consent at runtime. They are considered high-risk and can be
revoked by users at any time.

Special Permissions: Special permissions, like drawing over other apps or installing
unknown apps, require additional user action through system settings. They are typically
used for specific system-level operations and are not granted automatically.

Best Practices: Developers should request permissions judiciously, explaining clearly why
each permission is necessary. They should also handle permission requests gracefully,
respecting user decisions and providing alternative functionality if permissions are denied.

30. Develop an android application to show current location of an user’s car.


XML LAYOUT :

<?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/tvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Location"
android:textSize="18sp"
android:layout_centerInParent="true"/>

</RelativeLayout>

JAVA :

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity {

private static final int LOCATION_PERMISSION_REQUEST_CODE = 100;


private TextView tvLocation;
private FusedLocationProviderClient fusedLocationClient;

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

tvLocation = findViewById(R.id.tvLocation);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

requestLocationPermission();
}

private void requestLocationPermission() {


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
} else {
fetchLastLocation();
}
}

private void fetchLastLocation() {


fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String coordinates = "Latitude: " + latitude + "\nLongitude: " + longitude;
tvLocation.setText(coordinates);
} else {
tvLocation.setText("Location not available");
}
}
});
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
} else {
tvLocation.setText("Location permission denied");
}
}
}
}

31. Develop an android application using radio button.

XML LAYOUT FILE :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/radioButtonOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />

<RadioButton
android:id="@+id/radioButtonOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />

<RadioButton
android:id="@+id/radioButtonOption3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3" />
</RadioGroup>
<Button
android:id="@+id/buttonShowSelection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selection" />

<TextView
android:id="@+id/textViewSelection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_marginTop="16dp"/>
</LinearLayout>

Java :

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

RadioGroup radioGroup = findViewById(R.id.radioGroup);


Button buttonShowSelection = findViewById(R.id.buttonShowSelection);
TextView textViewSelection = findViewById(R.id.textViewSelection);

buttonShowSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (selectedRadioButtonId != -1) {
RadioButton selectedRadioButton = findViewById(selectedRadioButtonId);
textViewSelection.setText("Selected Option: " + selectedRadioButton.getText());
} else {
textViewSelection.setText("Please select an option");
}
}
});
}
}
32. Develop an application to send and receive SMS. (Write only . java and permission tag in
manifest file)
Mainfest :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsdemo">

<uses-permission android:name="android.permission.SEND_SMS" />


<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

<application
... <!-- other app configurations -->
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

Java File :

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

private EditText editTextPhoneNumber, editTextMessage;


private Button buttonSend;

private BroadcastReceiver smsReceiver = new BroadcastReceiver() {


@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String senderPhoneNumber = smsMessage.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();

Toast.makeText(context, "SMS received from: " + senderPhoneNumber +


"\nMessage: " + messageBody,
Toast.LENGTH_LONG).show();
}
}
}
}
};

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

editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);

buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();
sendSMS(phoneNumber, message);
}
});
}

@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, filter);
}

@Override
protected void onPause() {
super.onPause();
unregisterReceiver(smsReceiver);
}

private void sendSMS(String phoneNumber, String message) {


if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.SEND_SMS}, 123);
return;
}

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "SMS Sent to " + phoneNumber, Toast.LENGTH_SHORT).show();
}
}

33. Explain the fundamentals of Ul design in detail.


Views:
he basic building block for user interface in Android is a View, which is created from the
View class and occupies a rectangular area on the screen and is responsible for drawing
and event handling.
Views are the base class for all visual interface elements.
Examples of widgets are buttons, text boxes, labels etc.

View Groups:
The ViewGroup is a subclass of View and provides invisible container that hold other Views
or other ViewGroups and define their layout properties.
A ViewGroup provides the layout in which we can order the appearance and sequence of
views.
Examples of ViewGroup are FrmaeLayout, LineourLayout etc.

Fragments:
Fragments represents a portion of user interface in an Activity.
Each Fragment includes its own user interface (UI) layout and receives the related input
events but is tightly bound to the activity into which each must be embedded. Fragments
are similar to UI view controller in iPhone development.

Activities:
Activities dictate the UI and handle the user interaction to the smart phone screen.
Activities represent a single screen that user interact.
Activities are the Android equivalent of Forms in traditional windows desktop
development.
34. Write a program to display a rectangular progress bar.
XML LAYOUT :

<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:padding="16dp"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_centerVertical="true"
android:indeterminate="false"
android:max="100"
android:progress="50"
android:progressDrawable="@drawable/rectangular_progress_bar" />

</RelativeLayout>

Rectangular_progress_bar.xml in the res/drawable :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<!-- Background for the progress bar -->


<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="@color/light_gray" />
</shape>
</item>

<!-- Progress of the progress bar -->


<item android:id="@android:id/progress">
<clip>
<shape android:shape="rectangle">
<solid android:color="@color/teal" />
</shape>
</clip>
</item>

</layer-list>

Colors :

<resources>
<color name="light_gray">#CCCCCC</color>
<color name="teal">#009688</color>
</resources>

35. Explain the procedure of Geo-coding and reverse Geo-coding.


Geo-Coding:
Finding the geographical cooridinates of a given address or location is called geocoding
Google Maps in Android supports this via the Geocoder class
The following code shows how we can find out the address of a location we have just
touched using the getFromLocation() method:

classMapOverlay extends com.google.android.maps.Overlay


{
@Override
publicboolean draw(Canvas canvas, MapViewmapView,
boolean shadow, long when)
{
//...
}
@Override
publicbooleanonTouchEvent(MotionEvent event, MapViewmapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (inti=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}

Reverse-geocoding:
where a pair of longitude and latitude is converted into an address or location is called as
reverse geocoding.
The following code shows how we can find the exact location of the Empire State Building
by using the getFromLocationName() method:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
"empire state building", 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}
36. Explain with example, code to create GUI using absolute layout (Assume suitable data)
AbsoluteLayout is based on the simple idea of placing each control at an absolute position.
We specify the exact x and y coordinates on the screen for each control. This is not
recommended for most UI development since absolutely positioning every element on the
screen makes an inflexible UI that is much more difficult to maintain.
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children.
Absolute layouts are less flexible and harder to maintain than other types of layouts
without absolute positioning. AbsoluteLayout is based on the simple idea of placing each
control at an absolute position.
We specify for the exact x and y corodinates on the screen for every control.

XML Layout (activity_main.xml):

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


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

<Button
android:id="@+id/button1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Button 1"
android:layout_x="50dp"
android:layout_y="100dp" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1"
android:layout_x="200dp"
android:layout_y="200dp" />

<EditText
android:id="@+id/editText1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Enter text"
android:layout_x="100dp"
android:layout_y="300dp" />

</AbsoluteLayout>

37. Write a program to demonstrate Date and Time picker.


Question No 25

38. Describe multimedia framework of Android with diagram


The android multimedia system includes multimedia applications, multimedia frameworks,
OpenCore engine and hardware abstract for audio/video input/output devices.
And the goal of the android multimedia framework is to provide a reliable interface for java
services. The multimedia framework consists of several core dynamic libraries.
Java classes call the Native C library Libmedia through Java JNI.
Libmedia library communications with Media Server guard process through Android’s
Binder IPc Mechanism
Media Server process creates the corresponding multimedia service according to the Java
multimedia applications.
The whole communication between Libmedia and Media Server forms a Client/Server
model

39. Discuss developer console with at least four features


All Applications :
It displays all the application that you have publish

Your Account Details.

Your Developer Profile contains :


Developer name- displayed on the store listing page and elesewere on google play.
Contact info : used by google only
Website url : displayed on store listing page

Multiple user account :


Set up user account for other team members to asses different parts of your developer
controls.

Storel isitng details :


Use the developer console to setup store listing page. This is the home for your app in
google play. It is the page users see on their mobile phones or on the web to learn about
your app and download it.

40. Write a program to demonstrate declaring and using permissions with any relevant
example.

Q3 6 MARKS QUESTIONS :

1. Design a employee registration form using UI component.


XML FILE :

<?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:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="text" />

<EditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:layout_marginTop="16dp"
android:hint="Email"
android:inputType="textEmailAddress" />

<EditText
android:id="@+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextEmail"
android:layout_marginTop="16dp"
android:hint="Phone"
android:inputType="phone" />

<Button
android:id="@+id/buttonRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhone"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="Register" />

</RelativeLayout>

JAVA FILE :

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextName, editTextEmail, editTextPhone;


private Button buttonRegister;

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

editTextName = findViewById(R.id.editTextName);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPhone = findViewById(R.id.editTextPhone);
buttonRegister = findViewById(R.id.buttonRegister);

buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registerEmployee();
}
});
}

private void registerEmployee() {


String name = editTextName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String phone = editTextPhone.getText().toString().trim();

if (name.isEmpty() || email.isEmpty() || phone.isEmpty()) {


Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
} else {
// Perform registration process (e.g., send data to server)
// Here, we'll just display a toast message with the entered data
String message = "Name: " + name + "\nEmail: " + email + "\nPhone: " + phone;
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}

2. Develop an android application for taking student feedback with database connectivity
XML Layout for Feedback Form :

<?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:padding="16dp">

<TextView
android:id="@+id/textViewFeedback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Your Feedback:"
android:textSize="18sp"
android:layout_marginTop="16dp"/>

<EditText
android:id="@+id/editTextFeedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewFeedback"
android:layout_marginTop="8dp"
android:inputType="textMultiLine"
android:minLines="5"
android:hint="Write your feedback here..." />

<Button
android:id="@+id/buttonSubmitFeedback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Feedback"
android:layout_below="@id/editTextFeedback"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

</RelativeLayout>

XML Layout for Displaying Feedback :

<?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:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/textViewFeedbackTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feedback List"
android:textSize="20sp"
android:layout_marginBottom="16dp"/>

<ListView
android:id="@+id/listViewFeedback"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>

<Button
android:id="@+id/buttonRefresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"
android:layout_marginTop="16dp"
android:layout_gravity="center_horizontal"/>

</LinearLayout>

Java Code for Database Helper :

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "feedback.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_FEEDBACK = "feedback";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FEEDBACK_TEXT = "feedback_text";

private static final String CREATE_TABLE_FEEDBACK = "CREATE TABLE " +


TABLE_FEEDBACK + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FEEDBACK_TEXT + " TEXT);";

public DBHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_FEEDBACK);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FEEDBACK);
onCreate(db);
}
}

Java Code for Feedback Activity :

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class FeedbackActivity extends AppCompatActivity {

private EditText editTextFeedback;


private Button buttonSubmitFeedback;
private DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
dbHelper = new DBHelper(this);

editTextFeedback = findViewById(R.id.editTextFeedback);
buttonSubmitFeedback = findViewById(R.id.buttonSubmitFeedback);

buttonSubmitFeedback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveFeedback();
}
});
}

private void saveFeedback() {


String feedbackText = editTextFeedback.getText().toString().trim();

if (feedbackText.isEmpty()) {
Toast.makeText(this, "Please enter your feedback", Toast.LENGTH_SHORT).show();
return;
}

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_FEEDBACK_TEXT, feedbackText);

long newRowId = db.insert(DBHelper.TABLE_FEEDBACK, null, values);

if (newRowId != -1) {
Toast.makeText(this, "Feedback submitted successfully",
Toast.LENGTH_SHORT).show();
editTextFeedback.setText("");
} else {
Toast.makeText(this, "Failed to submit feedback", Toast.LENGTH_SHORT).show();
}

db.close();
}
}

Java Code for Display Feedback Activity :

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import androidx.appcompat.app.AppCompatActivity;

public class DisplayFeedbackActivity extends AppCompatActivity {

private ListView listViewFeedback;


private Button buttonRefresh;
private DBHelper dbHelper;

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

dbHelper = new DBHelper(this);

listViewFeedback = findViewById(R.id.listViewFeedback);
buttonRefresh = findViewById(R.id.buttonRefresh);

buttonRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshFeedbackList();
}
});

refreshFeedbackList();
}

private void refreshFeedbackList() {


SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(DBHelper.TABLE_FEEDBACK,
new String[]{DBHelper.COLUMN_ID, DBHelper.COLUMN_FEEDBACK_TEXT},
null, null, null, null, null);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,


android.R.layout.simple_list_item_1,
cursor,
new String[]{DBHelper.COLUMN_FEEDBACK_TEXT},
new int[]{android.R.id.text1},
0);

listViewFeedback.setAdapter(adapter);
}
}

3. Explain Geocoding and Reverse Geocoding with suitable example


REFER Q.35 OF 4 MARKS

4. Design an android application to show the list of paired devices by Bluetooth.


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:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/buttonListDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List Paired Devices" />

<ListView
android:id="@+id/listViewPairedDevices"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="16dp"
android:visibility="gone" />

</LinearLayout>
JAVA :

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

private BluetoothAdapter bluetoothAdapter;


private ListView listViewPairedDevices;
private ArrayAdapter<String> pairedDevicesArrayAdapter;

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

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
finish();
}

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


listViewPairedDevices = findViewById(R.id.listViewPairedDevices);
pairedDevicesArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1);
listViewPairedDevices.setAdapter(pairedDevicesArrayAdapter);
buttonListDevices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listPairedDevices();
}
});
}

private void listPairedDevices() {


if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Bluetooth is not enabled", Toast.LENGTH_SHORT).show();
return;
}

Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();


if (pairedDevices.size() > 0) {
listViewPairedDevices.setVisibility(View.VISIBLE);
pairedDevicesArrayAdapter.clear();
for (BluetoothDevice device : pairedDevices) {
pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
Toast.makeText(this, "No paired devices found", Toast.LENGTH_SHORT).show();
listViewPairedDevices.setVisibility(View.GONE);
}
}
}

5. Develop an android application for sending Short Message Service (SMS).


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:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Message"
android:inputType="textMultiLine"
android:minLines="5" />
<Button
android:id="@+id/buttonSendSMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send SMS"
android:layout_marginTop="16dp" />

</LinearLayout>

JAVA :

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

private static final int PERMISSION_SEND_SMS = 1;


private EditText editTextPhoneNumber, editTextMessage;
private Button buttonSendSMS;

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

editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSendSMS = findViewById(R.id.buttonSendSMS);

buttonSendSMS.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendSMS();
}
});
}

private void sendSMS() {


String phoneNumber = editTextPhoneNumber.getText().toString().trim();
String message = editTextMessage.getText().toString().trim();

if (phoneNumber.isEmpty() || message.isEmpty()) {
Toast.makeText(this, "Please enter phone number and message",
Toast.LENGTH_SHORT).show();
return;
}

// Check if permission to send SMS is granted


if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
// Request permission if not granted
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS}, PERMISSION_SEND_SMS);
} else {
// Permission already granted, send SMS
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "SMS sent", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_SEND_SMS) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, send SMS
sendSMS();
} else {
// Permission denied
Toast.makeText(this, "Permission denied to send SMS",
Toast.LENGTH_SHORT).show();
}
}
}
}

6. Explain how linear and frame layout is used to design an android application with suitable
example

Linear and Frame layouts are two fundamental layout types in Android used to arrange UI
components.
Linear Layout:
Linear layout arranges its children elements in a single direction, either horizontally or
vertically. Each child is placed next to or below the previous one in the layout. It's
particularly useful for creating simple user interfaces with a linear arrangement.

Example XML for a simple Linear Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />

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

</LinearLayout>

Frame Layout:
Frame layout is designed to block out an area on the screen to display a single item. It's
typically used for fragments or displaying a single view at a time.

Example XML for a simple Frame Layout:

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

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overlay text"
android:textSize="24sp"
android:layout_gravity="center" />

</FrameLayout>

7. Develop a program to perform addition, subtraction, division, multiplication of two


numbers and display the result. (Use appropriate UI controls)
XML Layout :

<?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:padding="16dp">

<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number 1"
android:inputType="numberDecimal" />

<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber1"
android:layout_marginTop="16dp"
android:hint="Enter number 2"
android:inputType="numberDecimal" />

<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber2"
android:layout_marginTop="16dp"
android:text="Add" />

<Button
android:id="@+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonAdd"
android:layout_marginTop="8dp"
android:text="Subtract" />

<Button
android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSubtract"
android:layout_marginTop="8dp"
android:text="Multiply" />

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonMultiply"
android:layout_marginTop="8dp"
android:text="Divide" />

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonDivide"
android:layout_marginTop="16dp"
android:text="Result:"
android:textSize="18sp" />

</RelativeLayout>
Java Code :

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber1, editTextNumber2;


private Button buttonAdd, buttonSubtract, buttonMultiply, buttonDivide;
private TextView textViewResult;

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

editTextNumber1 = findViewById(R.id.editTextNumber1);
editTextNumber2 = findViewById(R.id.editTextNumber2);
buttonAdd = findViewById(R.id.buttonAdd);
buttonSubtract = findViewById(R.id.buttonSubtract);
buttonMultiply = findViewById(R.id.buttonMultiply);
buttonDivide = findViewById(R.id.buttonDivide);
textViewResult = findViewById(R.id.textViewResult);

buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation('+');
}
});

buttonSubtract.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation('-');
}
});

buttonMultiply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation('*');
}
});

buttonDivide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation('/');
}
});
}

private void performOperation(char operation) {


String num1Str = editTextNumber1.getText().toString().trim();
String num2Str = editTextNumber2.getText().toString().trim();

if (num1Str.isEmpty() || num2Str.isEmpty()) {
textViewResult.setText("Please enter both numbers");
return;
}

double num1 = Double.parseDouble(num1Str);


double num2 = Double.parseDouble(num2Str);
double result = 0;

switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
textViewResult.setText("Cannot divide by zero");
return;
}
break;
}

textViewResult.setText("Result: " + result);


}
}

8. Develop an application to display a Google Map. (Write JAVA and Manifest file)
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtain the MapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
// Add markers, polylines, polygons, etc., as needed.
// For now, let's just display the map.
}
}

MANIFEST FILE :

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapexample">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!-- Google Maps API Key -->


<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY_HERE" />

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

<!-- Add Google Play services metadata -->


<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

</application>

</manifest>

9. Develop an application to convert “thanks” text to speech as given in the following GUI.
XML LAYOUT :

<?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:padding="16dp">

<Button
android:id="@+id/buttonSpeak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:layout_centerInParent="true"/>

</RelativeLayout>

JAVA :

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private TextToSpeech textToSpeech;

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

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

// Initialize TextToSpeech object


textToSpeech = new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
// Set language to English
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});

// Set onClickListener for the speak button


buttonSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speak();
}
});
}

private void speak() {


// Convert text to speech
textToSpeech.speak("Thanks", TextToSpeech.QUEUE_FLUSH, null, null);
}

@Override
protected void onDestroy() {
// Shutdown TextToSpeech when the activity is destroyed
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
}

10. Develop an application to update a record of an employee whose emp.id is ‘E101’ in SQlite
database. Change employee name from “PQR” to “XYZ”. Also display the updated record.
(Write .java and .xml files)
JAVA :

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private DBHelper dbHelper;


private TextView textViewResult;

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

dbHelper = new DBHelper(this);


textViewResult = findViewById(R.id.textViewResult);
Button buttonUpdate = findViewById(R.id.buttonUpdate);

buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateRecord();
}
});
}

private void updateRecord() {


SQLiteDatabase db = dbHelper.getWritableDatabase();

// Update record
String updateQuery = "UPDATE " + DBHelper.TABLE_EMPLOYEE +
" SET " + DBHelper.COLUMN_NAME + " = 'XYZ' " +
" WHERE " + DBHelper.COLUMN_ID + " = 'E101'";

db.execSQL(updateQuery);

// Display updated record


String selectQuery = "SELECT * FROM " + DBHelper.TABLE_EMPLOYEE +
" WHERE " + DBHelper.COLUMN_ID + " = 'E101'";
Cursor cursor = db.rawQuery(selectQuery, null);

if (cursor != null && cursor.moveToFirst()) {


String empId = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String empName =
cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
String empDept =
cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DEPARTMENT));

String result = "Emp ID: " + empId + "\n" +


"Emp Name: " + empName + "\n" +
"Emp Department: " + empDept;

textViewResult.setText("Updated Record:\n" + result);


cursor.close();
} else {
textViewResult.setText("No record found with ID 'E101'");
}

db.close();
}
}

SQLite Database Helper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "employee.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_EMPLOYEE = "employee";
public static final String COLUMN_ID = "emp_id";
public static final String COLUMN_NAME = "emp_name";
public static final String COLUMN_DEPARTMENT = "emp_department";
private static final String CREATE_TABLE_EMPLOYEE = "CREATE TABLE " +
TABLE_EMPLOYEE + " (" +
COLUMN_ID + " TEXT PRIMARY KEY, " +
COLUMN_NAME + " TEXT, " +
COLUMN_DEPARTMENT + " TEXT);";

public DBHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_EMPLOYEE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EMPLOYEE);
onCreate(db);
}
}

11. Write steps for customized permissions

12. Develop a program to TURN ON and OFF bluetooth. Write .java file and permission tags
JAVA :

import android.bluetooth.BluetoothAdapter;
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 {

private BluetoothAdapter bluetoothAdapter;

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

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Button buttonTurnOn = findViewById(R.id.buttonTurnOn);
Button buttonTurnOff = findViewById(R.id.buttonTurnOff);

buttonTurnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
turnOnBluetooth();
}
});
buttonTurnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
turnOffBluetooth();
}
});
}

private void turnOnBluetooth() {


if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device",
Toast.LENGTH_SHORT).show();
} else {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Toast.makeText(this, "Bluetooth turned on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Bluetooth is already turned on",
Toast.LENGTH_SHORT).show();
}
}
}

private void turnOffBluetooth() {


if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device",
Toast.LENGTH_SHORT).show();
} else {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(this, "Bluetooth turned off", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Bluetooth is already turned off",
Toast.LENGTH_SHORT).show();
}
}
}
}

MANIFEST :

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothcontrol">

<uses-permission android:name="android.permission.BLUETOOTH" />


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

13. Develop a program to send and receive an Email.


import android.os.AsyncTask;
import android.os.Bundle;
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 java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "EmailExample";

private EditText editTextTo, editTextSubject, editTextMessage;


private Button buttonSend;

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

editTextTo = findViewById(R.id.editTextTo);
editTextSubject = findViewById(R.id.editTextSubject);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);

buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
}

private void sendEmail() {


final String to = editTextTo.getText().toString().trim();
final String subject = editTextSubject.getText().toString().trim();
final String message = editTextMessage.getText().toString().trim();

if (to.isEmpty() || subject.isEmpty() || message.isEmpty()) {


Toast.makeText(MainActivity.this, "Please fill in all fields",
Toast.LENGTH_SHORT).show();
return;
}

// Configure mail server properties


Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

// Set up authenticator
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_email@gmail.com",
"your_password");
}
});

// Create email message


MimeMessage mimeMessage = new MimeMessage(session);
try {
mimeMessage.setFrom(new InternetAddress("your_email@gmail.com"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);

// Send email asynchronously


new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Transport.send(mimeMessage);
} catch (MessagingException e) {
Log.e(TAG, "Error sending email", e);
}
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(MainActivity.this, "Email sent", Toast.LENGTH_SHORT).show();
}
}.execute();

} catch (MessagingException e) {
Log.e(TAG, "Error creating email", e);
}
}
}

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:padding="16dp">

<EditText
android:id="@+id/editTextTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To" />

<EditText
android:id="@+id/editTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextTo"
android:layout_marginTop="16dp"
android:hint="Subject" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextSubject"
android:layout_marginTop="16dp"
android:hint="Message"
android:inputType="textMultiLine"
android:minLines="5" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMessage"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Send" />

</RelativeLayout>
USER PERMISION :

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

14. Develop a program for providing bluetooth connectivity.


MANIFEST :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth">

<uses-permission android:name="android.permission.BLUETOOTH" />


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

JAVA :

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

private BluetoothAdapter bluetoothAdapter;


private ArrayList<String> pairedDeviceList = new ArrayList<>();
private ArrayAdapter<String> arrayAdapter;

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

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ListView listViewPairedDevices = findViewById(R.id.listViewPairedDevices);
Button buttonEnableBluetooth = findViewById(R.id.buttonEnableBluetooth);

arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,


pairedDeviceList);
listViewPairedDevices.setAdapter(arrayAdapter);

buttonEnableBluetooth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enableBluetooth();
}
});

if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device",
Toast.LENGTH_SHORT).show();
buttonEnableBluetooth.setEnabled(false);
} else {
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 1);
}
listPairedDevices();
}
}

private void enableBluetooth() {


if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 1);
} else {
Toast.makeText(this, "Bluetooth is already enabled", Toast.LENGTH_SHORT).show();
}
}

private void listPairedDevices() {


Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDeviceList.add(device.getName() + "\n" + device.getAddress());
}
arrayAdapter.notifyDataSetChanged();
}
}
}

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:padding="16dp">

<Button
android:id="@+id/buttonEnableBluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Bluetooth"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

<ListView
android:id="@+id/listViewPairedDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/buttonEnableBluetooth"
android:layout_marginTop="16dp"/>

</RelativeLayout>

15. Develop a program to implement i) List view of 5 items ii) Grid view of 4 x 4 items iii) Image
view.

16. Develop an application to store customer's details like, customer-id, customer-name,


mobile number, address, pin-code and retrieve customer information using customer-id in
SQLite databases.
DATABESE :

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "customer.db";


private static final int DATABASE_VERSION = 1;

public static final String TABLE_CUSTOMER = "customer";


public static final String COLUMN_ID = "customer_id";
public static final String COLUMN_NAME = "customer_name";
public static final String COLUMN_MOBILE = "mobile_number";
public static final String COLUMN_ADDRESS = "address";
public static final String COLUMN_PIN_CODE = "pin_code";

private static final String CREATE_TABLE_CUSTOMER = "CREATE TABLE " +


TABLE_CUSTOMER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_MOBILE + " TEXT, " +
COLUMN_ADDRESS + " TEXT, " +
COLUMN_PIN_CODE + " TEXT);";

public DBHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CUSTOMER);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CUSTOMER);
onCreate(db);
}
}

JAVVA :

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextID, editTextName, editTextMobile, editTextAddress,


editTextPinCode;
private TextView textViewResult;
private DBHelper dbHelper;

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

editTextID = findViewById(R.id.editTextID);
editTextName = findViewById(R.id.editTextName);
editTextMobile = findViewById(R.id.editTextMobile);
editTextAddress = findViewById(R.id.editTextAddress);
editTextPinCode = findViewById(R.id.editTextPinCode);
textViewResult = findViewById(R.id.textViewResult);
dbHelper = new DBHelper(this);

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


buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addCustomer();
}
});

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


buttonRetrieve.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
retrieveCustomer();
}
});
}

private void addCustomer() {


SQLiteDatabase db = dbHelper.getWritableDatabase();

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


String mobile = editTextMobile.getText().toString();
String address = editTextAddress.getText().toString();
String pinCode = editTextPinCode.getText().toString();

ContentValues values = new ContentValues();


values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_MOBILE, mobile);
values.put(DBHelper.COLUMN_ADDRESS, address);
values.put(DBHelper.COLUMN_PIN_CODE, pinCode);

long newRowId = db.insert(DBHelper.TABLE_CUSTOMER, null, values);

if (newRowId != -1) {
Toast.makeText(this, "Customer added with ID: " + newRowId,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Error adding customer", Toast.LENGTH_SHORT).show();
}

db.close();
}

private void retrieveCustomer() {


SQLiteDatabase db = dbHelper.getReadableDatabase();

String id = editTextID.getText().toString();

String[] projection = {
DBHelper.COLUMN_NAME,
DBHelper.COLUMN_MOBILE,
DBHelper.COLUMN_ADDRESS,
DBHelper.COLUMN_PIN_CODE
};

String selection = DBHelper.COLUMN_ID + " = ?";


String[] selectionArgs = { id };

Cursor cursor = db.query(


DBHelper.TABLE_CUSTOMER,
projection,
selection,
selectionArgs,
null,
null,
null
);

if (cursor.moveToFirst()) {
String name =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_NAME));
String mobile =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_MOBILE));
String address =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_ADDRESS));
String pinCode =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_PIN_CODE));

String result = "Name: " + name + "\n" +


"Mobile: " + mobile + "\n" +
"Address: " + address + "\n" +
"Pin Code: " + pinCode;

textViewResult.setText(result);
} else {
textViewResult.setText("No customer found with ID: " + id);
}

cursor.close();
db.close();
}
}

LAYOUT :

<?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:padding="16dp">

<EditText
android:id="@+id/editTextID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Customer ID"
android:inputType="number" />

<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextID"
android:layout_marginTop="16dp"
android:hint="Name" />

<EditText
android:id="@+id/editTextMobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:layout_marginTop="16dp"
android:hint="Mobile Number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMobile"
android:layout_marginTop="16dp"
android:hint="Address" />

<EditText
android:id="@+id/editTextPinCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextAddress"
android:layout_marginTop="16dp"
android:hint="Pin Code"
android:inputType="number" />

<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPinCode"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Add Customer" />

<Button
android:id="@+id/buttonRetrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonAdd"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Retrieve Customer" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonRetrieve"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text=""
android:textSize="18sp" />

</RelativeLayout>

17. Write a program to find the direction from user's current location to MSBTE, Bandra.
(Write only Java and manitest file).
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;

private TextView textViewDirection;

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

textViewDirection = findViewById(R.id.textViewDirection);

// Check for location permission


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
} else {
// Permission already granted, start getting direction
getDirection();
}
}

private void getDirection() {


// Create a Geocoder object to convert location to address
Geocoder geocoder = new Geocoder(this, Locale.getDefault());

// MSBTE, Bandra location coordinates


double msbteLatitude = 19.055899;
double msbteLongitude = 72.834548;

// Get current location


try {
Location currentLocation = getCurrentLocation();
if (currentLocation != null) {
// Convert current location to address
List<Address> addresses =
geocoder.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String currentAddress = address.getAddressLine(0);
// Calculate direction
float[] results = new float[1];
Location.distanceBetween(currentLocation.getLatitude(),
currentLocation.getLongitude(),
msbteLatitude, msbteLongitude, results);
float distance = results[0];
String direction = "Distance to MSBTE, Bandra from your location (" +
currentAddress + "): " +
distance + " meters.";
textViewDirection.setText(direction);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

private Location getCurrentLocation() {


// This is a dummy method, you should implement your logic to get current location
// For simplicity, assume current location is available
Location location = new Location("dummy");
location.setLatitude(19.075983);
location.setLongitude(72.877655);
return location;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, start getting direction
getDirection();
} else {
// Permission denied, show a message
Toast.makeText(this, "Location permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
}

MANIFEST :

<?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:padding="16dp">

<TextView
android:id="@+id/textViewDirection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="18sp" />

</RelativeLayout>

18. Develop a simple calculator using relative layout.


JAVA :

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView textViewResult;


private StringBuilder input = new StringBuilder();

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

textViewResult = findViewById(R.id.textViewResult);
Button buttonClear = findViewById(R.id.buttonClear);
Button buttonEqual = findViewById(R.id.buttonEqual);

buttonClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearInput();
}
});

buttonEqual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
calculate();
}
});
}

public void onClickNumber(View view) {


Button button = (Button) view;
input.append(button.getText());
updateInput();
}

public void onClickOperator(View view) {


Button button = (Button) view;
input.append(" ").append(button.getText()).append(" ");
updateInput();
}

private void updateInput() {


textViewResult.setText(input.toString());
}

private void clearInput() {


input.setLength(0);
updateInput();
}

private void calculate() {


String expression = input.toString();
String[] parts = expression.split(" ");
if (parts.length != 3) {
textViewResult.setText("Invalid expression");
return;
}
double operand1 = Double.parseDouble(parts[0]);
double operand2 = Double.parseDouble(parts[2]);
double result;
switch (parts[1]) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
textViewResult.setText("Cannot divide by zero");
return;
}
result = operand1 / operand2;
break;
default:
textViewResult.setText("Invalid operator");
return;
}
textViewResult.setText(String.valueOf(result));
input.setLength(0);
input.append(result);
}
}

LAYOUT :

<?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:padding="16dp">

<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginBottom="16dp"
android:background="@android:color/darker_gray"
android:gravity="end"
android:padding="8dp"
android:textSize="24sp" />

<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textViewResult"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="C"
android:onClick="onClickClear"
android:layout_alignParentEnd="true"/>

<Button
android:id="@+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textViewResult"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="/"
android:onClick="onClickOperator"
android:layout_toStartOf="@id/buttonClear"
android:layout_alignParentEnd="true"/>

<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textViewResult"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="7"
android:onClick="onClickNumber"
android:layout_toStartOf="@id/buttonDivide"
android:layout_alignParentEnd="true"/>

<!-- Buttons for other numbers, operators, and equals -->

</RelativeLayout>

19. Write a program to convert temperature from celcius to farenhite and vice versa using
Toggle button. (Design UI as per your choice. Write XML and java file)
JAVA :

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextTemperature;


private TextView textViewResult;
private ToggleButton toggleButtonUnit;

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

editTextTemperature = findViewById(R.id.editTextTemperature);
textViewResult = findViewById(R.id.textViewResult);
toggleButtonUnit = findViewById(R.id.toggleButtonUnit);

toggleButtonUnit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
convertTemperature();
}
});
}

private void convertTemperature() {


double temperature = Double.parseDouble(editTextTemperature.getText().toString());
boolean isCelsius = toggleButtonUnit.isChecked();
double result;

if (isCelsius) {
// Convert Celsius to Fahrenheit
result = (temperature * 9 / 5) + 32;
textViewResult.setText(temperature + " °C = " + result + " °F");
} else {
// Convert Fahrenheit to Celsius
result = (temperature - 32) * 5 / 9;
textViewResult.setText(temperature + " °F = " + result + " °C");
}
}
}

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:padding="16dp">

<EditText
android:id="@+id/editTextTemperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter temperature"
android:inputType="numberDecimal"
android:layout_marginBottom="16dp" />

<ToggleButton
android:id="@+id/toggleButtonUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="°C"
android:textOn="°F"
android:checked="true"
android:layout_below="@id/editTextTemperature"
android:layout_marginBottom="16dp" />

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:layout_below="@id/toggleButtonUnit" />

</RelativeLayout>

20. Write a program to capture an image using camera and display it.
MANIFEST :

<uses-permission android:name="android.permission.CAMERA" />


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

LAYOUT :

<?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:padding="16dp">

<Button
android:id="@+id/buttonCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp" />

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/buttonCapture"
android:layout_marginTop="16dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:visibility="gone" />

</RelativeLayout>

JAVA :

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private static final int REQUEST_IMAGE_CAPTURE = 1;


private ImageView imageView;
private Button buttonCapture;

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

imageView = findViewById(R.id.imageView);
buttonCapture = findViewById(R.id.buttonCapture);

buttonCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}

private void dispatchTakePictureIntent() {


Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
imageView.setVisibility(View.VISIBLE);
}
}
}

21. Develop and application to send and receive SMS (Design minimal UI as per your choice.
Write XML, java and manifest file)
MANIFEST :

<uses-permission android:name="android.permission.SEND_SMS" />


<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

LAYOUT :

<?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:padding="16dp">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginTop="16dp"
android:hint="Message" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMessage"
android:layout_marginTop="16dp"
android:text="Send" />

<Button
android:id="@+id/buttonReceive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginTop="16dp"
android:text="Receive" />

</RelativeLayout>

JAVA :

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {

private EditText editTextPhoneNumber, editTextMessage;


private Button buttonSend, buttonReceive;

private BroadcastReceiver smsReceiver = new BroadcastReceiver() {


@Override
public void onReceive(Context context, Intent intent) {
// Display received SMS
Toast.makeText(context, "SMS Received: " + intent.getStringExtra("sms_body"),
Toast.LENGTH_SHORT).show();
}
};

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

editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);
buttonReceive = findViewById(R.id.buttonReceive);

// Register receiver for SMS


registerReceiver(smsReceiver, new
IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

buttonSend.setOnClickListener(v -> {
String phoneNumber = editTextPhoneNumber.getText().toString();
String message = editTextMessage.getText().toString();
sendSMS(phoneNumber, message);
});

buttonReceive.setOnClickListener(v -> {
// Request permissions if not granted
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.RECEIVE_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.RECEIVE_SMS}, 1);
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
// Unregister receiver
unregisterReceiver(smsReceiver);
}

private void sendSMS(String phoneNumber, String message) {


try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Failed to send SMS",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}

22. Write a program to implement Android Activity Life Cycle. Use toast messages to display
message through life cycle
JAVA :

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onStart() {
super.onStart();
showToast("onStart()");
}

@Override
protected void onResume() {
super.onResume();
showToast("onResume()");
}

@Override
protected void onPause() {
super.onPause();
showToast("onPause()");
}

@Override
protected void onStop() {
super.onStop();
showToast("onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
showToast("onDestroy()");
}

@Override
protected void onRestart() {
super.onRestart();
showToast("onRestart()");
}

private void showToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
Log.d("Lifecycle", message);
}
}

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:padding="16dp"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Lifecycle Demo"
android:textSize="24sp"
android:textStyle="bold"
android:layout_centerInParent="true" />

</RelativeLayout>

24. Develop an application to display Google map with user's current location.
PERMISSION :

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

API key :

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />

LAYOUT :

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


<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".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.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 com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;


private GoogleMap mMap;

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

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
}
}
}

25. Design UI using table layout to display buttons with 0 9 numbers on it. Even display submit
and clear button. When user clicks on particular buttons and later when clicks on submit
button, it should display the numbers clicked.
XML :

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- Row 1 -->


<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">

<Button
android:id="@+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />

</TableRow>
<!-- Row 2 -->
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />

</TableRow>

<!-- Row 3 -->


<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">

<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6" />

<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7" />

<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />

</TableRow>

<!-- Row 4 -->


<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">

<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9" />

<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />

<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear" />

</TableRow>

</TableLayout>

JAVA :

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private List<String> numbersClicked;


private TextView textViewNumbersClicked;

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

numbersClicked = new ArrayList<>();


textViewNumbersClicked = findViewById(R.id.textViewNumbersClicked);

// Set click listeners for number buttons


setNumberButtonClickListeners();

// Set click listener for Submit button


Button buttonSubmit = findViewById(R.id.buttonSubmit);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submitNumbers();
}
});

// Set click listener for Clear button


Button buttonClear = findViewById(R.id.buttonClear);
buttonClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearNumbersClicked();
}
});
}

private void setNumberButtonClickListeners() {


for (int i = 0; i <= 9; i++) {
int buttonId = getResources().getIdentifier("button" + i, "id", getPackageName());
Button button = findViewById(buttonId);
final String number = String.valueOf(i);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNumberClicked(number);
}
});
}
}

private void addNumberClicked(String number) {


numbersClicked.add(number);
updateNumbersClickedTextView();
}

private void updateNumbersClickedTextView() {


StringBuilder stringBuilder = new StringBuilder();
for (String number : numbersClicked) {
stringBuilder.append(number).append(" ");
}
textViewNumbersClicked.setText(stringBuilder.toString());
}

private void submitNumbers() {


// Handle submission of numbers (You can perform any action here)
// For now, just display the numbers clicked in a toast message
String message = "Numbers clicked: " + numbersClicked.toString();
// You can replace this toast message with your desired action
// For example, sending the numbers to a server, saving them to a database, etc.
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

private void clearNumbersClicked() {


numbersClicked.clear();
textViewNumbersClicked.setText("");
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy