PRACTICAL 12 — IMAGE ANIMATION & COLOR EFFECTS
Project Structure
MyApplication/
│
├── app/
│ ├── src/
│ │ ├── main/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java/
│ │ │ │ └── com/
│ │ │ │ └── example/
│ │ │ │ └── myapplication/
│ │ │ │ ├── MainActivity.java
│ │ │ │ └── MainActivity2.java ← (YOUR PRACTICAL 12 JAVA)
│ │ │ │
│ │ │ ├── res/
│ │ │ │ ├── layout/
│ │ │ │ │ ├── activity_main.xml
│ │ │ │ │ └── activity_main2.xml ← (YOUR PRACTICAL 12 LAYOUT)
│ │ │ │ │
│ │ │ │ ├── anim/ ← place ALL animation XML files here
│ │ │ │ │ ├── rotate.xml
│ │ │ │ │ ├── translate.xml
│ │ │ │ │ ├── scale.xml
│ │ │ │ │ ├── fade_in.xml
│ │ │ │ │ ├── fade_out.xml
│ │ │ │ │ ├── bounce.xml
│ │ │ │ │ ├── zoom_in.xml
│ │ │ │ │ └── zoom_out.xml
│ │ │ │ │
│ │ │ │ ├── drawable/
│ │ │ │ │ ├── killua.png ← (YOUR image)
│ │ │ │ │ └── other_images...
│ │ │ │ │
│ │ │ │ ├── mipmap-hdpi/
│ │ │ │ ├── mipmap-mdpi/
│ │ │ │ ├── mipmap-xhdpi/
│ │ │ │ ├── mipmap-xxhdpi/
│ │ │ │ ├── mipmap-xxxhdpi/
│ │ │ │ └── values/
│ │ │ │ ├── colors.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── strings.xml
│ │ │ │
│ │ │ └── ...
│ │ └── test/
│ │
│ ├── build.gradle (Module: app)
│ └── ...
│
├── build.gradle (Project)
└── settings.gradle
Java — MainActivity2.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
Button btnRotate, btnTranslate, btnScaling,
btnFadeIn, btnFadeOut, btnBounce, btnGrey,
btnInvert;
ImageView imageView;
boolean isGrey = false;
boolean isInverted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = findViewById(R.id.imageView);
btnRotate = findViewById(R.id.btnRotate);
btnTranslate = findViewById(R.id.btnTranslate);
btnScaling = findViewById(R.id.btnScaling);
btnFadeIn = findViewById(R.id.btnFadeIn);
btnFadeOut = findViewById(R.id.btnFadeOut);
btnBounce = findViewById(R.id.btnBounce);
btnGrey = findViewById(R.id.btnGrey);
btnInvert = findViewById(R.id.btnInvert);
// Rotate
btnRotate.setOnClickListener(v -> {
Animation rotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
imageView.startAnimation(rotate);
});
// Translate
btnTranslate.setOnClickListener(v -> {
Animation translate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.translate);
imageView.startAnimation(translate);
});
// Scale
btnScaling.setOnClickListener(v -> {
Animation scale = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale);
imageView.startAnimation(scale);
});
// Fade in
btnFadeIn.setOnClickListener(v -> {
Animation fadeIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
imageView.startAnimation(fadeIn);
});
// Fade out
btnFadeOut.setOnClickListener(v -> {
Animation fadeOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);
imageView.startAnimation(fadeOut);
});
// Bounce
btnBounce.setOnClickListener(v -> {
Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
imageView.startAnimation(bounce);
});
// Convert to grayscale / restore
btnGrey.setOnClickListener(v -> {
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.killua);
if (originalBitmap == null) {
Toast.makeText(this, "Drawable R.drawable.killua missing", Toast.LENGTH_SHORT).show();
return;
}
Bitmap processedBitmap = Bitmap.createBitmap(
originalBitmap.getWidth(),
originalBitmap.getHeight(),
originalBitmap.getConfig()
);
if (isGrey) {
imageView.setImageBitmap(originalBitmap);
isGrey = false;
} else {
for (int x = 0; x < originalBitmap.getWidth(); x++) {
for (int y = 0; y < originalBitmap.getHeight(); y++) {
int pixel = originalBitmap.getPixel(x, y);
int alpha = Color.alpha(pixel);
// correct average of R,G,B
int gray = (Color.red(pixel) + Color.green(pixel) + Color.blue(pixel)) / 3;
processedBitmap.setPixel(x, y, Color.argb(alpha, gray, gray, gray));
}
}
imageView.setImageBitmap(processedBitmap);
isGrey = true;
// reset inverted flag if set
isInverted = false;
}
});
// Invert colors / restore
btnInvert.setOnClickListener(v -> {
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.killua);
if (originalBitmap == null) {
Toast.makeText(this, "Drawable R.drawable.killua missing", Toast.LENGTH_SHORT).show();
return;
}
Bitmap processedBitmap = Bitmap.createBitmap(
originalBitmap.getWidth(),
originalBitmap.getHeight(),
originalBitmap.getConfig()
);
if (isInverted) {
imageView.setImageBitmap(originalBitmap);
isInverted = false;
} else {
for (int x = 0; x < originalBitmap.getWidth(); x++) {
for (int y = 0; y < originalBitmap.getHeight(); y++) {
int pixel = originalBitmap.getPixel(x, y);
int alpha = Color.alpha(pixel);
int red = 255 - Color.red(pixel);
int green = 255 - Color.green(pixel);
int blue = 255 - Color.blue(pixel);
processedBitmap.setPixel(x, y, Color.argb(alpha, red, green, blue));
}
}
imageView.setImageBitmap(processedBitmap);
isInverted = true;
// reset grey flag if set
isGrey = false;
}
});
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingBottom="24dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="280dp"
android:layout_height="280dp"
android:src="@drawable/killua"
android:scaleType="centerCrop"
android:contentDescription="demo image"
android:layout_marginBottom="16dp"/>
<Button
android:id="@+id/btnRotate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rotate" />
<Button
android:id="@+id/btnTranslate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Translate" />
<Button
android:id="@+id/btnScaling"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scale" />
<Button
android:id="@+id/btnFadeIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fade In" />
<Button
android:id="@+id/btnFadeOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fade Out" />
<Button
android:id="@+id/btnBounce"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bounce" />
<Button
android:id="@+id/btnGrey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Grey Image" />
<Button
android:id="@+id/btnInvert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Invert Colors" />
</LinearLayout>
</ScrollView>
Animations — place in app/src/main/res/anim/
Create the anim folder if it doesn't exist, then create the following files.
bounce.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="1.0"
android:toXScale="1.2"
android:fromYScale="1.0"
android:toYScale="1.2"
android:pivotX="50%"
android:pivotY="50%"
android:duration="500"
android:repeatCount="5"
android:repeatMode="reverse" />
fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="1500"
android:fillAfter="true" />
fade_out.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1500"
android:fillAfter="true" />
rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:repeatCount="infinite"
android:repeatMode="restart" />
scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0"
android:toXScale="2.0"
android:fromYScale="1.0"
android:toYScale="2.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1500"
android:repeatCount="1"
android:repeatMode="reverse"
android:fillAfter="true" />
</set>
translate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="30"
android:toXDelta="300"
android:fromYDelta="20"
android:toYDelta="200"
android:duration="3000"
android:repeatCount="3"
android:repeatMode="restart"
android:startOffset="1000"
android:fillAfter="true" />
</set>
zoom_in.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="1.5"
android:fromYScale="0.5"
android:toYScale="1.5"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1500"
android:fillAfter="true" />
zoom_out.xml
<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="1.5"
android:toXScale="0.5"
android:fromYScale="1.5"
android:toYScale="0.5"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1500"
android:fillAfter="true" />
Manifest — add the activity (if not already present)
Add inside in AndroidManifest.xml:
<activity android:name=".MainActivity2" android:exported="true" />
Resourse
Put an image named killua.png (or .jpg) into app/src/main/res/drawable/killua.png — the Java references R.drawable.killua.
If you prefer a different image name, update both the layout (android:src="@drawable/killua") and the Java (BitmapFactory.decodeResource(..., R.drawable.killua)).
Practical 13
Prepare Student Database with table Student with any 5 relevent fields, perform the following operations on it.
(A) Create table
(B) Insert new records
(c) View all the stored records
(D) Search record based on roll number
(E) Delete record based on Name
(F) Update record based on roll number
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.DatePickerDialog;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private EditText edtname, edtrno, edtDob, edtstream, edtAddress;
private Button btninsert, btnread, btndelete, btnsearch, btnupdate;
private TextView txtdata;
private DatabaseHandler con;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
con = new DatabaseHandler(this);
con.getWritableDatabase();
setupButtonListeners();
}
private void initializeViews() {
btninsert = findViewById(R.id.btninsert);
btnread = findViewById(R.id.btnread);
btndelete = findViewById(R.id.btndelete);
btnsearch = findViewById(R.id.btnsearch);
btnupdate = findViewById(R.id.btnupdate);
txtdata = findViewById(R.id.txtdata);
edtname = findViewById(R.id.edtname);
edtrno = findViewById(R.id.edtrno);
edtDob = findViewById(R.id.edtDob);
edtstream = findViewById(R.id.edtstream);
edtAddress = findViewById(R.id.edtAddress);
}
private void setupButtonListeners() {
btninsert.setOnClickListener(v -> {
String name = edtname.getText().toString();
int rno = Integer.parseInt(edtrno.getText().toString());
String dob = edtDob.getText().toString();
String stream = edtstream.getText().toString();
String address = edtAddress.getText().toString();
boolean status = con.saveData(name, rno, dob, stream, address);
Toast.makeText(
getApplicationContext(),
status ? "Inserted successfully" : "Insertion failed",
Toast.LENGTH_LONG
).show();
});
btnread.setOnClickListener(v -> {
Cursor c = con.showData();
StringBuilder buffer = new StringBuilder();
if (c.getCount() == 0) {
Toast.makeText(getApplicationContext(), "No record Found", Toast.LENGTH_LONG).show();
return;
}
while (c.moveToNext()) {
buffer.append("ID: ").append(c.getString(0)).append("\n");
buffer.append("ROLL Number: ").append(c.getInt(1)).append("\n");
buffer.append("Student name: ").append(c.getString(2)).append("\n");
String dobStr = c.getString(3);
buffer.append("Date of Birth: ").append(dobStr).append("\n");
int age = calculateAge(dobStr);
buffer.append("Age: ").append(age == -1 ? "N/A" : age).append("\n");
buffer.append("Stream: ").append(c.getString(4)).append("\n");
buffer.append("Address: ").append(c.getString(5)).append("\n\n");
}
showMessage("Records", buffer.toString());
});
btndelete.setOnClickListener(v -> {
String name = edtname.getText().toString();
int status = con.deleteRecord(name);
Toast.makeText(
getApplicationContext(),
status > 0 ? "Deleted successfully" : "Deletion failed",
Toast.LENGTH_LONG
).show();
});
btnupdate.setOnClickListener(v -> {
String name = edtname.getText().toString();
int rno = Integer.parseInt(edtrno.getText().toString());
int status = con.updateRecord(name, rno);
Toast.makeText(
getApplicationContext(),
status == -1 ? "Updated unsuccessfully" : "Updated successfully",
Toast.LENGTH_LONG
).show();
});
btnsearch.setOnClickListener(v -> {
Integer rno = Integer.parseInt(edtrno.getText().toString());
StringBuilder buffer = new StringBuilder();
Cursor c = con.searchData(rno);
if (c.getCount() == 0) {
Toast.makeText(getApplicationContext(), "No record Found", Toast.LENGTH_LONG).show();
showMessage("Records", "No record found");
return;
}
while (c.moveToNext()) {
buffer.append("ID: ").append(c.getString(0)).append("\n");
buffer.append("ROLL Number: ").append(c.getInt(1)).append("\n");
buffer.append("Student name: ").append(c.getString(2)).append("\n");
String dobStr = c.getString(3);
buffer.append("Date of Birth: ").append(dobStr).append("\n");
int age = calculateAge(dobStr);
buffer.append("Age: ").append(age == -1 ? "N/A" : age).append("\n");
buffer.append("Stream: ").append(c.getString(4)).append("\n");
buffer.append("Address: ").append(c.getString(5)).append("\n\n");
}
txtdata.setText(buffer.toString());
});
edtDob.setOnClickListener(v -> {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this,
(view, year1, monthOfYear, dayOfMonth) ->
edtDob.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year1),
year, month, day
);
datePickerDialog.show();
});
}
private void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
private int calculateAge(String dobStr) {
try {
@SuppressLint("SimpleDateFormat")
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
java.util.Date dobDate = sdf.parse(dobStr);
Calendar dob = Calendar.getInstance();
dob.setTime(dobDate);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH) ||
(today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
&& today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
DatabaseHandler.java
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "student.db";
private static final String TABLE_NAME = "student";
private static final int DB_VERSION = 7;
public DatabaseHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" +
"ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"RNO INTEGER," +
"NAME TEXT," +
"DOB TEXT," +
"STREAM TEXT," +
"ADDRESS TEXT" +
")";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean saveData(String name, int rno, String dob, String stream, String address) {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("RNO", rno);
cv.put("NAME", name);
cv.put("DOB", dob);
cv.put("STREAM", stream);
cv.put("ADDRESS", address);
long status = db.insert(TABLE_NAME, null, cv);
return status != -1;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Cursor showData() {
SQLiteDatabase db = getReadableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
public int deleteRecord(String name) {
SQLiteDatabase db = getWritableDatabase();
return db.delete(TABLE_NAME, "NAME=?", new String[]{name});
}
public int updateRecord(String name, int rno) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", name);
cv.put("RNO", rno);
return db.update(TABLE_NAME, cv, "RNO=" + rno, null);
}
public Cursor searchData(int rno) {
SQLiteDatabase db = getReadableDatabase();
return db.rawQuery("SELECT * FROM student WHERE RNO=?", new String[]{String.valueOf(rno)});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edtname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Student Name" />
<EditText
android:id="@+id/edtrno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll Number"
android:inputType="number" />
<EditText
android:id="@+id/edtDob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="DOB (dd/mm/yyyy)" />
<EditText
android:id="@+id/edtstream"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Stream" />
<EditText
android:id="@+id/edtAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Address" />
<Button
android:id="@+id/btninsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert" />
<Button
android:id="@+id/btnread"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Read" />
<Button
android:id="@+id/btnsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="@+id/btndelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="@+id/btnupdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update" />
<TextView
android:id="@+id/txtdata"
android:padding="10dp"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Results will appear here" />
</LinearLayout>
</ScrollView>
AndroidManifest.xml (required entry)
Add this inside :
<activity android:name=".MainActivity" android:exported="true"/>
Practical 14 - Create an Android application that allows users to play both audio and video files with media controls such as play, pause, and stop.
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
VideoView vv;
Button playBtn, pauseBtn, stopBtn, vplayBtn;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = findViewById(R.id.play);
pauseBtn = findViewById(R.id.pause);
stopBtn = findViewById(R.id.stop);
vplayBtn = findViewById(R.id.vplay);
vv = findViewById(R.id.vv);
// AUDIO: play
playBtn.setOnClickListener(v -> {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.sample);
mp.setOnCompletionListener(mediaPlayer -> {
// release when finished
mediaPlayer.release();
mp = null;
Toast.makeText(getApplicationContext(), "Audio completed", Toast.LENGTH_SHORT).show();
});
}
if (!mp.isPlaying()) {
mp.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_SHORT).show();
}
});
// AUDIO: pause
pauseBtn.setOnClickListener(v -> {
if (mp != null && mp.isPlaying()) {
mp.pause();
Toast.makeText(getApplicationContext(), "Audio paused", Toast.LENGTH_SHORT).show();
}
});
// STOP (audio) — also stop video if playing
stopBtn.setOnClickListener(v -> {
// stop audio
if (mp != null) {
if (mp.isPlaying()) mp.stop();
mp.release();
mp = null;
Toast.makeText(getApplicationContext(), "Audio stopped", Toast.LENGTH_SHORT).show();
}
// stop video if playing
if (vv != null && vv.isPlaying()) {
vv.stopPlayback();
Toast.makeText(getApplicationContext(), "Video stopped", Toast.LENGTH_SHORT).show();
}
});
// VIDEO: play
vplayBtn.setOnClickListener(v -> {
String path = "android.resource://" + getPackageName() + "/" + R.raw.video;
Uri uri = Uri.parse(path);
vv.setVideoURI(uri);
MediaController mc = new MediaController(MainActivity.this);
mc.setAnchorView(vv);
vv.setMediaController(mc);
vv.requestFocus();
vv.start();
});
}
@Override
protected void onPause() {
super.onPause();
// pause audio if playing
if (mp != null && mp.isPlaying()) {
mp.pause();
}
// pause video if playing
if (vv != null && vv.isPlaying()) {
vv.pause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mp != null) {
if (mp.isPlaying()) mp.stop();
mp.release();
mp = null;
}
if (vv != null) {
vv.stopPlayback();
}
}
}
Layout — activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play Audio" />
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause Audio"
android:layout_marginTop="8dp" />
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Audio / Video"
android:layout_marginTop="8dp" />
<Button
android:id="@+id/vplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play Video"
android:layout_marginTop="12dp" />
<VideoView
android:id="@+id/vv"
android:layout_width="match_parent"
android:layout_height="260dp"
android:layout_marginTop="12dp" />
</LinearLayout>
</ScrollView>
AndroidManifest.xml snippet
Add (or confirm) inside :
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Create app/src/main/res/raw/ (folder raw may not exist by default) and add:
sample.mp3 (or sample.wav) → referenced as R.raw.sample
video.mp4 → referenced as R.raw.video
Filename must be lowercase, no spaces. If you use other names, update R.raw.* references in MainActivity.java.
Practical 15 - Prepare a Student Database in Firebase Realtime Database with any five relevant fields, and perform the following operations:
(A) Create new records
(B) View all stored records
(C) Delete a record
(D) Update a record
Student.java
package com.example.firebase;
public class Student {
private String id;
private Integer rollno;
private String name;
private Double gradePointAverage;
private String department;
public Student() {
// required empty constructor for Firebase
}
public Student(String id, Integer rollno, String name, Double gradePointAverage, String department) {
this.id = id;
this.rollno = rollno;
this.name = name;
this.gradePointAverage = gradePointAverage;
this.department = department;
}
// getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public Integer getRollno() { return rollno; }
public void setRollno(Integer rollno) { this.rollno = rollno; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Double getGradePointAverage() { return gradePointAverage; }
public void setGradePointAverage(Double gradePointAverage) { this.gradePointAverage = gradePointAverage; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<LinearLayout
android:id="@+id/container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<EditText
android:id="@+id/edname"
android:hint="Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/edrollno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll No"
android:inputType="number" />
<EditText
android:id="@+id/edgpa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="GPA"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/eddept"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Department" />
<Button
android:id="@+id/btnadd"
android:text="Add Student"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"/>
<Button
android:id="@+id/btnupdate"
android:text="Update Student"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"/>
<Button
android:id="@+id/btndel"
android:text="Delete Student"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"/>
<Button
android:id="@+id/btnview"
android:text="View All Students"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"/>
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="8dp"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.firebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText edname, edrollno, edgpa, eddept;
Button btnadd, btnview, btndel, btnupdate;
ListView lv;
// to track selected item
String selectedId = "";
List<Student> studentList = new ArrayList<>();
FirebaseDatabase database;
DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// views
edname = findViewById(R.id.edname);
edrollno = findViewById(R.id.edrollno);
edgpa = findViewById(R.id.edgpa);
eddept = findViewById(R.id.eddept);
btnadd = findViewById(R.id.btnadd);
btnview = findViewById(R.id.btnview);
btnupdate = findViewById(R.id.btnupdate);
btndel = findViewById(R.id.btndel);
lv = findViewById(R.id.lv);
// init firebase reference (root node "student")
database = FirebaseDatabase.getInstance();
myRef = database.getReference("student");
// ADD
btnadd.setOnClickListener(v -> {
String name = edname.getText().toString().trim();
String rollStr = edrollno.getText().toString().trim();
String gpaStr = edgpa.getText().toString().trim();
String dept = eddept.getText().toString().trim();
if (name.isEmpty() || rollStr.isEmpty()) {
Toast.makeText(MainActivity.this, "Name and Roll required", Toast.LENGTH_SHORT).show();
return;
}
int roll = Integer.parseInt(rollStr);
double gpa = gpaStr.isEmpty() ? 0.0 : Double.parseDouble(gpaStr);
// new id from push
String id = myRef.push().getKey();
if (id == null) {
Toast.makeText(MainActivity.this, "Error generating id", Toast.LENGTH_SHORT).show();
return;
}
Student s = new Student(id, roll, name, gpa, dept);
myRef.child(id).setValue(s)
.addOnSuccessListener(aVoid -> {
Toast.makeText(MainActivity.this, "Student added", Toast.LENGTH_SHORT).show();
clearInputs();
})
.addOnFailureListener(e -> Toast.makeText(MainActivity.this, "Failed to add", Toast.LENGTH_SHORT).show());
});
// VIEW (reads once and updates list)
btnview.setOnClickListener(v -> fetchAllStudents());
// DELETE selected by selectedId (user chooses from ListView)
btndel.setOnClickListener(v -> {
if (selectedId.isEmpty()) {
Toast.makeText(MainActivity.this, "Select a student from list first", Toast.LENGTH_SHORT).show();
return;
}
myRef.child(selectedId).removeValue()
.addOnSuccessListener(aVoid -> {
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_SHORT).show();
selectedId = "";
fetchAllStudents();
})
.addOnFailureListener(e -> Toast.makeText(MainActivity.this, "Delete failed", Toast.LENGTH_SHORT).show());
});
// UPDATE selected record: write updated fields to same id
btnupdate.setOnClickListener(v -> {
if (selectedId.isEmpty()) {
Toast.makeText(MainActivity.this, "Select a student from list first", Toast.LENGTH_SHORT).show();
return;
}
String name = edname.getText().toString().trim();
String rollStr = edrollno.getText().toString().trim();
String gpaStr = edgpa.getText().toString().trim();
String dept = eddept.getText().toString().trim();
if (name.isEmpty() || rollStr.isEmpty()) {
Toast.makeText(MainActivity.this, "Name and Roll required", Toast.LENGTH_SHORT).show();
return;
}
int roll = Integer.parseInt(rollStr);
double gpa = gpaStr.isEmpty() ? 0.0 : Double.parseDouble(gpaStr);
Student s = new Student(selectedId, roll, name, gpa, dept);
myRef.child(selectedId).setValue(s)
.addOnSuccessListener(aVoid -> {
Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_SHORT).show();
clearInputs();
fetchAllStudents();
})
.addOnFailureListener(e -> Toast.makeText(MainActivity.this, "Update failed", Toast.LENGTH_SHORT).show());
});
// List item click -> populate selection
lv.setOnItemClickListener((parent, view, position, id) -> {
Student s = studentList.get(position);
selectedId = s.getId();
edname.setText(s.getName());
edrollno.setText(String.valueOf(s.getRollno()));
edgpa.setText(String.valueOf(s.getGradePointAverage()));
eddept.setText(s.getDepartment());
Toast.makeText(MainActivity.this, "Selected: " + s.getName(), Toast.LENGTH_SHORT).show();
});
// real-time listener (optional) to keep list synced
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
studentList.clear();
for (DataSnapshot sn : snapshot.getChildren()) {
Student s = sn.getValue(Student.class);
if (s != null) studentList.add(s);
}
refreshListView();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to read data.", Toast.LENGTH_SHORT).show();
}
});
// initial fetch (could be omitted since listener will populate)
fetchAllStudents();
}
private void fetchAllStudents() {
myRef.get().addOnSuccessListener(dataSnapshot -> {
studentList.clear();
for (DataSnapshot sn : dataSnapshot.getChildren()) {
Student s = sn.getValue(Student.class);
if (s != null) studentList.add(s);
}
refreshListView();
Toast.makeText(MainActivity.this, "Fetched " + studentList.size() + " students", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(e -> Toast.makeText(MainActivity.this, "Failed to fetch", Toast.LENGTH_SHORT).show());
}
private void refreshListView() {
List<String> display = new ArrayList<>();
for (Student s : studentList) {
display.add("Roll: " + s.getRollno() + " Name: " + s.getName() + " Dept: " + s.getDepartment());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this,
android.R.layout.simple_list_item_1, display);
lv.setAdapter(adapter);
}
private void clearInputs() {
edname.setText("");
edrollno.setText("");
edgpa.setText("");
eddept.setText("");
}
}
app/build.gradle (module) — add these dependencies & plugin
Open app/build.gradle and ensure you have:
plugins {
id 'com.android.application'
id 'com.google.gms.google-services' // add at bottom of file (or apply plugin)
}
android {
compileSdk 34
defaultConfig {
applicationId "com.example.firebase" // update to your package
minSdk 21
targetSdk 34
versionCode 1
versionName "1.0"
}
// ...
}
dependencies {
implementation platform('com.google.firebase:firebase-bom:32.2.0') // use latest BOM (adjust if needed)
implementation 'com.google.firebase:firebase-database'
implementation 'com.google.firebase:firebase-analytics' // optional
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
// other dependencies...
}
And at the bottom of the same file (if using apply plugin style), ensure:
// apply plugin: 'com.google.gms.google-services' // if not using plugins {} block
(If using the new plugins DSL, id 'com.google.gms.google-services' inside plugins {} is fine.)
Project-level build.gradle (add Google services classpath)
In the project build.gradle (the one in root), inside dependencies:
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.google.gms:google-services:4.3.15'
}
}
Firebase setup checklist (very important)
1.Go to Firebase Console → create a new project (or use existing).
2.Add an Android app with the package name you used in applicationId (e.g. com.example.firebase).
3.Download the generated google-services.json and place it into app/ (not the root).
4.In Firebase Console → Realtime Database → create a database, choose location, and set rules for testing:
For quick testing (NOT for production) use:
{
"rules": {
".read": true,
".write": true
}
}
(Later restrict rules before publishing.)
5.Sync Gradle, then run the app. The code uses node student under the DB root.
Practical 16 — GPS App (Full package)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gps">
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_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/Theme.Gps">
<activity android:name=".MainActivity" android:exported="true">
<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.example.gps;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager lm;
Button btnlocation;
TextView txtlocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtlocation = findViewById(R.id.txtlocation);
btnlocation = findViewById(R.id.btnlocation);
// Request runtime permission if not granted
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
}
btnlocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { getLocation(); }
});
}
private void getLocation() {
lm = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission not granted, request it
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
return;
}
// Request updates from GPS provider (minTime=5000ms, minDistance=100m)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 100, MainActivity.this);
Toast.makeText(this, "Requesting location updates...", Toast.LENGTH_SHORT).show();
}
@Override
public void onLocationChanged(@NonNull Location location) {
// location available
double lat = location.getLatitude();
double lon = location.getLongitude();
Toast.makeText(getApplicationContext(), "Lon: " + lon + " Lat: " + lat, Toast.LENGTH_LONG).show();
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null && !addresses.isEmpty()) {
String address = addresses.get(0).getAddressLine(0);
txtlocation.setText(address);
} else {
txtlocation.setText("Address not found for coords.");
}
} catch (IOException e) {
e.printStackTrace();
txtlocation.setText("Geocoder error: " + e.getMessage());
}
}
// Optional: handle permission result to trigger location after user allows
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (granted) {
getLocation();
} else {
Toast.makeText(this, "Location permission required.", Toast.LENGTH_SHORT).show();
}
}
}
// Other LocationListener callbacks (empty implementations are fine)
@Override public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override public void onProviderEnabled(@NonNull String provider) {}
@Override public void onProviderDisabled(@NonNull String provider) {}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="20dp"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnlocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Location" />
<TextView
android:id="@+id/txtlocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location will appear here"
android:textSize="18sp"
android:padding="16dp"
android:layout_marginTop="20dp" />
</LinearLayout>