0% found this document useful (0 votes)
7 views35 pages

mad pr cmp1 (1)

The document outlines a series of practical programming exercises in Android development, covering various UI components such as List View, Grid View, and custom Toast alerts. It includes Java and XML code snippets for implementing features like Date and Time Picker, Activity lifecycle management, explicit and implicit intents, content providers, services, broadcast receivers, and sensor integration. Each practical exercise is designed to enhance understanding of Android app development concepts and functionalities.

Uploaded by

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

mad pr cmp1 (1)

The document outlines a series of practical programming exercises in Android development, covering various UI components such as List View, Grid View, and custom Toast alerts. It includes Java and XML code snippets for implementing features like Date and Time Picker, Activity lifecycle management, explicit and implicit intents, content providers, services, broadcast receivers, and sensor integration. Each practical exercise is designed to enhance understanding of Android app development concepts and functionalities.

Uploaded by

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

PRACTICAL NO.

14
Develop a program to implement List View, Grid View, Image View and Scroll View.
Java Code android:padding="16dp"

package com.example.pr_14_listview; tools:context=".MainActivity">

import android.os.Bundle; <TextView

import android.widget.ArrayAdapter; android:id="@+id/textViewHeading"

import android.widget.ListView; android:layout_width="wrap_content"

import android:layout_height="wrap_content"
androidx.appcompat.app.AppCompatActivity;
android:text="LIST OF COLORS"
public class MainActivity extends
android:textSize="24sp"
AppCompatActivity {
android:textStyle="bold"
@Override
android:layout_marginBottom="16dp"/>
protected void onCreate(Bundle
savedInstanceState) { <ListView

super.onCreate(savedInstanceState); android:id="@+id/listView"

setContentView(R.layout.activity_main); android:layout_width="match_parent"

String[] colors = {"Red", "Green", "Blue", android:layout_height="wrap_content"/>


"Yellow", "Orange", "Purple", "Pink", "Cyan",
</LinearLayout>
"Magenta", "Brown"};

ArrayAdapter<String> adapter = new


ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, colors);

ListView listView = findViewById(R.id.listView);


listView.setAdapter(adapter);

}}

Xml code

<?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"
Practical 15
Develop a Program to Implement Custom Toast alert
XML File:-

<?xml version="1.0" encoding="utf-8"?> Toast.makeText(this,"Message for you\nYou have


got mail!",Toast.LENGTH_LONG).show();
<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"
tools:context=".MainActivity"
android:orientation="vertical">

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World.Toast Example"/>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show Toast"
android:onClick="Popup"/>

</LinearLayout>

Java:-

package com.example.myapplication;

import
androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View; import


android.widget.Toast;

public class MainActivity extends


AppCompatActivity { @Override

protected void onCreate(Bundle


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

}
public void Popup(View view)

{
Practical 16
Develop a Program to implement Date and Time Picker
Xml code

<?xml version="1.0" encoding="utf-8"?> android:text="Get Time"

<AbsoluteLayout android:textSize="20sp"/>
xmlns:android="http://schemas.android.com/apk/res
</AbsoluteLayout>
/android"

android:layout_width="match_parent"
Java code
android:layout_height="match_parent">
package com.example.practical16;
<TextView
import android.os.Bundle;
android:id="@+id/textView"
import android.view.View;
android:layout_width="376dp"
import android.widget.Button;
android:layout_height="118dp"
import android.widget.TextView;
android:layout_x="22dp"
import android.widget.TimePicker;
android:layout_y="29dp"
import android.widget.Toast;
android:gravity="center"
import
android:text="@string/time_picker_example"
androidx.appcompat.app.AppCompatActivity;
android:textSize="36sp"/>
public class MainActivity extends
<TimePicker AppCompatActivity {

android:id="@+id/timePicker" TimePicker Picker;


android:layout_width="362dp" Button getTime;

android:layout_height="wrap_content" TextView tv;

android:layout_x="29dp" @Override

android:layout_y="196dp" protected void onCreate(Bundle


savedInstanceState) {
android:timePickerMode="clock"/>
super.onCreate(savedInstanceState);
<Button
setContentView(R.layout.activity_main);
android:id="@+id/btn"
Picker = findViewById(R.id.timePicker);
android:layout_width="159dp"
getTime = findViewById(R.id.btn);
android:layout_height="49dp"
tv = findViewById(R.id.textView);
android:layout_x="43dp"
Picker.setIs24HourView(true);
android:layout_y="639dp"
getTime.setOnClickListener(new Toast.makeText(MainActivity.this, "Hour:
View.OnClickListener() { " + hour + " Minute: " + min,
Toast.LENGTH_SHORT).show();
@Override
}
public void onClick(View v) {
});
int hour = Picker.getHour();
}
int min = Picker.getMinute();
}
Practical 17
Develop Program to Create an Activity
Xml Code super.onResume();

<?xml version="1.0" encoding="utf-8"?> Log.v("lifecycle", "onResume invoked"); }

<LinearLayout @Override
xmlns:android="http://schemas.android.com/apk/res
protected void onPause() {
/android"
super.onPause();
xmlns:tools="http://schemas.android.com/tools"
Log.d("lifecycle", "onPause invoked"); }
android:layout_width="match_parent"
@Override
android:layout_height="match_parent"
protected void onStop() {
tools:context=".MainActivity">
super.onStop();
</LinearLayout>
Log.d("lifecycle", "onStop invoked"); }
Java Code
@Override
package com.example.pr17;
protected void onRestart() {
import
androidx.appcompat.app.AppCompatActivity; super.onRestart();

import android.os.Bundle; Log.d("lifecycle", "onRestart invoked"); }

import android.util.Log; @Override

public class MainActivity extends protected void onDestroy() {


AppCompatActivity {
super.onDestroy();
@Override
Log.d("lifecycle", "onDestroy invoked");
protected void onCreate(Bundle
}}
savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Log.d("lifecycle", "onCreate invoked"); }

@Override

protected void onStart() {

super.onStart();

Log.i("lifecycle", "onStart invoked"); }


@Override

protected void onResume() {


Practical 18
Develop a Program to implement new activity using Explicit intent And implicit intent
Xml code

<?xml version="1.0" encoding="utf-8"?> protected void onCreate(Bundle


savedInstanceState) {
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res super.onCreate(savedInstanceState);
/android"
setContentView(R.layout.activity_main);
xmlns:tools="http://schemas.android.com/tools"
startDialerButton =
android:layout_width="match_parent" findViewById(R.id.startDialerButton);

android:layout_height="match_parent" startDialerButton.setOnClickListener(new
View.OnClickListener() {
tools:context=".MainActivity">
@Override
<Button
public void onClick(View v) {
android:id="@+id/startDialerButton"
Intent intent = new
android:layout_width="wrap_content"
Intent(Intent.ACTION_DIAL);
android:layout_height="wrap_content"
intent.setData(Uri.parse("tel:"));
android:layout_centerInParent="true"
startActivity(intent);
android:text="Start Dialer" />
} });
</RelativeLayout>
}}
Java Code

package com.example.pr_18_02;
import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import
androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends


AppCompatActivity {

private Button startDialerButton;


@Override
Practical 19
Develop a Program to implement Content Provider
string.xml <Button

<resources> android:id="@+id/loadButton"

<string android:layout_width="wrap_content"

name="app_name">Accessing_Content_Provider</ android:layout_height="wrap_content"
string>
android:onClick="onClickShowDetails"
<string name="heading">Accessing data of Content
android:text="@string/loadButtonText" />
Provider</string>
<TextView
<string name="loadButtonText">Load
android:id="@+id/res"
Data</string>
android:layout_width="match_parent"
</resources>
android:layout_height="match_parent"
Activity_main.xml
android:textSize="18sp"
<?xml version="1.0" encoding="utf-8"?>
android:textStyle="bold" />
<LinearLayout
</LinearLayout>
xmlns:android="http://schemas.android.com/apk/res
/android" MainActivity.java

xmlns:app="http://schemas.android.com/apk/res- package com.example.mycontent;


auto"
import
xmlns:tools="http://schemas.android.com/tools" androidx.appcompat.app.AppCompatActivity;

android:layout_width="match_parent" import android.database.Cursor;


android:layout_height="match_parent" import android.net.Uri;
android:orientation="vertical" import android.os.Bundle;

tools:context=".MainActivity"> import android.view.View;

<TextView import android.widget.TextView;

android:id="@+id/textView1" public class MainActivity extends


AppCompatActivity {
android:layout_width="match_parent"
Uri CONTENT_URI
android:layout_height="wrap_content"
=Uri.parse("content://com.demo.user.provider/users
android:text="@string/app_name" ");

android:textAlignment="center" @Override
android:textSize="24sp" protected void onCreate(Bundle
savedInstanceState) {
android:textStyle="bold" />
super.onCreate(savedInstanceState); else {

setContentView(R.layout.activity_main); resultView.setText("No Records Found");

} }

public void onClickShowDetails(View view) { }

TextView resultView= (TextView) }

findViewById(R.id.res);

Cursor cursor
=getContentResolver().query(Uri.parse("content://c
om.demo.user.

provider/users"), null, null, null, null);

if(cursor.moveToFirst()) {

StringBuilder strBuild=new StringBuilder();


while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getCo
lumnIndex("i

d"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")))
;

cursor.moveToNext();

resultView.setText(strBuild);

}
Practical 20
Develop a Program to implement service
Xml code

<?xml version="1.0" encoding="utf-8"?> setContentView(R.layout.activity_main);

<RelativeLayout }
xmlns:android="http://schemas.android.com/apk/res
public void startWifiService(View view) {
/android"
Intent serviceIntent = new Intent(this,
xmlns:tools="http://schemas.android.com/tools"
WifiService.class);
android:layout_width="match_parent"
startService(serviceIntent);
android:layout_height="match_parent"
}
tools:context=".MainActivity">
}
<Button
AndroidManifest.xml
android:layout_width="wrap_content"
<?xml version="1.0" encoding="utf-8"?>
android:layout_height="wrap_content"
<manifest
android:text="Start Wi-Fi Service" xmlns:android="http://schemas.android.com/apk/res
/android"
android:onClick="startWifiService"
xmlns:tools="http://schemas.android.com/tools">
android:layout_centerInParent="true" />
<!-- Permission to change WiFi state -->
</RelativeLayout>
<uses-permission
Java code
android:name="android.permission.CHANGE_WIF
package com.example.practical_20_ex_01; I_STATE"/>
<application

import android.content.Intent; android:allowBackup="true"


android:dataExtractionRules="@xml/data_extractio
import android.os.Bundle;
n_rules"
import android.view.View; android:fullBackupContent="@xml/backup_rules"

import android:icon="@mipmap/ic_launcher"
androidx.appcompat.app.AppCompatActivity;
android:label="@string/app_name"
public class MainActivity extends android:roundIcon="@mipmap/ic_launcher_round"
AppCompatActivity {
android:supportsRtl="true"
@Override android:theme="@style/Theme.Practical_20_ex_01
"
protected void onCreate(Bundle
savedInstanceState) { tools:targetApi="31">

super.onCreate(savedInstanceState); <activity
android:name=".MainActivity" }

android:exported="true"> return START_STICKY; }

<intent-filter> @Override

<action public IBinder onBind(Intent intent) {


android:name="android.intent.action.MAIN" />
return null;
<category
}}
android:name="android.intent.category.LAUNCHE
R" /> </intent-filter>
</activity>

<!-- Registering the WifiService -->

<service android:name=".WifiService"
android:exported="false"/>

</application>

</manifest>

WifiService.java

package com.example.practical_20_ex_01;

import android.app.Service;

import android.content.Intent;
import android.net.wifi.WifiManager;

import android.os.IBinder;

public class WifiService extends Service {

private WifiManager wifiManager;

@Override

public void onCreate() {

super.onCreate();

wifiManager = (WifiManager)
getSystemService(WIFI_SERVICE);
}

@Override

public int onStartCommand(Intent intent, int


flags, int startId) {

if (!wifiManager.isWifiEnabled()) {

wifiManager.setWifiEnabled(true);
Practical 21
Develop a Program to implement broadcast receiver
Xml code super.onStart();

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

<LinearLayout IntentFilter filter = new


IntentFilter(Intent.ACTION_AIRPLANE_MODE_
xmlns:android="http://schemas.android.com/apk/res
CHANGED);
/android"
registerReceiver(airplaneModeChangeReceiver,
xmlns:app="http://schemas.android.com/apk/res-
filter);
auto"
}
xmlns:tools="http://schemas.android.com/tools"
@Override
android:layout_width="match_parent"
protected void onStop() {
android:layout_height="match_parent"
super.onStop();
tools:context=".MainActivity">
unregisterReceiver(airplaneModeChangeReceiver);
</LinearLayout>
}
Java code
}
package com.example.pr_21;
Broadcast Reciever code
import
package com.example.pr_21;
androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.Context;
import android.os.Bundle;
import android.content.Intent;
public class MainActivity extends
AppCompatActivity { import android.provider.Settings;

AirplaneModeChangeReceiver import android.widget.Toast;


airplaneModeChangeReceiver = new
public class AirplaneModeChangeReceiver extends
AirplaneModeChangeReceiver();
BroadcastReceiver {
@Override
@Override
protected void onCreate(Bundle
public void onReceive(Context context, Intent
savedInstanceState) {
intent) {
super.onCreate(savedInstanceState);
if
setContentView(R.layout.activity_main); (isAirplaneModeOn(context.getApplicationContext
())) {
}
Toast.makeText(context, "Airplane mode is
@Override
ON", Toast.LENGTH_LONG).show();
protected void onStart() {
} else {
Toast.makeText(context, "Airplane mode is
OFF", Toast.LENGTH_SHORT).show();

}
}

private static boolean


isAirplaneModeOn(Context context) {

return Settings.System.getInt(

context.getContentResolver(),

Settings.Global.AIRPLANE_MODE_ON, 0

) != 0;
}

}
Practical 22
Develop a Program to implement Sensors
Xml code

<?xml version="1.0" encoding="utf-8"?> private LinearLayout mainLayout;

<LinearLayout private static final float SHAKE_THRESHOLD


= 10f;
xmlns:android="http://schemas.android.com/apk/res private long lastShakeTime;
/android"
@SuppressLint("MissingInflatedId")
xmlns:tools="http://schemas.android.com/tools"
@Override
android:id="@+id/mainLayout"
protected void onCreate(Bundle
android:layout_width="match_parent" savedInstanceState) {

android:layout_height="match_parent" super.onCreate(savedInstanceState);

android:gravity="center" setContentView(R.layout.activity_main);

android:orientation="vertical" mainLayout =
findViewById(R.id.mainLayout);
tools:context=".MainActivity">
sensorManager = (SensorManager)
</LinearLayout>
getSystemService(Context.SENSOR_SERVICE);
java code
accelerometerSensor =
package com.example.practical_22; sensorManager.getDefaultSensor(Sensor.TYPE_AC
CELEROMETER);
import android.annotation.SuppressLint;
lastShakeTime = System.currentTimeMillis();
import android.app.Activity;
}
import android.content.Context;
@Override
import android.graphics.Color;
protected void onResume() {
import android.hardware.Sensor;
super.onResume();
import android.hardware.SensorEvent;
sensorManager.registerListener(this,
import android.hardware.SensorEventListener;
accelerometerSensor,
import android.hardware.SensorManager; SensorManager.SENSOR_DELAY_NORMAL);

import android.os.Bundle; }

import android.widget.LinearLayout; @Override

public class MainActivity extends Activity protected void onPause() {


implements SensorEventListener {
super.onPause();
private SensorManager sensorManager;
sensorManager.unregisterListener(this);
private Sensor accelerometerSensor;
} Manifest file

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

public void onSensorChanged(SensorEvent <manifest


event) { xmlns:android="http://schemas.android.com/apk/res
/android"
if (event.sensor.getType() ==
Sensor.TYPE_ACCELEROMETER) { xmlns:tools="http://schemas.android.com/tools">

long currentTime = <uses-permission


System.currentTimeMillis(); android:name="android.permission.ACCELEROM
ETER"/>
if ((currentTime - lastShakeTime) > 1000) {
<application
float x = event.values[0];
android:allowBackup="true"
float y = event.values[1];
android:dataExtractionRules="@xml/data_extractio
float z = event.values[2]; n_rules"
float acceleration = Math.abs(x + y + z - android:fullBackupContent="@xml/backup_rules"
SensorManager.GRAVITY_EARTH);
android:icon="@mipmap/ic_launcher"
if (acceleration >
android:label="@string/app_name"
SHAKE_THRESHOLD) {
android:roundIcon="@mipmap/ic_launcher_round"
changeBackgroundColor();
android:supportsRtl="true"
lastShakeTime = currentTime;
android:theme="@style/Theme.Practical_22"
} }}}
tools:targetApi="31">
@Override
<activity
public void onAccuracyChanged(Sensor sensor,
android:name=".MainActivity"
int accuracy) {
android:exported="true">
}
<intent-filter>
private void changeBackgroundColor() {
<action
int randomColor = Color.rgb(
android:name="android.intent.action.MAIN" />
(int) (Math.random() * 256),
<category
(int) (Math.random() * 256), android:name="android.intent.category.LAUNCHE
R" />
(int) (Math.random() * 256)
</intent-filter>
);
</activity>
mainLayout.setBackgroundColor(randomColor);
</application>
}
</manifest>
}
Practical 23
Develop a Program to Build Camera
Xml code

<?xml version="1.0" encoding="utf-8"?> import android.os.Bundle;

<RelativeLayout import android.provider.MediaStore;


xmlns:android="http://schemas.android.com/apk/res
import android.widget.Button;
/android"
import android.widget.ImageView;
xmlns:tools="http://schemas.android.com/tools"
import androidx.annotation.Nullable;
android:layout_width="match_parent"
import
android:layout_height="match_parent"
androidx.appcompat.app.AppCompatActivity;
tools:context=".MainActivity">
public class MainActivity extends
<!-- Button to open Camera --> AppCompatActivity {

<Button private static final int pic_id = 123;

android:id="@+id/camera_button" Button camera_open_id;

android:layout_width="100dp" ImageView click_image_id;

android:layout_height="50dp" @Override
android:layout_marginStart="150dp" protected void onCreate(Bundle
savedInstanceState) {
android:text="Camera" />
super.onCreate(savedInstanceState);
<!-- ImageView to display captured image -->
setContentView(R.layout.activity_main);
<ImageView
camera_open_id =
android:id="@+id/click_image"
findViewById(R.id.camera_button);
android:layout_width="350dp"
click_image_id =
android:layout_height="450dp" findViewById(R.id.click_image);

android:layout_marginStart="30dp" camera_open_id.setOnClickListener(v -> {

android:layout_marginTop="70dp" Intent camera_intent = new


Intent(MediaStore.ACTION_IMAGE_CAPTURE);
android:layout_marginBottom="10dp" />
startActivityForResult(camera_intent,
</RelativeLayout>
pic_id);
Java code
});
package com.example.pr_23;
}
import android.content.Intent;
@Override
import android.graphics.Bitmap;
protected void onActivityResult(int requestCode,
int resultCode, @Nullable Intent data) {

super.onActivityResult(requestCode,
resultCode, data);

if (requestCode == pic_id && resultCode ==


RESULT_OK && data != null) {

Bitmap photo = (Bitmap)


data.getExtras().get("data");

click_image_id.setImageBitmap(photo);

} }}
Practical 24
Develop a Program for Providing Bluetooth Connectivity
Java code turnOnBtn.setOnClickListener(v ->
turnOnBluetooth());
package com.example.madpracticalno24;
getVisibleBtn.setOnClickListener(v ->
import android.bluetooth.BluetoothAdapter; makeVisible());
import android.bluetooth.BluetoothDevice; listDevicesBtn.setOnClickListener(v ->
import android.content.Intent; listDevices());

import android.os.Bundle; turnOffBtn.setOnClickListener(v ->


turnOffBluetooth());
import android.view.View;
}
import android.widget.Button;

import android.widget.Toast;
private void turnOnBluetooth() {
import
androidx.appcompat.app.AppCompatActivity; if (!bluetoothAdapter.isEnabled()) {

import java.util.Set; Intent enableBtIntent = new


Intent(BluetoothAdapter.ACTION_REQUEST_EN
public class MainActivity extends ABLE);
AppCompatActivity {
startActivityForResult(enableBtIntent,
private static final int REQUEST_ENABLE_BT REQUEST_ENABLE_BT);
= 1;
} else {
private BluetoothAdapter bluetoothAdapter;
Toast.makeText(this, "Bluetooth is already
@Override on", Toast.LENGTH_SHORT).show();
protected void onCreate(Bundle }
savedInstanceState) {
}
super.onCreate(savedInstanceState);
private void makeVisible() {
setContentView(R.layout.activity_main);
Intent discoverableIntent = new
bluetoothAdapter = Intent(BluetoothAdapter.ACTION_REQUEST_DIS
BluetoothAdapter.getDefaultAdapter(); COVERABLE);
Button turnOnBtn =
findViewById(R.id.turn_on_btn); discoverableIntent.putExtra(BluetoothAdapter.EXT
Button getVisibleBtn = RA_DISCOVERABLE_DURATION, 300);
findViewById(R.id.get_visible_btn); startActivity(discoverableIntent);
Button listDevicesBtn = }
findViewById(R.id.list_devices_btn);
private void listDevices() {
Button turnOffBtn =
findViewById(R.id.turn_off_btn);
Set<BluetoothDevice> pairedDevices = android:layout_height="match_parent"
bluetoothAdapter.getBondedDevices();
android:orientation="vertical"
StringBuilder devicesList = new
android:padding="16dp">
StringBuilder();
<!-- Button to turn on Bluetooth -->

<Button
if (!pairedDevices.isEmpty()) {
android:id="@+id/turn_on_btn"
for (BluetoothDevice device :
pairedDevices) { android:layout_width="match_parent"
devicesList.append("Device: android:layout_height="wrap_content"
").append(device.getName()).append("\n")
android:text="Turn On Bluetooth" />
.append("MAC Address:
<!-- Button to make Bluetooth discoverable -->
").append(device.getAddress()).append("\n\n");
<Button
}
android:id="@+id/get_visible_btn"
Toast.makeText(this, devicesList.toString(),
Toast.LENGTH_LONG).show(); android:layout_width="match_parent"

} else { android:layout_height="wrap_content"

Toast.makeText(this, "No paired devices android:text="Make Device Discoverable" />


found", Toast.LENGTH_SHORT).show();
<!-- Button to list paired Bluetooth devices -->
} }
<Button
private void turnOffBluetooth() {
android:id="@+id/list_devices_btn"
if (bluetoothAdapter.isEnabled()) {
android:layout_width="match_parent"
bluetoothAdapter.disable();
android:layout_height="wrap_content"
Toast.makeText(this, "Bluetooth turned off",
android:text="List Paired Devices" />
Toast.LENGTH_SHORT).show();
<!-- Button to turn off Bluetooth -->
} else {
<Button
Toast.makeText(this, "Bluetooth is already
off", Toast.LENGTH_SHORT).show(); android:id="@+id/turn_off_btn"

} }} android:layout_width="match_parent"

Xml code android:layout_height="wrap_content"

<?xml version="1.0" encoding="utf-8"?> android:text="Turn Off Bluetooth" />

<LinearLayout </LinearLayout>
Android Manifest
xmlns:android="http://schemas.android.com/apk/res
<?xml version="1.0" encoding="utf-8"?>
/android"

android:layout_width="match_parent"
<manifest </intent-filter>
xmlns:android="http://schemas.android.com/apk/res
</activity>
/android"
</application>
package="com.example.madpracticalno24">
</manifest>
<!-- Bluetooth permissions for Android 12+ -->

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

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

<!-- Bluetooth permissions for older versions -->

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

<uses-permission
android:name="android.permission.BLUETOOTH_
ADMIN"/>
<application

android:allowBackup="true"

android:supportsRtl="true"

android:theme="@style/Theme.MadPracticalNo24"
>

<activity android:name=".MainActivity"

android:exported="true">
<intent-filter>

<action
android:name="android.intent.action.MAIN" />

<category
android:name="android.intent.category.LAUNCHE
R" />
Practical 25
Develop a Program for Animation
Xml code app:layout_constraintStart_toStartOf="parent"

<?xml version="1.0" encoding="utf-8"?> app:layout_constraintTop_toTopOf="parent">

<androidx.constraintlayout.widget.ConstraintLayou
t
<ImageView

android:id="@+id/img"
xmlns:android="http://schemas.android.com/apk/res
/android" android:layout_width="match_parent"

xmlns:app="http://schemas.android.com/apk/res- android:layout_height="wrap_content"
auto"
android:src="@drawable/img" />
xmlns:tools="http://schemas.android.com/tools"
<Button
android:layout_width="match_parent"
android:onClick="b1"
android:layout_height="match_parent"
android:layout_width="wrap_content"
tools:context=".MainActivity">
android:layout_height="wrap_content"
<EditText
android:layout_gravity="center_horizontal"
android:id="@+id/editTextTextPersonName"
android:layout_marginTop="15dp"
android:layout_width="162dp"
android:text="Clockwise / Anti Clockwise"
android:layout_height="48dp" />

android:ems="10" <Button

android:inputType="textPersonName" android:onClick="b2"
android:text="Atharva Butte" android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_gravity="center_horizontal"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="15dp"
/>
android:text="Zoom In / Out" />
<LinearLayout
<Button
android:layout_width="319dp"
android:onClick="b3"
android:layout_height="549dp"
android:layout_width="wrap_content"
android:layout_marginTop="112dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="15dp"
app:layout_constraintHorizontal_bias="0.63"
android:text="Fade In / Out" /> public void onAnimationStart(Animation
animation) { }
</LinearLayout>
@Override
</androidx.constraintlayout.widget.ConstraintLayo
ut> public void onAnimationEnd(Animation
animation) {

img.startAnimation(ant_rot);
Java code
}
package com.example.practical25;
@Override
import
androidx.appcompat.app.AppCompatActivity; public void onAnimationRepeat(Animation
animation) { }
import android.os.Bundle;
});
import android.view.View;
img.startAnimation(rot);
import android.view.animation.Animation;
}
import android.view.animation.AnimationUtils;
public void b2(View v) {
import android.widget.ImageView;
Animation zom_in =
public class MainActivity extends
AnimationUtils.loadAnimation(this,
AppCompatActivity {
R.anim.zoom_in);
ImageView img;
Animation zom_out =
@Override AnimationUtils.loadAnimation(this,
R.anim.zoom_out);
protected void onCreate(Bundle
savedInstanceState) { zom_in.setAnimationListener(new
Animation.AnimationListener() {
super.onCreate(savedInstanceState);
@Override
setContentView(R.layout.activity_main);
public void onAnimationStart(Animation
img = findViewById(R.id.img);
animation) { }
}
@Override
public void b1(View v) {
public void onAnimationEnd(Animation
Animation rot = animation) {
AnimationUtils.loadAnimation(this, R.anim.rotate);
img.startAnimation(zom_out);
Animation ant_rot =
}
AnimationUtils.loadAnimation(this,
R.anim.anti_rotate); @Override

rot.setAnimationListener(new public void onAnimationRepeat(Animation


Animation.AnimationListener() { animation) { }

@Override });

img.startAnimation(zom_in);
} }

public void b3(View v) { }

Animation fad_in =
AnimationUtils.loadAnimation(this,
R.anim.fade_in);

Animation fad_out =
AnimationUtils.loadAnimation(this,
R.anim.fade_out);

fad_in.setAnimationListener(new
Animation.AnimationListener() {

@Override

public void onAnimationStart(Animation


animation) { }
@Override

public void onAnimationEnd(Animation


animation) {

img.startAnimation(fad_out);

}
@Override

public void onAnimationRepeat(Animation


animation) { }

});

img.startAnimation(fad_in);
Practical 26
Perform Async task using SQLite
Xml code Java code

<?xml version="1.0" encoding="utf-8"?> package com.example.sql;

<RelativeLayout import
xmlns:android="http://schemas.android.com/apk/res androidx.appcompat.app.AppCompatActivity;
/android"
import android.database.Cursor;
android:layout_width="match_parent"
import android.os.Bundle;
android:layout_height="match_parent"
import android.view.View;
android:padding="16dp">
import android.widget.ArrayAdapter;
<EditText
import android.widget.Button;
android:id="@+id/editTextName"
import android.widget.EditText;
android:layout_width="match_parent"
import android.widget.ListView;
android:layout_height="wrap_content"
import android.widget.Toast;
android:hint="Enter Name"
import java.util.ArrayList;
android:inputType="text" />
import java.util.List;
<Button
public class MainActivity extends
android:id="@+id/buttonInsert" AppCompatActivity {

android:layout_width="wrap_content" private EditText editTextName;

android:layout_height="wrap_content" private Button buttonInsert;


android:layout_below="@id/editTextName" private ListView listViewData;

android:layout_marginTop="16dp" private DatabaseHelper databaseHelper;

android:text="Insert Data" /> private ArrayAdapter<String> dataAdapter;

<ListView private List<String> dataList;

android:id="@+id/listViewData" @Override

android:layout_width="match_parent" protected void onCreate(Bundle


savedInstanceState) {
android:layout_height="wrap_content"
super.onCreate(savedInstanceState);
android:layout_below="@id/buttonInsert"
setContentView(R.layout.activity_main);
android:layout_marginTop="24dp" />
editTextName =
</RelativeLayout>
findViewById(R.id.editTextName);
buttonInsert = public void onDataFetched(Cursor cursor) {
findViewById(R.id.buttonInsert);
dataList.clear();
listViewData =
if (cursor != null &&
findViewById(R.id.listViewData);
cursor.moveToFirst()) {
databaseHelper = new DatabaseHelper(this);
do {
dataList = new ArrayList<>();
String name =
dataAdapter = new ArrayAdapter<>(this, cursor.getString(cursor.getColumnIndex(DatabaseH
android.R.layout.simple_list_item_1, dataList); elper.COLUMN_NAME));
listViewData.setAdapter(dataAdapter); dataList.add(name);

buttonInsert.setOnClickListener(new } while (cursor.moveToNext());


View.OnClickListener() {
cursor.close();
@Override
}
public void onClick(View v) {
dataAdapter.notifyDataSetChanged();
String name =
}
editTextName.getText().toString().trim();
});
if (!name.isEmpty()) {
}}
databaseHelper.insertDataAsync(name,
new DatabaseHelper.DataInsertListener() { Helper class

@Override package com.example.sql;

public void onDataInserted() { import android.content.ContentValues;

Toast.makeText(MainActivity.this, import android.content.Context;


"Data Inserted Successfully",
import android.database.Cursor;
Toast.LENGTH_SHORT).show();
import android.database.sqlite.SQLiteDatabase;
fetchDataAndUpdateUI();
import android.database.sqlite.SQLiteOpenHelper;
} });
import android.os.AsyncTask;
editTextName.setText("");
public class DatabaseHelper extends
}}
SQLiteOpenHelper {
});
private static final String DATABASE_NAME =
fetchDataAndUpdateUI(); "my_database";

} private static final String TABLE_NAME =


"my_table";
private void fetchDataAndUpdateUI() {
private static final String COLUMN_ID = "id";
databaseHelper.fetchData(new
DatabaseHelper.DataFetchListener() { public static final String COLUMN_NAME =
"name";
@Override
public DatabaseHelper(Context context) { public void fetchData(DataFetchListener listener)
{
super(context, DATABASE_NAME, null, 1);
new FetchDataAsyncTask(listener).execute();
}
}
@Override
private class InsertDataAsyncTask extends
public void onCreate(SQLiteDatabase db) {
AsyncTask<String, Void, Void> {
String createTable = "CREATE TABLE " +
private DataInsertListener listener;
TABLE_NAME + " (" +
public
COLUMN_ID + " INTEGER PRIMARY
InsertDataAsyncTask(DataInsertListener listener) {
KEY AUTOINCREMENT, " +
this.listener = listener;
COLUMN_NAME + " TEXT)";
}
db.execSQL(createTable);
@Override
}
protected Void doInBackground(String...
@Override
strings) {
public void onUpgrade(SQLiteDatabase db, int
String name = strings[0];
oldVersion, int newVersion) {
insertData(name);
db.execSQL("DROP TABLE IF EXISTS " +
TABLE_NAME); return null;

onCreate(db); }
} @Override

public void insertData(String name) { protected void onPostExecute(Void aVoid) {

SQLiteDatabase db = if (listener != null) {


this.getWritableDatabase();
listener.onDataInserted();
ContentValues contentValues = new
}} }
ContentValues();
private class FetchDataAsyncTask extends
contentValues.put(COLUMN_NAME, name);
AsyncTask<Void, Void, Cursor> {
db.insert(TABLE_NAME, null,
private DataFetchListener listener;
contentValues);
public
db.close();
FetchDataAsyncTask(DataFetchListener listener) {
}
this.listener = listener;
public void insertDataAsync(String name,
}
DataInsertListener listener) {
@Override
new
InsertDataAsyncTask(listener).execute(name); protected Cursor doInBackground(Void...
voids) {
}
SQLiteDatabase db =
getReadableDatabase();

return db.query(TABLE_NAME, null, null,


null, null, null, null);

@Override

protected void onPostExecute(Cursor cursor) {

if (listener != null) {

listener.onDataFetched(cursor);

}}}

public interface DataInsertListener {

void onDataInserted();
}
public interface DataFetchListener {

void onDataFetched(Cursor cursor);

}
Practical 27
Create sample application with login module. (Check username and password) On
successful login, Change Text View “Login Successful” and on login fail, alert user using
Toast “Login fail”.
Xml code
android:layout_below="@id/editTextUsername"
<?xml version="1.0" encoding="utf-8"?>
android:layout_marginTop="20dp"
<RelativeLayout
android:layout_marginHorizontal="20dp" />

xmlns:android="http://schemas.android.com/apk/res android:id="@+id/btnLogin"
/android"
android:layout_width="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Login"
android:layout_height="match_parent"

tools:context=".MainActivity"> android:layout_below="@id/editTextPassword"

<EditText android:layout_centerHorizontal="true"

android:id="@+id/editTextUsername" android:layout_marginTop="20dp" />

android:layout_width="match_parent" <TextView

android:layout_height="wrap_content" android:id="@+id/textViewLoginStatus"

android:hint="Username" android:layout_width="wrap_content"

android:layout_marginTop="50dp" android:layout_height="wrap_content"

android:layout_marginHorizontal="20dp" /> android:text=""

<EditText android:layout_below="@id/btnLogin"

android:id="@+id/editTextPassword" android:layout_centerHorizontal="true"

android:layout_width="match_parent" android:layout_marginTop="20dp" />


android:layout_height="wrap_content" </RelativeLayout>

android:hint="Password"

android:inputType="textPassword" Java code

package com.example.pr_27_01; import android.widget.TextView;

import android.os.Bundle; import android.widget.Toast;


import android.view.View; import
androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;
public class MainActivity extends
import android.widget.EditText;
AppCompatActivity {
private EditText editTextUsername, editTextPassword.getText().clear();
editTextPassword;
} else {
private Button btnLogin;
Toast.makeText(MainActivity.this, "Login
private TextView textViewLoginStatus; Failed", Toast.LENGTH_SHORT).show();}

private final String validUsername = "rsmpoly"; }}

private final String validPassword = "rsm1002";

@Override

protected void onCreate(Bundle


savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editTextUsername =
findViewById(R.id.editTextUsername);

editTextPassword =
findViewById(R.id.editTextPassword);

btnLogin = findViewById(R.id.btnLogin);

textViewLoginStatus =
findViewById(R.id.textViewLoginStatus);

btnLogin.setOnClickListener(new
View.OnClickListener() {

@Override

public void onClick(View v) {

validateLogin();
}});}
private void validateLogin() {

String username =
editTextUsername.getText().toString().trim();

String password =
editTextPassword.getText().toString().trim();

if (username.equals(validUsername) &&
password.equals(validPassword)) {
textViewLoginStatus.setText("Login
Successful");

editTextUsername.getText().clear();
Practical 28
Create login application where you will have to validate username and password till the
username and password is not validated, login button should remain disabled.
Xml code
editTextUsername.addTextChangedListener(loginTe
package com.example.pr_28_01; xtWatcher);
import android.os.Bundle;

import android.text.Editable; editTextPassword.addTextChangedListener(loginTe


xtWatcher);
import android.text.TextWatcher;
btnLogin.setOnClickListener(new
import android.view.View; View.OnClickListener() {
import android.widget.Button; @Override
import android.widget.EditText; public void onClick(View v) {
import android.widget.Toast; validateLogin();
import }});}
androidx.appcompat.app.AppCompatActivity;
private final TextWatcher loginTextWatcher =
public class MainActivity extends new TextWatcher() {
AppCompatActivity {
@Override
private EditText editTextUsername,
editTextPassword; public void beforeTextChanged(CharSequence
s, int start, int count, int after) {}
private Button btnLogin;
@Override
private final String validUsername = "rsmpoly";
public void onTextChanged(CharSequence s,
private final String validPassword = "rsm1002"; int start, int before, int count) {}
@Override @Override
protected void onCreate(Bundle public void afterTextChanged(Editable s) {
savedInstanceState) {

super.onCreate(savedInstanceState); btnLogin.setEnabled(!editTextUsername.getText().t
setContentView(R.layout.activity_main); oString().isEmpty() &&

editTextUsername =
findViewById(R.id.editTextUsername); !editTextPassword.getText().toString().isEmpty());

editTextPassword = } };
findViewById(R.id.editTextPassword); private void validateLogin() {
btnLogin = findViewById(R.id.btnLogin); String username =
btnLogin.setEnabled(false); editTextUsername.getText().toString().trim();
String password = editTextUsername =
editTextPassword.getText().toString().trim(); findViewById(R.id.editTextUsername);

if (username.equals(validUsername) && editTextPassword =


password.equals(validPassword)) { findViewById(R.id.editTextPassword);

Toast.makeText(MainActivity.this, "Login btnLogin = findViewById(R.id.btnLogin);


Successful", Toast.LENGTH_SHORT).show();
btnLogin.setEnabled(false);
} else {

Toast.makeText(MainActivity.this, "Login editTextUsername.addTextChangedListener(loginTe


Unsuccessful", Toast.LENGTH_SHORT).show(); xtWatcher);

} }}
editTextPassword.addTextChangedListener(loginTe
Java code
xtWatcher);
package com.example.pr_28_01;
btnLogin.setOnClickListener(new
import android.os.Bundle; View.OnClickListener() {

import android.text.Editable; @Override

import android.text.TextWatcher; public void onClick(View v) {

import android.view.View; validateLogin();

import android.widget.Button; } }); }

import android.widget.EditText; private final TextWatcher loginTextWatcher =


new TextWatcher() {
import android.widget.Toast;
@Override
import
androidx.appcompat.app.AppCompatActivity; public void beforeTextChanged(CharSequence
s, int start, int count, int after) {}
public class MainActivity extends
AppCompatActivity { @Override

private EditText editTextUsername, public void onTextChanged(CharSequence s,


editTextPassword; int start, int before, int count) {}

private Button btnLogin; @Override

private final String validUsername = "rsmpoly"; public void afterTextChanged(Editable s) {

private final String validPassword = "rsm1002";


btnLogin.setEnabled(!editTextUsername.getText().t
@Override
oString().isEmpty() &&
protected void onCreate(Bundle
savedInstanceState) {
!editTextPassword.getText().toString().isEmpty());
super.onCreate(savedInstanceState);
}
setContentView(R.layout.activity_main);
};
private void validateLogin() {

String username =
editTextUsername.getText().toString().trim();
String password =
editTextPassword.getText().toString().trim();

if (username.equals(validUsername) &&
password.equals(validPassword)) {

Toast.makeText(MainActivity.this, "Login
Successful", Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "Login
Unsuccessful", Toast.LENGTH_SHORT).show();

} }}
Practical 30
Develop a program to send and receive Email
Xml Code android:gravity="top"

<?xml version="1.0" encoding="utf-8"?> android:layout_below="@id/editTextSubject"

<RelativeLayout android:layout_marginTop="8dp"/>

<Button
xmlns:android="http://schemas.android.com/apk/res
android:id="@+id/buttonSend"
/android"
android:layout_width="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Send"
android:layout_height="match_parent"
android:layout_below="@id/editTextBody"
android:padding="16dp"
android:layout_centerHorizontal="true"
tools:context=".MainActivity">
android:layout_marginTop="16dp"/>
<EditText
</RelativeLayout>
android:id="@+id/editTextTo"
Java code
android:layout_width="match_parent"
package com.example.madpracticalno30;
android:layout_height="wrap_content"
import android.content.Intent;
android:hint="To" />
import android.net.Uri;
<EditText
import android.os.Bundle;
android:id="@+id/editTextSubject"
import android.view.View;
android:layout_width="match_parent"
import android.widget.Button;
android:layout_height="wrap_content"
import android.widget.EditText;
android:hint="Subject"
import
android:layout_below="@id/editTextTo"
androidx.appcompat.app.AppCompatActivity;
android:layout_marginTop="8dp"/>
public class MainActivity extends
<EditText AppCompatActivity {

android:id="@+id/editTextBody" private EditText editTextTo, editTextSubject,


editTextBody;
android:layout_width="match_parent"
private Button buttonSend;
android:layout_height="wrap_content"
@Override
android:hint="Body"
protected void onCreate(Bundle
android:minLines="5"
savedInstanceState) {
super.onCreate(savedInstanceState); } }}

setContentView(R.layout.activity_main);

editTextTo = findViewById(R.id.editTextTo);

editTextSubject =
findViewById(R.id.editTextSubject);

editTextBody =
findViewById(R.id.editTextBody);

buttonSend = findViewById(R.id.buttonSend);

buttonSend.setOnClickListener(new
View.OnClickListener() {

@Override

public void onClick(View view) {


sendEmail();

}});

private void sendEmail() {

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

String body =
editTextBody.getText().toString().trim();

Intent intent = new


Intent(Intent.ACTION_SENDTO);

intent.setData(Uri.parse("mailto:")); // Ensures
only email apps handle this intent

intent.putExtra(Intent.EXTRA_EMAIL, new
String[]{to});

intent.putExtra(Intent.EXTRA_SUBJECT,
subject);

intent.putExtra(Intent.EXTRA_TEXT, body);

if
(intent.resolveActivity(getPackageManager()) !=
null) {

startActivity(intent);

You might also like