Question 1
Question
Create the standard calculator application in android:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Calculator">
<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.calculator1;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView tvResult;
private String currentInput = "";
private double firstValue = 0.0;
private String operator = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = findViewById(R.id.tvResult);
setOperatorListener(R.id.btnAdd, "+");
setOperatorListener(R.id.btnSub, "-");
setOperatorListener(R.id.btnMul, "*");
setOperatorListener(R.id.btnDiv, "/");
setOperatorListener(R.id.btnMod, "%");
findViewById(R.id.btnClear).setOnClickListener(v -> {
currentInput = "";
firstValue = 0.0;
operator = "";
tvResult.setText("0");
});
findViewById(R.id.btnDel).setOnClickListener(v -> {
if (currentInput.length() > 0) {
currentInput = currentInput.substring(0, currentInput.length() - 1);
tvResult.setText(currentInput.isEmpty() ? "0" : currentInput);
}
});
findViewById(R.id.btnEqual).setOnClickListener(v -> calculateResult());
}
public void onDigitClick(View view) {
Button btn = (Button) view;
currentInput += btn.getText().toString();
tvResult.setText(currentInput);
}
private void setOperatorListener(int btnId, String op) {
findViewById(btnId).setOnClickListener(v -> {
if (!currentInput.isEmpty()) {
firstValue = Double.parseDouble(currentInput);
operator = op;
currentInput = ""; }
});
}
private void calculateResult() {
if (!currentInput.isEmpty() && !operator.isEmpty()) {
double secondValue = Double.parseDouble(currentInput);
double result = 0.0;
switch (operator) {
case "+":
result = firstValue + secondValue;
break;
case "-":
result = firstValue - secondValue;
break;
case "*":
result = firstValue * secondValue;
break;
case "/":
result = firstValue / secondValue;
break;
case "%":
result = firstValue % secondValue;
break;
}
tvResult.setText(String.valueOf(result));
currentInput = String.valueOf(result);
operator = "";
}
}
}
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="10dp"
android:background="#FFFFFF">
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#EEEEEE"
android:gravity="bottom|end"
android:padding="50dp"
android:text="0"
android:textColor="#000000"
android:textSize="48sp" />
<GridLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:columnCount="4"
android:rowCount="5"
android:layout_marginTop="10dp"
android:alignmentMode="alignMargins">
<Button android:id="@+id/btnDel" android:text="DEL" style="@style/CalcBtn"/>
<Button android:id="@+id/btnClear" android:text="C" style="@style/CalcBtn"/>
<Button android:id="@+id/btnMod" android:text="%" style="@style/CalcBtn"/>
<Button android:id="@+id/btnAdd" android:text="+" style="@style/CalcBtn"/>
<Button android:text="1" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="2" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="3" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:id="@+id/btnDiv" android:text="/" style="@style/CalcBtn"/>
<Button android:text="4" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="5" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="6" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:id="@+id/btnSub" android:text="-" style="@style/CalcBtn"/>
<Button android:text="7" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="8" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="9" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:id="@+id/btnMul" android:text="X" style="@style/CalcBtn"/>
<Button android:text="." android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button android:text="0" android:onClick="onDigitClick" style="@style/CalcBtn"/>
<Button
android:id="@+id/btnEqual"
android:text="="
style="@style/CalcBtn"
android:layout_columnSpan="2"
android:layout_gravity="fill_horizontal"/>
</GridLayout>
</LinearLayout>
Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="teal_primary">#009688</color>
<color name="teal_dark">#00796B</color>
<color name="button_gray">#E0E0E0</color>
</resources>
Themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Base.Theme.Calculator" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/teal_primary</item>
<item name="colorPrimaryDark">@color/teal_dark</item>
<item name="colorAccent">@color/teal_primary</item>
<item name="titleTextColor">@color/white</item>
</style>
<style name="Theme.Calculator" parent="Base.Theme.Calculator" />
<style name="CalcBtn">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">0dp</item>
<item name="android:layout_columnWeight">1</item>
<item name="android:layout_rowWeight">1</item>
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>
<item name="android:layout_margin">6dp</item>
<item name="android:background">@color/button_gray</item>
<item name="android:textColor">@color/black</item>
</style>
</resources>
Question 2
Question
Create a login screen with EditText fields for username and password, and a Button to submit. Include validation for empty fields.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uielements">
<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.UIElements">
<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.uielements;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EditText et_user_name = findViewById(R.id.et_user_name);
EditText et_password = findViewById(R.id.et_password);
Button btnReset = findViewById(R.id.btn_reset);
Button btnSubmit = findViewById(R.id.btn_submit);
btnReset.setOnClickListener(v -> {
et_user_name.setText("");
et_password.setText("");
});
btnSubmit.setOnClickListener(v -> {
String uname = et_user_name.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
if (uname.isEmpty()) {
et_user_name.setError("Username is required");
et_user_name.requestFocus();
return; }
if (pwd.isEmpty()) {
et_password.setError("Password is required");
et_password.requestFocus();
return; }
Toast.makeText(MainActivity.this, "Welcome " + uname, Toast.LENGTH_LONG).show();
});
}}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="UI Elements Demo"
app:titleTextColor="@android:color/white"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:layout_marginTop="80dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="Login"
android:layout_gravity="center_horizontal"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="textPersonName" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:passwordToggleEnabled="true"> <com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:layout_marginTop="16dp">
<Button
android:id="@+id/btn_reset"
android:text="Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"/>
<Button
android:id="@+id/btn_submit"
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="16dp"/>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Question 3
Question
Create an android application to display Alert Dialog on pressing the Back button.
MainActivity.java
package com.example.alertdialogapp;
import android.os.Bundle;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a callback to handle the back button press
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
showExitDialog();
}
};
// Add the callback to the dispatcher
getOnBackPressedDispatcher().addCallback(this, callback);
}
private void showExitDialog() {
// Build the Alert Dialog
new AlertDialog.Builder(this)
.setTitle("Exit Application")
.setMessage("Are you sure you want to exit?")
.setCancelable(false) // Prevent closing by clicking outside
.setPositiveButton("Yes", (dialog, which) -> {
// User clicked Yes, so close the activity
finish();
})
.setNegativeButton("No", (dialog, which) -> {
// User clicked No, so just close the dialog
dialog.dismiss();
})
.show();
}
}
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:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press the Back Button to see the Alert"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
Question 4
Question
Create an android application to display Alert Dialog on pressing the Back button.
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Datapassingapp">
<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>
<activity android:name=".SecondActivity" />
</application>
</manifest>
MainActivity.java
package com.example.datapassingapp; // TODO: Check your package name
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Declare variables
private EditText etInput;
private Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. Bind Views (These IDs match activity_main.xml)
etInput = findViewById(R.id.etInput);
btnSend = findViewById(R.id.btnSend);
// 2. Set Button Click Listener
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the string from the EditText
String message = etInput.getText().toString();
// Create the Intent object (From Here -> To SecondActivity)
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// Pass the data (Key: "USER_MESSAGE", Value: message)
intent.putExtra("USER_MESSAGE", message);
// Start the new activity
startActivity(intent);
}
});
}
}
SecondActivity.java
package com.example.datapassingapp; // TODO: Check your package name
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
private TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// 1. Bind View (Matches activity_second.xml)
tvResult = findViewById(R.id.tvResult);
// 2. Get the Intent that started this activity
Intent intent = getIntent();
// 3. Extract the string using the same Key "USER_MESSAGE"
if (intent != null) {
String receivedText = intent.getStringExtra("USER_MESSAGE");
// Set the text to the TextView
tvResult.setText(receivedText);
}
}
}
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:gravity="center"
android:padding="20dp">
<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type a message here"
android:textSize="18sp" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send to Second Activity"
android:layout_marginTop="20dp" />
</LinearLayout>
Activity_second.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:gravity="center"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Received Data:"
android:textSize="16sp" />
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting..."
android:textSize="24sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:textColor="@android:color/holo_blue_dark"/>
</LinearLayout>
Question 5
Question
Create a user interface with a TextView, Button, and ImageView. When the button is clicked, the image should be changed dynamically.
MainActivity.java
package com.example.imagechanger; // TODO: Check your package name
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Declare View variables
private TextView tvStatus;
private ImageView ivDisplay;
private Button btnChange;
// Flag to track which image is currently showing
private boolean isImageOne = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. Initialize Views
tvStatus = findViewById(R.id.tvStatus);
ivDisplay = findViewById(R.id.ivDisplay);
btnChange = findViewById(R.id.btnChange);
// 2. Set Button Click Listener
btnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isImageOne) {
// Switch to second image
ivDisplay.setImageResource(R.drawable.image_two);
tvStatus.setText("Current Image: Two");
isImageOne = false; // Update flag
} else {
// Switch back to first image
ivDisplay.setImageResource(R.drawable.image_one);
tvStatus.setText("Current Image: One");
isImageOne = true; // Update flag
}
}
});
}
}
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:gravity="center"
android:padding="20dp">
<TextView
android:id="@+id/tvStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Image: One"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>
<ImageView
android:id="@+id/ivDisplay"
android:layout_width="250dp"
android:layout_height="250dp"
android:src="@drawable/image_one"
android:scaleType="centerCrop"
android:layout_marginBottom="30dp"/>
<Button
android:id="@+id/btnChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image"
android:padding="15dp"/>
</LinearLayout>
Question 6
Question
Create the background service android application to play the ringtone/music.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Backgroundmusic">
<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>
<service android:name=".MusicService" />
</application>
</manifest>
MainActivity.java
package com.example.backgroundmusic; // TODO: Check your package name
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button btnStart, btnStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = findViewById(R.id.btnStart);
btnStop = findViewById(R.id.btnStop);
// Listener to Start Service
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
startService(serviceIntent);
}
});
// Listener to Stop Service
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
stopService(serviceIntent);
}
});
}
}
MusicService.java
package com.example.backgroundmusic; // TODO: Check your package name
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MusicService extends Service {
private MediaPlayer player;
@Override
@Nullable
public IBinder onBind(Intent intent) {
// We are not binding to an activity, so return null
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 1. Create the MediaPlayer logic
if (player == null) {
// Use the default system ringtone
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true); // Loop the music
}
// 2. Start the player if it's not already playing
if (!player.isPlaying()) {
player.start();
Toast.makeText(this, "Music Service Started", Toast.LENGTH_SHORT).show();
}
// START_STICKY ensures the service restarts if the system kills it
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// 3. Cleanup: Stop and release the player when service is stopped
if (player != null) {
if (player.isPlaying()) {
player.stop();
}
player.release();
player = null;
}
Toast.makeText(this, "Music Service Stopped", Toast.LENGTH_SHORT).show();
}
}
Question 7
Question
Create an android application which automatically notify the user when Aeroplane mode is turned on or off using a broadcast receiver.
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:gravity="center"
android:padding="20dp">
<TextView
android:id="@+id/tvInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Airplane Mode via your Quick Settings Panel to test."
android:textSize="18sp"
android:gravity="center"
android:layout_marginBottom="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(Toast notification will appear)"
android:textSize="14sp"
android:textColor="#666666"/>
</LinearLayout>
MainActivity.java
package com.example.airplanemodeapp; // TODO: Check your package name
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private AirplaneModeReceiver airplaneModeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the receiver
airplaneModeReceiver = new AirplaneModeReceiver();
}
@Override
protected void onStart() {
super.onStart();
// 1. Create an IntentFilter for Airplane Mode
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
// 2. Register the receiver dynamically
// This is required for Android 8.0 (Oreo) and above
registerReceiver(airplaneModeReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
// 3. Unregister the receiver to save battery and prevent crashes
if (airplaneModeReceiver != null) {
unregisterReceiver(airplaneModeReceiver);
}
}
}
AirplaneModeReceiver.java
package com.example.airplanemodeapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.Toast;
public class AirplaneModeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
String message = isAirplaneModeOn ? "Airplane Mode is ON " : "Airplane Mode is OFF ";
showCustomDurationToast(context, message, 10000);
}
}
private void showCustomDurationToast(Context context, String message, int durationInMillis) {
final Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
new CountDownTimer(durationInMillis, 1000) {
public void onTick(long millisUntilFinished) {
toast.show();
}
public void onFinish() {
// Ensure the toast disappears when time is up
toast.cancel();
}
}.start();
}
}
Question 8
Question
Explain the Android Activity life cycle in detail. Implement a simple app that logs the lifecycle methods (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy())
MainActivity.java
package com.example.lifecyclelogger; // TODO: Check your package name
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Tag for filtering logs in Android Studio
private static final String TAG = "LifecycleEvent";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate() called: Activity Initialized");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called: Activity is becoming visible");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called: Activity is interactive (Top of stack)");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called: User is leaving (or app partially obscured)");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called: Activity is no longer visible");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart() called: Activity returning from stopped state");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called: Activity is being destroyed");
}
}
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:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Logcat for 'LifecycleEvent'"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
Question 9
Question
Create a simple Hello World application in Android Studio. Explain the purpose of the MainActivity and the activity_main.xml file.
MainActivity.java
package com.example.helloworld;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Question 10
Question
Create an android application to demonstrate the following event listeners on the following widgets: Button: on click listener, long click listener Image: Touch listener with these motion events :Action up, action down and action pointer down Edit Text : key listener on Enter key The Appropriate message should be displayed in text view.
MainActivity.java
package com.example.eventlistenersdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button btnClick;
ImageView imageView;
EditText editText;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick = findViewById(R.id.btnClick);
imageView = findViewById(R.id.imageView);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
btnClick.setOnClickListener(v ->
textView.setText("Button Clicked"));
btnClick.setOnLongClickListener(v -> {
textView.setText("Button Long Pressed");
return true;
});
imageView.setOnTouchListener((v, event) -> {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
textView.setText("Image Action Down");
break;
case MotionEvent.ACTION_UP:
textView.setText("Image Action Up");
break;
case MotionEvent.ACTION_POINTER_DOWN:
textView.setText("Pointer Down (Multiple Fingers)");
break;
}
return true;
});
editText.setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_DOWN &&
keyCode == KeyEvent.KEYCODE_ENTER) {
textView.setText("Enter Key Pressed");
return true;
}
return false;
});
}
}
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"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Press Enter Key" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Event Message Will Appear Here"
android:textSize="18sp" />
<Button
android:id="@+id/btnClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click or Long Press Me" />
</LinearLayout>
Question 11
Question
Implement a custom color scheme for your registration form. Set the background color of the entire layout to a light color, and use a contrasting color for the Submit button.
colors.xml
<resources>
<color name="light_bg">#B9FF00</color>
<color name="submit_color">#000000</color>
<color name="white">#FFFFFF</color>
</resources>
activity_main
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<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="20dp"
android:background="@color/light_bg">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:layout_marginTop="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:textColor="@color/white"
android:backgroundTint="@color/submit_color"
android:layout_marginTop="20dp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Question 12
Question
Insert the new contents in the following resources and demonstrate their uses in the android application Android Resources: (Color, Theme, String, Drawable, Dimension, Image).
MainActivity.java
package com.example.resourcedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="@dimen/padding"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="@string/welcome_text"
android:textSize="@dimen/text_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:src="@drawable/sample_image"
android:layout_width="@dimen/image_size"
android:layout_height="@dimen/image_size"
android:layout_marginTop="20dp"/>
<Button
android:text="@string/button_text"
android:textColor="@color/white"
android:background="@drawable/button_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"/>
</LinearLayout>
Strings.xml
<resources>
<string name="app_name">ResourceDemo</string>
<string name="welcome_text">Welcome to Resource Demo</string>
<string name="button_text">Submit</string>
</resources>
Colors.xml
<resources>
<color name="bg_color">#F0F0F0</color>
<color name="primary_color">#6200EE</color>
<color name="white">#FFFFFF</color>
</resources>
Button_bg.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/primary_color"/>
<corners android:radius="12dp"/>
</shape>
Dimens.xml
<resources>
<dimen name="padding">20dp</dimen>
<dimen name="text_size">20sp</dimen>
<dimen name="image_size">150dp</dimen>
</resources>
Themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.ResourceDemo" parent="Theme.Material3.DayNight.NoActionBar">
<item name="android:windowBackground">@color/bg_color</item>
</style>
</resources>
Question 13
Question
Define the following string resources in the strings.xml file for the registration form: Full Name, Email Password Confirm Password and Submit Use these string resources in the corresponding TextView and Button in your layout XML. Project Name: RegistrationForm
MainActivity.java
package com.example.registrationform;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Strings.xml
<resources>
<string name="app_name">RegistrationForm</string>
<string name="full_name">Full Name</string>
<string name="email">Email</string>
<string name="password">Password</string>
<string name="confirm_password">Confirm Password</string>
<string name="submit">Submit</string>
</resources>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="@string/full_name"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/full_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:text="@string/email"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:text="@string/password"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:text="@string/confirm_password"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/confirm_password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="@string/submit"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Question 14
Question
Create a registration form where the form fields (Name, Email, Password, Confirm Password) are stacked vertically. Include a Submit button at the bottom of the form. Project Name: RegistrationForm
MainActivity.java
package com.example.registrationform;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="24dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:hint="@string/full_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/email"
android:inputType="textEmailAddress"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/password"
android:inputType="textPassword"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="@string/confirm_password"
android:inputType="textPassword"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="@string/submit"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Strings.xml
<resources>
<string name="app_name">RegistrationForm</string>
<string name="full_name">Full Name</string>
<string name="email">Email</string>
<string name="password">Password</string>
<string name="confirm_password">Confirm Password</string>
<string name="submit">Submit</string>
</resources>
Question 15
Question
Create an android application, with one button and image view also set the background image in the application, the image should be changed on each click of the button (Use two images). Project Name: ImageSwitcherApp
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:background="@drawable/bg_image"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:src="@drawable/image1"
android:layout_width="200dp"
android:layout_height="200dp"/>
<Button
android:id="@+id/button"
android:text="Change Image"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
package com.example.imageswitcherapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
boolean isFirstImage = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
button = findViewById(R.id.button);
button.setOnClickListener(v -> {
if(isFirstImage){
imageView.setImageResource(R.drawable.image2);
isFirstImage = false;
}
else{
imageView.setImageResource(R.drawable.image1);
isFirstImage = true;
}
});
}
}
Question 16
Question
Create an android application to demonstrate the use of sub menu the toast should be appeared by selecting the sub menu item.
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_options"
android:title="Options">
<menu>
<item
android:id="@+id/sub_item1"
android:title="Profile"/>
<item
android:id="@+id/sub_item2"
android:title="Settings"/>
<item
android:id="@+id/sub_item3"
android:title="Logout"/>
</menu>
</item>
</menu>
MainActivity.java
package com.example.submenudemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.sub_item1){
Toast.makeText(this, "Profile Selected", Toast.LENGTH_SHORT).show();
return true;
}
else if(id == R.id.sub_item2){
Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
return true;
}
else if(id == R.id.sub_item3){
Toast.makeText(this, "Logout Selected", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.SubMenuDemo" parent="Theme.Material3.DayNight">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>
<style name="Theme.SubMenuDemo" parent="Base.Theme.SubMenuDemo" />
</resources>
Question 17
Question
Design a form with a RadioGroup for selecting the gender (Male/Female/Other). Include a Submit button that shows the selected gender in a TextView.
MainActivity.java
package com.example.radiogroup;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
Button buttonSubmit;
TextView textViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
buttonSubmit = findViewById(R.id.buttonSubmit);
textViewResult = findViewById(R.id.textViewResult);
buttonSubmit.setOnClickListener(v -> {
int selectedId = radioGroup.getCheckedRadioButtonId();
if(selectedId == -1){
textViewResult.setText("Please select a gender");
}
else{
if(selectedId == R.id.radioMale){
textViewResult.setText("Selected Gender: Male");
}
else if(selectedId == R.id.radioFemale){
textViewResult.setText("Selected Gender: Female");
}
else{
textViewResult.setText("Selected Gender: Other");
}
}
});
}
}
strings.xml
<resources>
<string name="app_name">GenderForm</string>
<string name="select_gender">Select Gender</string>
<string name="male">Male</string>
<string name="female">Female</string>
<string name="other">Other</string>
<string name="submit">Submit</string>
</resources>
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="@string/select_gender"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioGroup
android:id="@+id/radioGroup"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioMale"
android:text="@string/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/radioFemale"
android:text="@string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/radioOther"
android:text="@string/other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
<Button
android:id="@+id/buttonSubmit"
android:text="@string/submit"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textViewResult"
android:textSize="18sp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Question 18
Question
Create a RelativeLayout for a profile screen with:A Profile Image centered at the top of the screen. A TextView displaying the name below the profile image, aligned to the center. A Button below the name, aligned to the center.
string.xml
<resources>
<string name="app_name">ProfileScreen</string>
<string name="user_name">IVNO</string>
<string name="follow">Follow</string>
</resources>
MainActivity.java
package com.example.profilescreen;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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">
<!-- Profile Image -->
<ImageView
android:id="@+id/profileImage"
android:src="@drawable/profile_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"/>
<!-- Name TextView -->
<TextView
android:id="@+id/textName"
android:text="@string/user_name"
android:textSize="22sp"
android:layout_below="@id/profileImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Button -->
<Button
android:id="@+id/buttonFollow"
android:text="@string/follow"
android:layout_below="@id/textName"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Question 19
Question
Write a program that logs the different lifecycle methods of an Activity (e.g., onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy()) to the logout.
MainActivity.java
package com.example.activitylifecycledemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "LifecycleDemo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate() called");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Check Logcat for Lifecycle Methods"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Question 20
Question
Design a ListView that displays a list of items. Each item should be a simple TextView with a string from an array of names. The list should be populated dynamically in your Activity.
MainActivity.java
package com.example.listviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] names = {
" ",
"IVNESH",
"PARAKEET",
"NARESH",
"PRATHAM",
"RUHI",
"SHIVANI",
"RIYADHI",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
names);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Question 21
Question
Create an Activity that hosts a Fragment. When a button in the Activity is clicked, pass a string value to the Fragment and display it in a TextView. res → layout → fragment_my.xml
fragment_my.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/textViewFragment"
android:text="Message will appear here"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
MyFragment.java
package com.example.fragmentdatademo;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyFragment extends Fragment {
TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
textView = view.findViewById(R.id.textViewFragment);
// Receive data from Activity
if(getArguments() != null){
String message = getArguments().getString("data");
textView.setText(message);
}
return view;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="460dp"
android:layout_marginTop="20dp">
</FrameLayout>
<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Data to Fragment" />
</LinearLayout>
MainActivity.java
package com.example.fragmentdatademo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button buttonSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(v -> {
MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("data", "Hello from 4021,5059,5081!");
fragment.setArguments(bundle);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragmentContainer, fragment);
ft.commit();
});
}
}
Question 22
Question
Create an android application using linear layout and insert 10 animals in the list view and display the appropriate Toast. Project Name: AnimalListApp
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listViewAnimals"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Mainactivity.java
package com.example.animallistapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView;
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] animals = {
"Lion",
"Tiger",
"Elephant",
"Dog",
"Cat",
"Horse",
"Monkey",
"Zebra",
"Bear",
"Deer"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewAnimals);
ArrayAdapter<String> adapter =
new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,
animals);
listView.setAdapter(adapter);
// Display Toast on item click
listView.setOnItemClickListener((parent, view, position, id) -> {
String selectedAnimal = animals[position];
Toast.makeText(
MainActivity.this,
"Selected: " + selectedAnimal,
Toast.LENGTH_SHORT
).show();
});
}
}
Question 23
Question
Create an app that displays an ImageView. When the user clicks the ImageView, show a Toast with the message & Image clicked! Project Name : ImageClickApp Add one image “sample_image.png” app-> res->drawable
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:src="@drawable/sample_image"
android:layout_width="200dp"
android:layout_height="200dp"
android:clickable="true"/>
</LinearLayout>
Mainactivity.java
package com.example.imageclickapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
imageView.setOnClickListener(v -> {
Toast.makeText(
MainActivity.this,
"Image clicked!",
Toast.LENGTH_SHORT
).show();
}); }}
Question 24
Question
Create the background service android application to play the ringtone/music. Project name: MusicServiceApp Inside app-> res Create a new folder “raw” Paste any audio inside raw folder “music.mp3” Create a java class -> “MusicService”
MusicService.java
package com.example.musicserviceapp;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MusicService extends Service {
MediaPlayer mediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.music);
mediaPlayer.setLooping(true); // plays continuously
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start(); // start music
return START_STICKY; // keeps service running
}
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.example.musicserviceapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startBtn, stopBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = findViewById(R.id.buttonStart);
stopBtn = findViewById(R.id.buttonStop);
startBtn.setOnClickListener(v -> {
startService(new Intent(MainActivity.this, MusicService.class));
});
stopBtn.setOnClickListener(v -> {
stopService(new Intent(MainActivity.this, MusicService.class));
});
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonStart"
android:text="Start Music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/buttonStop"
android:text="Stop Music"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MusicServiceApp">
<service android:name=".MusicService"/>
<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>
Question 25
Question
Design a simple login form using ConstraintLayout that has: Username and Password fields aligned vertically. Login button centered horizontally below the fields. Forgot Password? link aligned to the right of the password field. Task: Position all the elements using constraints in the ConstraintLayout.
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="24dp">
<!-- Username Field -->
<EditText
android:id="@+id/editUsername"
android:hint="@string/username"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<!-- Password Field -->
<EditText
android:id="@+id/editPassword"
android:hint="@string/password"
android:inputType="textPassword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/editUsername"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<!-- Forgot Password Link -->
<TextView
android:id="@+id/textForgot"
android:text="@string/forgot_password"
android:textColor="@android:color/holo_blue_dark"
android:layout_marginTop="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/editPassword"
app:layout_constraintEnd_toEndOf="@id/editPassword"/>
<!-- Login Button -->
<Button
android:id="@+id/buttonLogin"
android:text="@string/login"
android:layout_marginTop="24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/textForgot"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.loginformapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Strings.xml
<resources>
<string name="app_name">LoginFormApp</string>
<string name="username">Username</string>
<string name="password">Password</string>
<string name="login">Login</string>
<string name="forgot_password">Forgot Password?</string>
</resources>
Question 26
Question
Create an android application to demonstrate the use of sub menu the toast should be appeared by selecting the sub menu item Name: SubMenuApp
In res → values → themes.xml
Make sure this line is correct
<style name="Base.Theme.SubMenuApp" parent="Theme.Material3.DayNight">
</style>
Inside res folder create a menu folder
Inside menu-> menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_more"
android:title="More Options">
<menu>
<item
android:id="@+id/profile"
android:title="Profile"/>
<item
android:id="@+id/settings"
android:title="Settings"/>
<item
android:id="@+id/logout"
android:title="Logout"/>
</menu>
</item>
</menu>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
MainActivity.java
package com.example.submenuapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Create Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// Handle Sub Menu Click
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.profile){
Toast.makeText(this, "Profile Selected", Toast.LENGTH_SHORT).show();
}
else if(id == R.id.settings){
Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
}
else if(id == R.id.logout){
Toast.makeText(this, "Logout Selected", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Question 27
Question
Design a screen with two buttons: Start and Stop. When the Start button is clicked, start a Timer (display the time in seconds). When the Stop button is clicked, stop the timer.
MainActivity.java
package com.example.timerapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textTimer;
Button startBtn, stopBtn;
Handler handler = new Handler();
int seconds = 0;
boolean running = false;
Runnable runnable = new Runnable() {
@Override
public void run() {
if(running){
seconds++;
textTimer.setText(String.valueOf(seconds));
handler.postDelayed(this, 1000); // repeat every 1 sec
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTimer = findViewById(R.id.textTimer);
startBtn = findViewById(R.id.buttonStart);
stopBtn = findViewById(R.id.buttonStop);
startBtn.setOnClickListener(v -> {
if(!running){
running = true;
handler.post(runnable);
}
});
stopBtn.setOnClickListener(v -> running = false);
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Timer Display -->
<TextView
android:id="@+id/textTimer"
android:text="0"
android:textSize="40sp"
android:layout_marginBottom="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Start Button -->
<Button
android:id="@+id/buttonStart"
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Stop Button -->
<Button
android:id="@+id/buttonStop"
android:text="Stop"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Question 28
Question
Create a simple Registration Form with the following fields: Name (Text Input) Email (Text Input) Phone Number (Text Input) Password (Password Input) Confirm Password (Password Input) Submit Button activity_main
<?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">
<LinearLayout
android:orientation="vertical"
android:padding="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Name -->
<EditText
android:hint="@string/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Email -->
<EditText
android:hint="@string/email"
android:inputType="textEmailAddress"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Phone -->
<EditText
android:hint="@string/phone"
android:inputType="phone"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Password -->
<EditText
android:hint="@string/password"
android:inputType="textPassword"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Confirm Password -->
<EditText
android:hint="@string/confirm_password"
android:inputType="textPassword"
android:layout_marginTop="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Submit Button -->
<Button
android:text="@string/submit"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
strings.xml
<resources>
<string name="app_name">RegistrationFormApp</string>
<string name="name">Name</string>
<string name="email">Email</string>
<string name="phone">Phone Number</string>
<string name="password">Password</string>
<string name="confirm_password">Confirm Password</string>
<string name="submit">Submit</string>
</resources>
MainActivity.java
package com.example.registrationformapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}