0% found this document useful (0 votes)
10 views81 pages

Mad 1

The document provides code examples for developing various Android applications, including sending and receiving SMS, capturing images using the camera, using fragments, sending emails, displaying the user's current location, and integrating Google Maps. Each section includes the necessary XML layout files and Java code snippets to implement the functionalities. Permissions and manifest configurations are also specified where required.

Uploaded by

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

Mad 1

The document provides code examples for developing various Android applications, including sending and receiving SMS, capturing images using the camera, using fragments, sending emails, displaying the user's current location, and integrating Google Maps. Each section includes the necessary XML layout files and Java code snippets to implement the functionalities. Permissions and manifest configurations are also specified where required.

Uploaded by

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

Q.

Develop an application to send and receive SMS (Write only Java and permission tag
in manifest file).
Q.Develop a Program to send an SMS.
Ans:
Permissions and <receiver> tag required in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.and.sendandreceivesms">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</manifest>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
1
android:padding="16dp"
android:gravity="center_vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="To :"
android:gravity="end"/>

<EditText
android:id="@+id/etPhno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="25"
android:inputType="phone"
android:hint="Enter Phone Number"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Sms Text"
android:gravity="end"/>

<EditText

2
android:id="@+id/etmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:inputType="textMultiLine"
android:hint="Enter SMS Text"
android:ems="25"
android:minLines="3"/>
<Button
android:id="@+id/btnSms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEND SMS"
android:layout_marginTop="16dp"/>

</LinearLayout>
MainActivity.java
package com.and.sendreceivesms;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.IntentFilter;
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;

3
import android.widget.Toast;
import com.and.sendreceivesms.SmsReceiver;
public class MainActivity extends AppCompatActivity {
SmsReceiver sms= new SmsReceiver();
EditText et1,et2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.etPhno);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEND_
SMS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String phno= et1.getText().toString();
String msg=et2.getText().toString();
SmsManager smsManager= SmsManager.getDefault();
smsManager.sendTextMessage(phno,null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms sent successfully",
Toast.LENGTH_LONG).show();
}
4
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Sms failed to send... try again",
Toast.LENGTH_LONG).show();
}}
});
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(sms,filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(sms);
}
}
SmsReceiver.java
package com.and.sendreceivesms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
SmsReceiver(){}

5
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] sms = (Object[]) bundle.get("pdus");
for (int i=0; i < sms.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String phone = smsMessage.getOriginatingAddress();
String message = smsMessage.getMessageBody().toString();
Toast.makeText(context, "Receivedfrom"+ phone + ": " + message,
Toast.LENGTH_SHORT).show();
}}}}

Q. Write a program to capture an image using camera and display it. (Note: Consider
the appropriate XML file. All attributes are not required. In java file all imports are not
expected. Different relevant logic/code can be considered.).(6m)*
Ans:
activity_main.xml
<?xmlversion="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="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CAMERA"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<ImageView

6
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="81dp"
android:src="@drawable/rose"/>
<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="TAKEPHOTO"/>
</RelativeLayout>

MainActivity.java
package com.and.captureimage;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
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;
public class MainActivity extends AppCompatActivity
{
Button b1;
ImageView imageView;
int CAMERA_REQUEST=1;
@Override
protected void onCreate(Bundle savedInstanceState) {

7
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.photo);
imageView=findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,CAMERA_REQUEST);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST {
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}

11. What is Fragment? Explain with example. (4m)


Ans:
Android Fragment is the part of Activity, it is also known as Sub-Activity.
It represents behaviour or a portion of user interface in an Activity.
There can be more than one fragment in an Activity .

8
Fragment can be represent in multiple screen inside one activity.
It declaring as a <Fragment> Element.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="example.javatpoint.com.fragmentexample.MainActivity">
<fragment
android:id="@+id/fragment1"
android:name="example.javatpoint.com.fragmentexample.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment2"
android:name="example.javatpoint.com.fragmentexample.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
Q.Develop a program to send and receive an Email. (6 M)
Q.Write a program to send Email.(6m)(s-24)
Ans:
<receiver android:name=".GmailReceiver" android:exported="true">
<intent-filter>

9
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</receiver>
Program to send Email
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/emailTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Send To" />
<EditText
android:id="@+id/emailSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject" />
<EditText
android:id="@+id/emailBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message" />

10
<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Email" />
</LinearLayout>
MainActivity.java
package com.and.emailapp;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity{
EditText emailTo, emailSubject, emailBody;
Button sendBtn;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailTo = findViewById(R.id.emailTo);
emailSubject = findViewById(R.id.emailSubject);
emailBody = findViewById(R.id.emailBody);
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(view -> {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]
{emailTo.getText().toString()});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject.getText().toString());
emailIntent.putExtra(Intent.EXTRA_TEXT, emailBody.getText().toString());
11
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Choose Email App"));
});
}
}
Gmailrerciever..java
package com.and.emailapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class GmailReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"EmailReceived(simulated)", Toast.LENGTH_SHORT).show();
}}
Q. Write a program to show users current location.(6m)(s-24)
Ans:
Androidmanifest.xml
<manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Mainactivity.java
package com.javapapers.android.geolocationfinder;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;

12
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" +
location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
13
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

Q. Develop an application to display Google map with user's current location. (Note :
Consider the appropriate XML file. All attributes are not required. In java file all
imports are not expected. Different relevant logic/code can be considered.)(6m)
Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>

14
MainActivity.Java
package com.example.location;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
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;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends FragmentActivity implements OnMapReadyCallback
{
Location currentlocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

15
setContentView(R.layout.activity_main);
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null)
{
currentlocation=location;

Toast.makeText(getApplicationContext(),currentlocation.getLatitude()+""+current
location.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.go
ogle_map);

16
supportMapFragment.getMapAsync(MainActivity.this);
}}
});
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
LatLng latLng=new
LatLng(currentlocation.getLatitude(),currentlocation.getLongitude());
MarkerOptions markerOptions=new MarkerOptions().position(latLng)
.title("I am Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,5));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
break;
} }}

Q. Develop an android application to show current location of an user's car (4 M)


Ans

17
activity_maps.xml
<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="example.com.mapexample.MapsActivity" />

MapsActivity.java
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.api.GoogleApiClient;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;
import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;

18
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);

19
} }
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCU
RACY)
;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
20
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE
_GREEN));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
} @Override
public void onConnectionFailed(ConnectionResult connectionResult) {
} }
Add the following user-permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Q. Write a program to find the direction from user's current location to MSBTE,
Bandra. (Write only Java and manitest file). (Note : Any other relevant logic to get the
required output can also be considered.)(6m)*
Ans:

21
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.msbte.google_map_currentlocationroute">
<uses-permission android:name="android.permission.INTERNET" />
<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">
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<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>

22
MainActivity.java
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;

23
import com.google.android.gms.maps.model.PolylineOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener , OnMapReadyCallback,
TaskLoadedCallback{
private GoogleMap mMap;
private MarkerOptions place1, place2;
Button getDirection;
private Polyline currentPolyline;
private MapFragment mapFragment;
private boolean isFirstTime = true;
//variables for current location
private static final String TAG = "MainActivity";
private TextView tvLocation;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
@Override

24
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code for getting current location
requestMultiplePermissions();
tvLocation = (TextView) findViewById((R.id.tv));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
Log.d("mylog", "Added Markers");
mMap.addMarker(place1);
mMap.addMarker(place2);
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(22.7739,71.6673))
.zoom(7)
.bearing(0)
.tilt(45)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 5000,
null);
}
private String getUrl(LatLng origin, LatLng dest, String directionMode) {

25
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String mode = "mode=" + directionMode;
String parameters = str_origin + "&" + str_dest + "&" + mode;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" +
parameters + "&key=" + getString(R.string.google_maps_key);
return url;
}
@Override
public void onTaskDone(Object... values) {
if (currentPolyline != null)
currentPolyline.remove();
currentPolyline = mMap.addPolyline((PolylineOptions) values[0]);
}
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION )
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by
user!", Toast.LENGTH_SHORT).show();
}
if (report.isAnyPermissionPermanentlyDenied()) {

26
openSettingsDialog();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest>
permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
@Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ",
Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
private void openSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Required Permissions");
builder.setMessage("This app require permission to use awesome feature. Grant them in
app settings.");
builder.setPositiveButton("Take Me To SETTINGS", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();

27
Intent intent = new
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}

28
if (mLocation != null) {
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}}
protected void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)

29
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
tvLocation.setText(String.valueOf(location.getLatitude() +"
"+String.valueOf(location.getLongitude())));
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
if(isFirstTime){
getDirection = findViewById(R.id.btnGetDirection);
getDirection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new FetchURL(MainActivity.this).execute(getUrl(place1.getPosition(),
place2.getPosition(), "driving"), "driving");
}
});
place1 = new MarkerOptions().position(new LatLng(location.getLatitude(),

30
location.getLongitude())).title("Location 1");
place2 = new MarkerOptions().position(new
LatLng(19.021824,72.8662016)).title("MSBTE");
mapFragment = (MapFragment)
getFragmentManager().findFragmentById(R.id.mapNearBy);
mapFragment.getMapAsync(this);
isFirstTime = false;
} }}

Q. Develop an application to display a Google Map. (Write JAVA & Manifest file)(6m)
Ans:
AndroidManifest.xml code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.mapexample">
<usespermission android:name="android.permission.ACCESS_FINE_LOCATION" />
<usespermission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

code of MapsActivity.java :
package example.com.mapexample;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragment
Manager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
32
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sy
dney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Q. Describe with example, how to create a simple database in SQLite (Assume
suitable data) (4m)
Ans:
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

<?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">
<Button
android:text="Create SQLite Database"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
33
android:layout_marginTop="46dp"
android:id="@+id/button" />
</RelativeLayout>

MainActivity.java
package com.and.sqlitedatabase;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;;

public class MainActivity extends AppCompatActivity {


SQLiteDatabase sqLiteDatabaseObj;
Button createData;

@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);
}
});

34
}}
Q. Develop an android application for taking student feedback with database
connectivity. (6m)
Ans:
activity_main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Feedback Form"
android:textSize="20sp"
android:gravity="center"
android:padding="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll No."
35
android:id="@+id/editrollno"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Class"
android:id="@+id/editclass"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your Feedback"
android:lines="3"
android:id="@+id/editfeedback"/>
<Button
android:text="Submit Feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button" />
</LinearLayout>
MainActivity.java
package com.and.feedbackapp;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.app.feedbackapp.DatabaseHelper;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText stdName, stdRollno, stdClass, stdFeedback;

36
Button submitBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
stdName = findViewById(R.id.editname);
stdRollno = findViewById(R.id.editrollno);
stdClass = findViewById(R.id.editclass);
stdFeedback = findViewById(R.id.editfeedback);
submitBtn = findViewById(R.id.button);
submitBtn.setOnClickListener(view -> saveFeedback());
}
private void saveFeedback()
{
String name = stdName.getText().toString().trim();
String rollno = stdRollno.getText().toString().trim();
String className = stdClass.getText().toString().trim();
String feedback = stdFeedback.getText().toString().trim();
if (name.isEmpty() || rollno.isEmpty() || className.isEmpty() || feedback.isEmpty()) {
Toast.makeText(this, "All fields are required!", Toast.LENGTH_LONG).show();
return;
}
boolean inserted = databaseHelper.insertFeedback(name, rollno, className, feedback);
if (inserted)
{
Toast.makeText(this,"Feedback Submitted Successfully",
Toast.LENGTH_LONG).show();
stdName.setText("");
stdRollno.setText("");
37
stdClass.setText("");
stdFeedback.setText("");
}
else
{
Toast.makeText(this, "Submission Failed", Toast.LENGTH_LONG).show();
} }}

DatabaseHelper.java
package com.app.feedbackapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "FeedbackDB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "Student";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_ROLLNO = "rollno";
private static final String COLUMN_CLASS = "class_name";
private static final String COLUMN_FEEDBACK = "feedback";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override

38
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_ROLLNO + " TEXT, " +
COLUMN_CLASS + " TEXT, " +
COLUMN_FEEDBACK + " TEXT);";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertFeedback(String name, String rollno, String className, String
feedback) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
contentValues.put(COLUMN_ROLLNO, rollno);
contentValues.put(COLUMN_CLASS, className);
contentValues.put(COLUMN_FEEDBACK, feedback);
long result = db.insert(TABLE_NAME, null, contentValues);
db.close();
return result != -1;
}}
Q.Develop a program to TURN ON and OFF bluetooth. Write .java file and permission
tags.(6m)
Q. Develop a program for providing bluetooth connectivity.(6m)*(4m)

39
Ans:
activity_main.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView android:text=""
android:id="@+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="49dp"
android:text="TURN_ON" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"

40
android:layout_marginTop="27dp"
android:text="DISCOVERABLE" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button2"
android:layout_below="@+id/button2"
android:layout_marginTop="28dp"
android:text="TURN_OFF" />
</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

41
<activity
android:name="com.example.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

MainActivity.java
package com.and.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{

42
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
out.append("device not supported");
}
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering())
{
Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE
DISCOVERABLE",

43
Toast.LENGTH_LONG);

Intent enableBtIntent = new


Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);

}
}
});
button3.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
mBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(),"TURNING_OFFBLUETOOTH",Toast.LENGTH_
LONG);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}

Q. Design an android application to show the list of paired devices by Bluetooth.(6m)


Ans:
activity_main.xml

44
<?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"
android:transitionGroup="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List all Paired devices"
android:onClick="list"
android:id="@+id/button1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView1"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button1" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_below="@+id/textView1" />
</RelativeLayout>

45
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.and.bluetoothconnectivity"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher_background"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.and.bluetoothconnectivity.MainActivity"
android:label="@string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
46
</manifest>
MainActivity.java
package com.and.bluetoothconnectivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity
{
Button b1;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
lv = (ListView)findViewById(R.id.listView);
BA = BluetoothAdapter.getDefaultAdapter();
}

47
public void list(View v)
{
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(),"ShowingPairedDevices",Toast.LENGTH_SH
ORT).
show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,
list);
lv.setAdapter(adapter);
}
}
Q .Explain text to speech conversion technique in android.(4m)
Ans:
Text to Speech converts the text written on the screen to speech like you have written “Hello
World” on the screen and when you press the button it will speak “Hello World”.
Text-to speech is commonly used as an accessibility feature to help people who have trouble
reading on screen text, but it’s also convenient for those who want to be read too.
This feature has come out to be a very common and useful feature for the users.
In android, by using TextToSpeech class we can easily convert our text into voice and it
supports different types of speaking languages. We can choose the speaking language based
on our requirements in the android application.
Q. Develop an application to convert thanks" text to speech as given in the
following GUI.(6m)

48
Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextView
android:id="@+id/textview1"
android:padding="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextToSpeechDemo"
android:gravity="center"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="@android:color/white"

49
android:background="@color/black"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Text to Speech(TTS) Demo"
android:textSize="35dp"
android:gravity="center"
android:id="@+id/textView2"
android:layout_below="@+id/textview1" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="22dp"
android:ems="50"
android:text="thanks" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLICK TO CONVERT TEXT TO SPEECH"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:textSize="15dp" />
</RelativeLayout>

MainActivity.java.

50
package com.and.texttospeech;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{
TextToSpeech t1;
EditText ed1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = findViewById(R.id.editText);
b1 = findViewById(R.id.button);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()
{
@Override
public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
t1.setLanguage(Locale.UK);
}

51
}
});
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String toSpeak = ed1.getText().toString();
if (!toSpeak.isEmpty())
{
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, null);
} else
{
Toast.makeText(getApplicationContext(), "Please enter text to speak",
Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onDestroy()
{
if (t1 != null) {
t1.stop();
t1.shutdown();
}
super.onDestroy();
}

52
}

Q. Develop an application to update a record of an employee whose emp.id is ‘E101’ in


SQlite database. Change employee name from “POR" to “XYZ". Also display the
updated record (Write .java and .xml files).
Ans:
(not runnable)
activity_update_emp.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/idEdtEmpName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Employee Name" />
<EditText
android:id="@+id/idEdtEmpSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Employee Salary" />
<Button
android:id="@+id/idBtnAddCourse"

53
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add Employee"
android:textAllCaps="false" />
</LinearLayout>
DBHandler.java file
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "empdb";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "myemp";
private static final String ID_COL = "id";
private static final String NAME_COL = "emp_name";
private static final String TRACKS_COL = "emp_salary";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ SALARY_COL + " TEXT)";
db.execSQL(query);
}

54
public void addNewCourse(String empName, String empSalary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_COL, empName);
values.put(TRACKS_COL, empSalary);
db.insert(TABLE_NAME, null, values);
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
empRVAdapter.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 empNameEdt, empSalaryEdt;
private Button addempBtn;
private DBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

55
empNameEdt = findViewById(R.id.idEdtempName);
empSalaryEdt = findViewById(R.id.idEdtempSalary);
addempBtn = findViewById(R.id.idBtnAddemp);
dbHandler = new DBHandler(MainActivity.this);
addCourseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String empName = empNameEdt.getText().toString();
String empSalary = empSalaryEdt.getText().toString();
if (empName.isEmpty() && empSalary.isEmpty() &&) {
Toast.makeText(MainActivity.this, "Please enter all the data..",
Toast.LENGTH_SHORT).show();
return;
}
dbHandler.addNewemp(empName, empSalary);
Toast.makeText(MainActivity.this, "Employee has been added.",
Toast.LENGTH_SHORT).show();
empNameEdt.setText("");
empSalaryEdt.setText("");
}
});
}
}
Update employee record java file:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

56
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class UpdateCourseActivity extends AppCompatActivity {
private EditText empNameEdt, empSalaryEdt;
private Button updateempBtn;
private DBHandler dbHandler;
String empName, empSalary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_emp);
empNameEdt = findViewById(R.id.idEdtempName);
empSalaryEdt = findViewById(R.id.idEdtempSalary);
updateempBtn = findViewById(R.id.idBtnUpdateemp);
dbHandler = new DBHandler(UpdateempActivity.this);
empName = getIntent().getStringExtra("emp_name");
empSalary = getIntent().getStringExtra("emp_salary");
empNameEdt.setText(empName);
empSalaryEdt.setText(empSalary);
updateempBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHandler.updateemp(empName, empNameEdt.getText().toString(),
empSalaryEdt.getText().toString());
Toast.makeText(UpdateempActivity.this, "Employee Record Updated..",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(UpdateempActivity.this, MainActivity.class);
startActivity(i);
} }); }}

57
Q. 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. (Any other relevant logic can be considered)(6m)
Ans:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
58
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"

59
android:layout_centerHorizontal="true"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />
</RelativeLayout>
MainActivity.java
package com.and.customersdetail;

60
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
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.Toast;
public class MainActivity extends AppCompatActivity
{
SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode, editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener()

61
{
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS
AndroidJSonTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, cid
VARCHAR, name VARCHAR, mobile VARCHAR, address VARCHAR, pincode
VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString() ;
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO AndroidJSonTable (cid, name, mobile, address,
pincode) VALUES('"+cid+"', '"+cname+"', '"+cmobile+"', '"+caddress+"', '"+cpincode+"');";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Data Inserted Successfully",
Toast.LENGTH_LONG).show();
}
});
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from AndroidJSonTable
where cid="+sid+"", null );
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext()) {
String cid =cursor.getString(1);
String name =cursor.getString(2);

62
String mob =cursor.getString(3);
String addr =cursor.getString(4);
String pcode =cursor.getString(5);
buffer.append(cid+ " " + name + " " + mob +" " + addr +" " + pcode +"\n");
Toast.makeText(getApplicationContext(),buffer,Toast.LENGTH_LONG).sh
ow();
} } }); } }
Q. Develop Android application to enter one number and display factorial of a number
once click on button
Ans:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<Button
android:id="@+id/buttonCalculate"
android:layout_width="wrap_content"

63
android:layout_height="wrap_content"
android:text="Calculate Factorial"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Factorial: "
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="@id/buttonCalculate"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
</RelativeLayout>
MainActivity.java
package com.and.factorialnumber;
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 android.app.Activity;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {

64
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

EditText editTextNumber = (EditText)


findViewById(R.id.editTextNumber);
Button buttonCalculate =(Button)
findViewById(R.id.buttonCalculate);
TextView textViewResult = (TextView)
findViewById(R.id.textViewResult);

buttonCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String input = editTextNumber.getText().toString();

if (input.isEmpty())
{
Toast.makeText(MainActivity.this,"Please enter a number",
Toast.LENGTH_SHORT).show();
} else
{
try
{
int number = Integer.parseInt(input);
if (number < 0)
{
Toast.makeText(MainActivity.this, "Enter a non-negative number",
Toast.LENGTH_SHORT).show();
} else
65
{
long result = factorial(number);
textViewResult.setText("Factorial: " + result);
}
} catch (NumberFormatException e)
{
Toast.makeText(MainActivity.this,"Invalid input. Enter a valid number.",
Toast.LENGTH_SHORT).show();
}}}
});
}
private long factorial(int n)
{
if (n == 0) return 1;
long result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result; } }
Q.Write a program to display the list of sensors supported by Device.(6m)
Ans:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
66
<ListView
android:id="@+id/sensorListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java
package com.and.displaylistofsensor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{

private SensorManager sensorManager;


private ListView sensorListView;
private ArrayAdapter<String> sensorAdapter;
private List<String> sensorList;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorListView = findViewById(R.id.sensorListView);

67
sensorList = new ArrayList<>();
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors)
{
sensorList.add(sensor.getName());
}
sensorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
sensorList);
sensorListView.setAdapter(sensorAdapter);
}
}

Q. 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) (Note:
Consider the appropriate XML file. All attributes are not required. In java file all
imports are not expected. Different relevant logic/code can be considered.) (6m)
Ans:
activity_main.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext"
android:hint="Enter the temp"/>
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"

68
android:layout_height="wrap_content"
android:layout_below="@+id/edittext"
android:layout_marginTop="35dp"
android:textOff="F to C"
android:textOn="C to F" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/togglebutton"
android:layout_marginTop="56dp" />
</RelativeLayout>
MainActivity.java
package com.and.demo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.Activity;
public class MainActivity extends Activity
{
Double a;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText)
findViewById(R.id.edittext);
Button b1 = (Button)
findViewById(R.id.button);
ToggleButton tb = (ToggleButton)
findViewById(R.id.togglebutton);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (tb.isChecked())
{
a = Double.parseDouble(String.valueOf(et.getText()));
69
Double b = a * 9 / 5 + 32;
String r = String.valueOf(b);
Toast.makeText(MainActivity.this, r + "°F", Toast.LENGTH_SHORT).show();
}
else
{
a = Double.parseDouble(String.valueOf(et.getText()));
Double b = a - 32;
Double c = b * 5 / 9;
String r = String.valueOf(c);

Toast.makeText(MainActivity.this, r + "°C", Toast.LENGTH_SHORT).show();


}
} }); }}

Q.Develop an android application using radio button.(4m)


Ans:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="30dp"
tools:context=".MainActivity">
<TextView android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Radio Button"
android:textSize="20dp"
android:gravity="center"
android:textColor="#f00"/>
<RadioGroup
android:id="@+id/group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text1">
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"

70
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/male"
android:text="Female"/>
</RadioGroup>
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/group"
android:layout_marginTop="99dp"
android:layout_centerHorizontal="true"
android:text="Submit" />

</RelativeLayout>
MainActivity.java
package com.and.radiobutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioButton r1=(RadioButton)
findViewById(R.id.male);
RadioButton r2=(RadioButton)
findViewById(R.id.female);
Button b1=(Button)
findViewById(R.id.submit);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
71
public void onClick(View v)
{
String selected;
if(r1.isChecked())
{
selected="You selected" + r1.getText();
}
else
{
selected="You Selected"+ r2.getText();
}
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
}
});
}
}
Q.Write a program to display a rectangular progress bar.(4m)(w-22)
Ans:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:indeterminate="false"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1" />
<TextView
72
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/progressBar"
android:layout_below="@+id/progressBar"/>
</RelativeLayout>
MainActivity.java
package com.and.rectangularprogresbar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int progressStatus = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = (ProgressBar)
findViewById(R.id.progressBar);
TextView textView = (TextView)
findViewById(R.id.textView);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
}).start();

73
}
}
Q. Write a program to create first display screen of any search Engine using
AutoCompleteTextView . (s-24)(6-m)
Ans:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center"
android:background="@android:color/white">
<AutoCompleteTextView
android:id="@+id/auto_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search here..."
android:textSize="18sp"
android:padding="12dp"
android:background="@android:drawable/editbox_background"
android:completionThreshold="1" />
<Button
android:id="@+id/btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:layout_marginTop="20dp"
android:padding="10dp" />
</LinearLayout>
MainActivity.java
package com.and.autocompletetextview;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;

74
import android.app.Activity;
public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView auto1 =(AutoCompleteTextView)
findViewById(R.id.auto_id);
Button btn = (Button)
findViewById(R.id.btn_id);
String[] arr= {"Google", "Bing", "Yahoo", "DuckDuckGo", "Baidu", "Yandex",
"Ask.com", "Ecosia", "AOL", "StartPage", "WolframAlpha"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,arr);
auto1.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String searchQuery = auto1.getText().toString().trim();
if (!searchQuery.isEmpty()){
Toast.makeText(MainActivity.this, "Searching for: " + searchQuery,
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Please enter a search term",
Toast.LENGTH_SHORT).show();
}}
}); } }
Q.Write a Program to show five Checkboxes and Toast Selected Checkboxes using
Linear Layout.(s-24)(6m)
Ans:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<CheckBox
75
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3" />
<CheckBox
android:id="@+id/checkBox4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4" />
<CheckBox
android:id="@+id/checkBox5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 5" />
<Button
android:id="@+id/btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected"
android:layout_marginTop="20dp" />
</LinearLayout>
MainActivity.java
package com.and.checkboxesusinglinearlayouts_24;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
76
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox ch1 =(CheckBox)
findViewById(R.id.checkBox1);
CheckBox ch2 =(CheckBox)
findViewById(R.id.checkBox2);
CheckBox ch3 = (CheckBox)
findViewById(R.id.checkBox3);
CheckBox ch4 = (CheckBox)
findViewById(R.id.checkBox4);
CheckBox ch5 = (CheckBox)
findViewById(R.id.checkBox5);
Button btn = (Button)
findViewById(R.id.btn_id);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
StringBuilder selectedOptions = new StringBuilder("Selected: ");
if (ch1.isChecked()) selectedOptions.append("Option 1, ");
if (ch2.isChecked()) selectedOptions.append("Option 2, ");
if (ch3.isChecked()) selectedOptions.append("Option 3, ");
if (ch4.isChecked()) selectedOptions.append("Option 4, ");
if (ch5.isChecked()) selectedOptions.append("Option 5, ");

if (selectedOptions.toString().endsWith(", ")) {
selectedOptions.setLength(selectedOptions.length()-2);
}
Toast.makeText(MainActivity.this, selectedOptions.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}
Q. Develop a Simple Calculator Using Relative layout. (6m) (s-23)
Q. Develop a program to perform addition, subtraction, division, multiplication of two
numbers and display the result. (Use appropriate UI controls).(6m)(w-23).
Ans:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
77
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Calculator"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<EditText
android:id="@+id/edit_id1"
android:layout_below="@+id/heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Number 1"
android:inputType="number" />
<EditText
android:id="@+id/edit_id2"
android:layout_below="@+id/edit_id1"
android:hint="Enter Number 2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" />
<TextView
android:id="@+id/txt_id2"
android:layout_below="@+id/edit_id2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Result" />
<Button
android:id="@+id/sum"
android:layout_below="@id/txt_id2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="+" />
<Button
android:id="@+id/sub"
android:layout_below="@id/txt_id2"

78
android:layout_toRightOf="@id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="-" />
<Button
android:id="@+id/div"
android:layout_below="@id/txt_id2"
android:layout_toRightOf="@id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="/" />
<Button
android:id="@+id/mul"
android:layout_below="@id/txt_id2"
android:layout_toRightOf="@id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="x"/>
</RelativeLayout>
MainActivity.java
package com.and.simplecalusingrelativelayout;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
int num1, num2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText e1 = (EditText)
findViewById(R.id.edit_id1);
EditText e2 = (EditText)
findViewById(R.id.edit_id2);
TextView t1 = (TextView)
findViewById(R.id.txt_id2);
79
Button add = (Button)
findViewById(R.id.sum);
Button mul = (Button)
findViewById(R.id.mul);
Button div = (Button)
findViewById(R.id.div);
Button sub = (Button)
findViewById(R.id.sub);
add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
});
sub.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int sub = num1 - num2;
t1.setText(Integer.toString(sub));
}
});
mul.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int mul = num1 * num2;
t1.setText(Integer.toString(mul));
}
});
div.setOnClickListener(new View.OnClickListener()
{
@Override

80
public void onClick(View view)
{
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
int div= num1 / num2;
t1.setText(Integer.toString(div));
}
});
}
}

81

You might also like