Nothing Special   »   [go: up one dir, main page]

Android Studio Codes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 214

Slip 1

Q.1) Write an application to create a splash screen.


[10 Marks]

1. Create a new activity for the splash screen (`SplashActivity.java`):

package com.example.myapp;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {

private static int SPLASH_TIME_OUT = 2000; // Splash screen display time


in milliseconds

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_splash);

// Set a delay for launching the main activity after the splash screen

new Handler().postDelayed(new Runnable() {

@Override
public void run() {

// Start the main activity

Intent mainIntent = new Intent(SplashActivity.this,


MainActivity.class);

startActivity(mainIntent);

// Close this activity

finish();

}, SPLASH_TIME_OUT);

2. Create the layout file for the splash screen (`activity_splash.xml`) in the
`res/layout` directory:

<?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:background="@color/colorPrimary">

<!-- Add your splash screen content here, such as logo or image -->

</RelativeLayout>
3. Update the `AndroidManifest.xml` file to define the splash screen activity:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.myapp">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<!-- Define the splash screen activity as the launcher activity -->

<activity

android:name=".SplashActivity"

android:theme="@style/Theme.AppCompat.NoActionBar">

<intent-filter>

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

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

</intent-filter>

</activity>
<!-- Define the main activity -->

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

</application>

</manifest>

4. Replace `"@drawable/splash_screen"` with the appropriate resource identifier


for your splash screen image in `activity_splash.xml` layout file.

5. Optionally, you can add animations or additional UI elements to enhance the


splash screen.

Q.2) Create table Student (roll_no, name, address, percentage). Create


Application for performing the following operation on the table. (Using
SQLite database). i] Insert record of 5 new student details.
ii] Show all the student details.
[20 Marks]
1. Define the SQLite database schema in a class named `StudentContract.java`:

import android.provider.BaseColumns;

public final class StudentContract {

private StudentContract() {}

public static class StudentEntry implements BaseColumns {

public static final String TABLE_NAME = "student";

public static final String COLUMN_NAME_ROLL_NO = "roll_no";

public static final String COLUMN_NAME_NAME = "name";

public static final String COLUMN_NAME_ADDRESS = "address";

public static final String COLUMN_NAME_PERCENTAGE =


"percentage";

2. Create a database helper class named `StudentDbHelper.java` to manage


database creation and version management:

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;
import static com.example.myapp.StudentContract.StudentEntry;

public class StudentDbHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;

public static final String DATABASE_NAME = "Student.db";

private static final String SQL_CREATE_ENTRIES =

"CREATE TABLE " + StudentEntry.TABLE_NAME + " (" +

StudentEntry._ID + " INTEGER PRIMARY KEY," +

StudentEntry.COLUMN_NAME_ROLL_NO + " INTEGER," +

StudentEntry.COLUMN_NAME_NAME + " TEXT," +

StudentEntry.COLUMN_NAME_ADDRESS + " TEXT," +

StudentEntry.COLUMN_NAME_PERCENTAGE + " REAL)";

private static final String SQL_DELETE_ENTRIES =

"DROP TABLE IF EXISTS " + StudentEntry.TABLE_NAME;

public StudentDbHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}
public void onCreate(SQLiteDatabase db) {

db.execSQL(SQL_CREATE_ENTRIES);

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL(SQL_DELETE_ENTRIES);

onCreate(db);

public void onDowngrade(SQLiteDatabase db, int oldVersion, int


newVersion) {

onUpgrade(db, oldVersion, newVersion);

```

3. Implement methods in your `MainActivity.java` to perform database


operations like inserting records and showing all student details:

```java

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import com.example.myapp.StudentContract.StudentEntry;

import com.example.myapp.StudentDbHelper;

public class MainActivity extends AppCompatActivity {

private StudentDbHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

dbHelper = new StudentDbHelper(this);

insertStudentRecords();

showStudentDetails();

private void insertStudentRecords() {


SQLiteDatabase db = dbHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(StudentEntry.COLUMN_NAME_ROLL_NO, 1);

values.put(StudentEntry.COLUMN_NAME_NAME, "John");

values.put(StudentEntry.COLUMN_NAME_ADDRESS, "123 Main St");

values.put(StudentEntry.COLUMN_NAME_PERCENTAGE, 85.5);

db.insert(StudentEntry.TABLE_NAME, null, values);

// Insert records for 4 more students similarly

private void showStudentDetails() {

SQLiteDatabase db = dbHelper.getReadableDatabase();

String[] projection = {

StudentEntry.COLUMN_NAME_ROLL_NO,

StudentEntry.COLUMN_NAME_NAME,

StudentEntry.COLUMN_NAME_ADDRESS,

StudentEntry.COLUMN_NAME_PERCENTAGE

};
Cursor cursor = db.query(

StudentEntry.TABLE_NAME,

projection,

null,

null,

null,

null,

null

);

StringBuilder studentDetails = new StringBuilder();

while (cursor.moveToNext()) {

int rollNo =
cursor.getInt(cursor.getColumnIndexOrThrow(StudentEntry.COLUMN_NAME
_ROLL_NO));

String name =
cursor.getString(cursor.getColumnIndexOrThrow(StudentEntry.COLUMN_NA
ME_NAME));

String address =
cursor.getString(cursor.getColumnIndexOrThrow(StudentEntry.COLUMN_NA
ME_ADDRESS));

double percentage =
cursor.getDouble(cursor.getColumnIndexOrThrow(StudentEntry.COLUMN_N
AME_PERCENTAGE));
studentDetails.append("Roll No: ").append(rollNo).append("\n");

studentDetails.append("Name: ").append(name).append("\n");

studentDetails.append("Address: ").append(address).append("\n");

studentDetails.append("Percentage: ").append(percentage).append("\n\
n");

cursor.close();

TextView textView = findViewById(R.id.textView);

textView.setText(studentDetails.toString());

4. Create the layout file `activity_main.xml` to display the student details:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView
android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:textSize="18sp" />

</RelativeLayout>

Q.3) Viva [5 Marks]


Slip 2
Q.1) Create an application that allows the user to enter a number in the
textbox. Check whether the number in the textbox is perfect number or
not. Print the message using Toast control.
[10 Marks]

1. Define the layout for the activity (`activity_main.xml`):

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter a number"

android:inputType="number"/>

<Button

android:id="@+id/buttonCheck"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber"

android:layout_marginTop="16dp"

android:text="Check"

android:>

</RelativeLayout>

2. Implement the logic in the MainActivity class to check whether the entered
number is a perfect number or not (`MainActivity.java`):

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

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

// Method to check whether the entered number is a perfect number or not

public void checkNumber(View view) {

EditText editTextNumber = findViewById(R.id.editTextNumber);

String input = editTextNumber.getText().toString().trim();

if (input.isEmpty()) {

// Display an error message if the input is empty

showToast("Please enter a number.");

return;

int number = Integer.parseInt(input);

if (number <= 0) {

// Display an error message if the input is not a positive integer

showToast("Please enter a positive integer.");

return;

// Check whether the entered number is a perfect number


boolean isPerfect = isPerfectNumber(number);

// Display the result using a Toast message

if (isPerfect) {

showToast(number + " is a perfect number.");

} else {

showToast(number + " is not a perfect number.");

// Method to check whether a number is a perfect number

private boolean isPerfectNumber(int number) {

int sum = 0;

for (int i = 1; i < number; i++) {

if (number % i == 0) {

sum += i;

return sum == number;

// Method to display a Toast message


private void showToast(String message) {

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

```

Q.2) Java Android Program to perform all arithmetic Operations using


Calculator.
[20 marks]

1. Define the layout for the calculator (`activity_main.xml`):

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"
android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter first number"

android:inputType="numberDecimal"/>

<EditText

android:id="@+id/editTextNumber2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber1"

android:layout_marginTop="16dp"

android:hint="Enter second number"

android:inputType="numberDecimal"/>
<Button

android:id="@+id/buttonAdd"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber2"

android:layout_marginTop="16dp"

android:text="Add"

android:>

<Button

android:id="@+id/buttonSubtract"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonAdd"

android:layout_marginTop="16dp"

android:text="Subtract"

android:>

<Button

android:id="@+id/buttonMultiply"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonSubtract"

android:layout_marginTop="16dp"

android:text="Multiply"

android:>

<Button

android:id="@+id/buttonDivide"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonMultiply"

android:layout_marginTop="16dp"

android:text="Divide"

android:>

<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_below="@id/buttonDivide"

android:layout_marginTop="16dp"/>

</RelativeLayout>

2. Implement the logic in the MainActivity class to perform arithmetic


operations (`MainActivity.java`):

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber1;

private EditText editTextNumber2;

private TextView textViewResult;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editTextNumber1 = findViewById(R.id.editTextNumber1);

editTextNumber2 = findViewById(R.id.editTextNumber2);

textViewResult = findViewById(R.id.textViewResult);

// Method to perform addition

public void performAddition(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 + num2;

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

// Method to perform subtraction

public void performSubtraction(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());
double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 - num2;

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

// Method to perform multiplication

public void performMultiplication(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 * num2;

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

// Method to perform division

public void performDivision(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

if (num2 == 0) {
textViewResult.setText("Result: Infinity (Division by zero)");

} else {

double result = num1 / num2;

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

```

Q.3) Viva [5 Marks]

Slip 3
Q.1) Create an application that allows the user to enter a number in the
textbox. Check whether the number in the textbox is Armstrong or not.
Print the message accordingly in the label control.
[10 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter a number"

android:inputType="number"/>

<Button

android:id="@+id/buttonCheck"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber"

android:layout_marginTop="16dp"

android:text="Check"

android:>

<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonCheck"

android:layout_marginTop="16dp"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to check whether the entered
number is an Armstrong number or not (`MainActivity.java`):

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Method to check whether the entered number is an Armstrong number or


not

public void checkArmstrong(View view) {

EditText editTextNumber = findViewById(R.id.editTextNumber);

String input = editTextNumber.getText().toString().trim();

if (input.isEmpty()) {

// Display an error message if the input is empty

showResult("Please enter a number.");

return;

}
int number = Integer.parseInt(input);

if (number < 0) {

// Display an error message if the input is negative

showResult("Please enter a non-negative number.");

return;

// Check whether the entered number is an Armstrong number

boolean isArmstrong = isArmstrongNumber(number);

// Display the result

if (isArmstrong) {

showResult(number + " is an Armstrong number.");

} else {

showResult(number + " is not an Armstrong number.");

// Method to check whether a number is an Armstrong number

private boolean isArmstrongNumber(int number) {

int sum = 0;

int originalNumber = number;


int numberOfDigits = String.valueOf(number).length();

while (number > 0) {

int digit = number % 10;

sum += Math.pow(digit, numberOfDigits);

number /= 10;

return sum == originalNumber;

// Method to display the result

private void showResult(String message) {

TextView textViewResult = findViewById(R.id.textViewResult);

textViewResult.setText(message);

Q.2) Create an Android application which examine a phone number


entered by a user with the given format.
• Area code should be one of the following: 040, 041, 050,
0400, 044 • There should 6 - 8 numbers in telephone
number (+ area code).
[20 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextPhoneNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter phone number"

android:inputType="phone"/>

<Button
android:id="@+id/buttonCheck"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/editTextPhoneNumber"

android:layout_marginTop="16dp"

android:text="Check"

android:>

<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonCheck"

android:layout_marginTop="16dp"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to examine the entered phone
number with the given format requirements (`MainActivity.java`):

```java
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Method to check the entered phone number format

public void checkPhoneNumber(View view) {

EditText editTextPhoneNumber =
findViewById(R.id.editTextPhoneNumber);

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


if (phoneNumber.isEmpty()) {

// Display an error message if the input is empty

showResult("Please enter a phone number.");

return;

// Define the regex pattern for the phone number format

String regex = "^((040|041|050|0400|044)[0-9]{3}[0-9]{3,5})$";

// Create a Pattern object

Pattern pattern = Pattern.compile(regex);

// Create a Matcher object

Matcher matcher = pattern.matcher(phoneNumber);

// Check if the entered phone number matches the pattern

if (matcher.matches()) {

showResult("Valid phone number format.");

} else {

showResult("Invalid phone number format.");

}
}

// Method to display the result

private void showResult(String message) {

TextView textViewResult = findViewById(R.id.textViewResult);

textViewResult.setText(message);

```

Q.3) Viva [5 Marks]

Slip 4
Q.1) Construct image switcher using setFactory().
[10 Marks]
Q.2) Write a program to search a specific location on Google Map.

[20 Marks]

1. **Set up Google Maps API:**

- Go to the Google Cloud Console: https://console.cloud.google.com/.

- Create a new project (or select an existing one).

- Enable the "Maps SDK for Android" API for your project.

- Generate an API key for your project.

2. **Configure Android Manifest:**

- Add the necessary permissions for internet access and location services to
your AndroidManifest.xml file:

```xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.mapsearch">

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

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

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

...

```

3. **Set up Google Maps activity layout:**

- Define the layout for your activity containing a MapFragment or


SupportMapFragment:

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MapsActivity">

<fragment

android:id="@+id/map"

android:name="com.google.android.gms.maps.SupportMapFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_above="@+id/searchButton"
android:layout_alignParentStart="true"

android:layout_alignParentTop="true" />

<Button

android:id="@+id/searchButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_centerHorizontal="true"

android:text="Search Location" />

</RelativeLayout>

```

4. **Implement Map Search functionality:**

- In your activity class, initialize the GoogleMap object and handle the search
button click event:

```java

import android.os.Bundle;

import android.view.View;

import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

private Button searchButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);
searchButton = findViewById(R.id.searchButton);

searchButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

searchLocation();

});

// Obtain the SupportMapFragment and get notified when the map is ready
to be used.

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager()

.findFragmentById(R.id.map);

if (mapFragment != null) {

mapFragment.getMapAsync(this);

@Override

public void onMapReady(GoogleMap googleMap) {

mMap = googleMap;
// Add a marker in default location and move the camera

LatLng defaultLocation = new LatLng(37.7749, -122.4194); // San


Francisco coordinates

mMap.addMarker(new
MarkerOptions().position(defaultLocation).title("Default Location"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(defaultLocation));

mMap.animateCamera(CameraUpdateFactory.zoomTo(10)); // Zoom level


10

private void searchLocation() {

// Implement your location search functionality here

// Example: You can use Geocoding API to convert an address to


coordinates and then move the camera to that location.

Toast.makeText(this, "Location search functionality will be implemented


here.", Toast.LENGTH_SHORT).show();

```

Q.3) Viva [5 Marks]


Slip 5
Q.1) Java Android Program to Demonstrate Alert Dialog Box.
[10 Marks]

To create an Android application that demonstrates an AlertDialog box, you


can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<Button

android:id="@+id/buttonShowDialog"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Dialog"
android:layout_centerInParent="true"

android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to show the AlertDialog box
(`MainActivity.java`):

```java

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

// Method to show the AlertDialog

public void showAlertDialog(View view) {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Alert Dialog")

.setMessage("This is a demonstration of AlertDialog box.")

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialogInterface, int i) {

// Do something when the user clicks OK button

dialogInterface.dismiss(); // Dismiss the dialog

})

.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialogInterface, int i) {

// Do something when the user clicks Cancel button

dialogInterface.dismiss(); // Dismiss the dialog

})
.setCancelable(false); // Prevent dismiss when touching outside of
the dialog

AlertDialog alertDialog = builder.create();

alertDialog.show();

```

Q.2) Create an Android application which will ask the user to input his /
her name. A message should display the two items concatenated in a label.
Change the format of the label using radio buttons and check boxes for
selection. The user can make the label text bold, underlined or italic as
well as change its color. Also include buttons to display the message in the
label, clear the text boxes as well as label. Finally exit.
[20 Marks]

To create an Android application with the described functionality, you'll need to


create a layout with EditText fields for inputting the user's name, radio buttons
and check boxes for selecting text format options, buttons for displaying the
message, clearing the text, and exiting the application, and a TextView (label) to
display the concatenated message. Below are the steps to achieve this:

1. Define the layout for the activity (`activity_main.xml`):

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:layout_marginBottom="8dp"/>

<RadioGroup

android:id="@+id/radioGroupFormat"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextName"

android:orientation="horizontal">
<RadioButton

android:id="@+id/radioButtonBold"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Bold"/>

<RadioButton

android:id="@+id/radioButtonUnderline"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Underline"/>

<RadioButton

android:id="@+id/radioButtonItalic"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Italic"/>

</RadioGroup>

<CheckBox

android:id="@+id/checkBoxColor"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Change color"

android:layout_below="@id/radioGroupFormat"/>

<Button

android:id="@+id/buttonDisplay"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Display Message"

android:layout_below="@id/checkBoxColor"

android:>

<Button

android:id="@+id/buttonClear"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Clear"

android:layout_below="@id/buttonDisplay"

android:layout_marginTop="16dp"

android:>

<TextView
android:id="@+id/textViewMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonClear"

android:layout_marginTop="16dp"/>

<Button

android:id="@+id/buttonExit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Exit"

android:layout_below="@id/textViewMessage"

android:layout_marginTop="16dp"

android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle button clicks and
update the label (`MainActivity.java`):

```java
import android.graphics.Color;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private EditText editTextName;

private RadioGroup radioGroupFormat;

private CheckBox checkBoxColor;

private TextView textViewMessage;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize views

editTextName = findViewById(R.id.editTextName);

radioGroupFormat = findViewById(R.id.radioGroupFormat);

checkBoxColor = findViewById(R.id.checkBoxColor);

textViewMessage = findViewById(R.id.textViewMessage);

// Method to display the message in the label

public void displayMessage(View view) {

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

StringBuilder message = new StringBuilder(name);

// Check which text format options are selected

int checkedRadioButtonId =
radioGroupFormat.getCheckedRadioButtonId();

if (checkedRadioButtonId != -1) {

RadioButton radioButton = findViewById(checkedRadioButtonId);

switch (radioButton.getId()) {

case R.id.radioButtonBold:

message.insert(0, "<b>");

message.append("</b>");

break;
case R.id.radioButtonUnderline:

message.insert(0, "<u>");

message.append("</u>");

break;

case R.id.radioButtonItalic:

message.insert(0, "<i>");

message.append("</i>");

break;

// Change text color if checkbox is checked

if (checkBoxColor.isChecked()) {

message.insert(0, "<font color='#FF0000'>");

message.append("</font>");

// Set the formatted message to the label

textViewMessage.setText(android.text.Html.fromHtml(message.toString()));

}
// Method to clear all fields

public void clearFields(View view) {

editTextName.setText("");

radioGroupFormat.clearCheck();

checkBoxColor.setChecked(false);

textViewMessage.setText("");

// Method to exit the application

public void exitApp(View view) {

finish(); // Close the activity

Q.3) Viva [5 Marks]


Slip 6
Q.1) Java Android Program to demonstrate login form with validation.
[10 Marks]

EMAIL

PASSWORD

LOGIN

Not a member? Sign Up now.

To create an Android application that demonstrates a login form with


validation, you can follow these steps:

1. Define the layout for the login activity (`activity_login.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".LoginActivity">

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

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="8dp"
android:hint="Password"
android:inputType="textPassword"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"
android:>

<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonLogin"
android:layout_marginTop="16dp"/>

</RelativeLayout>
```

2. Implement the logic in the LoginActivity class to handle login button click
and perform validation (`LoginActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends AppCompatActivity {

private EditText editTextUsername, editTextPassword;


private TextView textViewMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Initialize views
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
textViewMessage = findViewById(R.id.textViewMessage);
}

// Method to handle login button click


public void login(View view) {
// Get username and password from EditText fields
String username = editTextUsername.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();

// Perform validation
if (isValidCredentials(username, password)) {
// Show success message
textViewMessage.setText("Login successful!");

textViewMessage.setTextColor(getResources().getColor(android.R.color.holo_
green_dark));
} else {
// Show error message
textViewMessage.setText("Invalid username or password.");

textViewMessage.setTextColor(getResources().getColor(android.R.color.holo_
red_dark));
}
}
// Method to validate username and password
private boolean isValidCredentials(String username, String password) {
// Validate username and password (example validation: username must be
"admin" and password must be "password")
return username.equals("admin") && password.equals("password");
}
}

Q.2) Write a program to search a specific location on Google Map.


[20 Marks]
Same as slip 4 Q2

Q.3) Viva [5 Marks]


Slip 7
Q.1] Java Android Program to Demonstrate ProgressBar.
[10 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<Button

android:id="@+id/buttonStart"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Start Progress"

android:layout_centerInParent="true"

android: > <ProgressBar

android:id="@+id/progressBar"

style="@android:style/Widget.ProgressBar.Horizontal"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/buttonStart"

android:layout_marginTop="16dp"

android:max="100"

android:visibility="invisible"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to start and stop the progress
(`MainActivity.java`):

```java

import android.os.Bundle;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

private ProgressBar progressBar;

private Button buttonStart;

private Handler handler;

private int progressStatus = 0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize views

progressBar = findViewById(R.id.progressBar);

buttonStart = findViewById(R.id.buttonStart);

handler = new Handler();

// Method to start the progress


public void startProgress(View view) {

progressStatus = 0;

progressBar.setVisibility(View.VISIBLE);

buttonStart.setEnabled(false);

// Start a background thread to update progress

new Thread(new Runnable() {

@Override

public void run() {

while (progressStatus < 100) {

progressStatus += 5; // Increment progress

// Update the progress bar and display it on the UI thread

handler.post(new Runnable() {

@Override

public void run() {

progressBar.setProgress(progressStatus);

});

try {

// Simulate a delay by sleeping for 500 milliseconds

Thread.sleep(500);

} catch (InterruptedException e) {
e.printStackTrace();

// After completing progress, enable the button and hide the progress
bar

handler.post(new Runnable() {

@Override

public void run() {

buttonStart.setEnabled(true);

progressBar.setVisibility(View.INVISIBLE);

});

}).start();

Q.2] Create table Employee (E_id, name, address, ph_no). Create


Application for performing the following operation on the table. (Using
SQLite database). i] Insert record of 5 new Employees. ii] Show all the
details of Employee.
[20 Marks]
To create an Android application that performs operations on an SQLite
database table named "Employee," you can follow these steps:
1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Employee"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:>

<Button
android:id="@+id/buttonShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Employees"
android:layout_below="@id/buttonInsert"
android:layout_centerHorizontal="true"
android:>

<TextView
android:id="@+id/textViewEmployees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonShow"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to perform database


operations (`MainActivity.java`):

```java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private TextView textViewEmployees;


private DatabaseHelper dbHelper;

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

// Initialize views
textViewEmployees = findViewById(R.id.textViewEmployees);

// Initialize DatabaseHelper
dbHelper = new DatabaseHelper(this);
}

// Method to insert 5 new employees into the database


public void insertEmployee(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();

// Inserting 5 new employees


for (int i = 1; i <= 5; i++) {
ContentValues values = new ContentValues();
values.put("name", "Employee " + i);
values.put("address", "Address " + i);
values.put("ph_no", "12345678" + i);

long newRowId = db.insert("Employee", null, values);

if (newRowId == -1) {
// Error occurred while inserting
Toast.makeText(this, "Error inserting employee " + i,
Toast.LENGTH_SHORT).show();
}
}

// Close the database connection


db.close();
}

// Method to show all the details of employees


public void showEmployees(View view) {
SQLiteDatabase db = dbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database to


query
String[] projection = {
"E_id",
"name",
"address",
"ph_no"
};

// Perform a query on the "Employee" table


Cursor cursor = db.query(
"Employee", // The table to query
projection, // The array of columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null // The sort order
);

// Display the details of employees in the TextView


StringBuilder stringBuilder = new StringBuilder();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("E_id"));
String name =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
String address =
cursor.getString(cursor.getColumnIndexOrThrow("address"));
String phNo =
cursor.getString(cursor.getColumnIndexOrThrow("ph_no"));

stringBuilder.append("ID: ").append(id).append(", Name:


").append(name)
.append(", Address: ").append(address).append(", Phone No:
").append(phNo).append("\n");
}
textViewEmployees.setText(stringBuilder.toString());

// Close the cursor and database connection


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

3. Define the DatabaseHelper class to create and manage the SQLite


database (`DatabaseHelper.java`):

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

public class DatabaseHelper extends SQLiteOpenHelper {

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


private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// Create the "Employee" table
String SQL_CREATE_EMPLOYEE_TABLE = "CREATE TABLE
Employee (" +
"E_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"address TEXT," +
"ph_no TEXT)";
db.execSQL(SQL_CREATE_EMPLOYEE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop the table if it exists and recreate it
db.execSQL("DROP TABLE IF EXISTS Employee");
onCreate(db);
}
}
```

Q.3] Viva.
Slip 8
Q.1] Create a Application which shows Life Cycle of Activity.
[10 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<TextView

android:id="@+id/textViewLifecycle"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Activity Lifecycle:"

android:textSize="18sp"

android:textStyle="bold"/>
</RelativeLayout>

```

2. Implement the logic in the MainActivity class to observe and log the lifecycle
callbacks (`MainActivity.java`):

```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "ActivityLifecycle";

private TextView textViewLifecycle;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize views

textViewLifecycle = findViewById(R.id.textViewLifecycle);

// Log the onCreate lifecycle callback

Log.d(TAG, "onCreate");

// Update the TextView to display the current state

updateLifecycleText("onCreate");

@Override

protected void onStart() {

super.onStart();

// Log the onStart lifecycle callback

Log.d(TAG, "onStart");

// Update the TextView to display the current state

updateLifecycleText("onStart");

@Override
protected void onResume() {

super.onResume();

// Log the onResume lifecycle callback

Log.d(TAG, "onResume");

// Update the TextView to display the current state

updateLifecycleText("onResume");

@Override

protected void onPause() {

super.onPause();

// Log the onPause lifecycle callback

Log.d(TAG, "onPause");

// Update the TextView to display the current state

updateLifecycleText("onPause");

@Override
protected void onStop() {

super.onStop();

// Log the onStop lifecycle callback

Log.d(TAG, "onStop");

// Update the TextView to display the current state

updateLifecycleText("onStop");

@Override

protected void onDestroy() {

super.onDestroy();

// Log the onDestroy lifecycle callback

Log.d(TAG, "onDestroy");

// Update the TextView to display the current state

updateLifecycleText("onDestroy");

// Helper method to update the TextView with the current lifecycle state
private void updateLifecycleText(String lifecycleState) {

String currentText = textViewLifecycle.getText().toString();

textViewLifecycle.setText(currentText + "\n" + lifecycleState);

```

Q.2] Create table Customer (id, name, address, ph_no). Create


Application for performing the following operation on the table. (Using
SQLite database). i] Insert new customer details (At least 5 records).
ii] Show all the customer details. [20 Marks]
1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Customer"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:>

<Button
android:id="@+id/buttonShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Customers"
android:layout_below="@id/buttonInsert"
android:layout_centerHorizontal="true"
android:>

<TextView
android:id="@+id/textViewCustomers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonShow"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to perform database operations


(`MainActivity.java`):

```java
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private TextView textViewCustomers;


private DatabaseHelper dbHelper;

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

// Initialize views
textViewCustomers = findViewById(R.id.textViewCustomers);

// Initialize DatabaseHelper
dbHelper = new DatabaseHelper(this);
}

// Method to insert new customer details into the database


public void insertCustomer(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();

// Inserting 5 new customers


for (int i = 1; i <= 5; i++) {
ContentValues values = new ContentValues();
values.put("name", "Customer " + i);
values.put("address", "Address " + i);
values.put("ph_no", "12345678" + i);

long newRowId = db.insert("Customer", null, values);

if (newRowId == -1) {
// Error occurred while inserting
Toast.makeText(this, "Error inserting customer " + i,
Toast.LENGTH_SHORT).show();
}
}

// Close the database connection


db.close();
}

// Method to show all the details of customers


public void showCustomers(View view) {
SQLiteDatabase db = dbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database to


query
String[] projection = {
"id",
"name",
"address",
"ph_no"
};

// Perform a query on the "Customer" table


Cursor cursor = db.query(
"Customer", // The table to query
projection, // The array of columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null // The sort order
);

// Display the details of customers in the TextView


StringBuilder stringBuilder = new StringBuilder();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name =
cursor.getString(cursor.getColumnIndexOrThrow("name"));
String address =
cursor.getString(cursor.getColumnIndexOrThrow("address"));
String phNo =
cursor.getString(cursor.getColumnIndexOrThrow("ph_no"));

stringBuilder.append("ID: ").append(id).append(", Name:


").append(name)
.append(", Address: ").append(address).append(", Phone No:
").append(phNo).append("\n");
}
textViewCustomers.setText(stringBuilder.toString());

// Close the cursor and database connection


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

3. Define the DatabaseHelper class to create and manage the SQLite database
(`DatabaseHelper.java`):

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

public class DatabaseHelper extends SQLiteOpenHelper {

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


private static final int DATABASE_VERSION = 1;

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
// Create the "Customer" table
String SQL_CREATE_CUSTOMER_TABLE = "CREATE TABLE
Customer (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"address TEXT," +
"ph_no TEXT)";
db.execSQL(SQL_CREATE_CUSTOMER_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop the table if it exists and recreate it
db.execSQL("DROP TABLE IF EXISTS Customer");
onCreate(db);
}
}

Q.3] Viva. [5 Marks]


Slip 9
Q.1] Create an application that allows the user to enter a number in the
textbox named „getnum‟. Check whether the number in the textbox
„getnum‟ is Palindrome or not. Print the message accordingly in the label
when the user clicks on the button
„Check‟.
[10 Marks]
s To create an Android application that allows the user to check whether a
number entered in a textbox is a palindrome or not, you can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/buttonCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android:>

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonCheck"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>
</RelativeLayout>
```

2. Implement the logic in the MainActivity class to check whether the entered
number is a palindrome or not (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

EditText editTextNumber;
TextView textViewResult;

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

// Initialize views
editTextNumber = findViewById(R.id.editTextNumber);
textViewResult = findViewById(R.id.textViewResult);
}

// Method to check if the entered number is a palindrome


public void checkPalindrome(View view) {
String numberString = editTextNumber.getText().toString().trim();
if (!numberString.isEmpty()) {
int number = Integer.parseInt(numberString);
if (isPalindrome(number)) {
textViewResult.setText(number + " is a palindrome.");
} else {
textViewResult.setText(number + " is not a palindrome.");
}
} else {
textViewResult.setText("Please enter a number.");
}
}

// Helper method to check if a number is palindrome


private boolean isPalindrome(int number) {
int reversedNumber = 0;
int originalNumber = number;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
return originalNumber == reversedNumber;
}
}
```

Q.2] Java android program to create simple calculator.


[20 Marks]
Refer Slip 2 Q2
Q.3] Viva. [5 Marks]

Slip 10
Q.1] Create an application that allows the user to enter a number in the
textbox named getnum. Check whether the number in the textbox getnum
is Armstrong or not. Print the message using Toast control when the user
clicks on the button Check.
[10 Marks]

To create an Android application that allows the user to check whether a


number entered in a textbox is an Armstrong number or not, and display the
message using a Toast control, you can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/buttonCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android: > </RelativeLayout>
```

2. Implement the logic in the MainActivity class to check whether the entered
number is an Armstrong number or not and display the message using a Toast
control (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText editTextNumber;

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

// Initialize views
editTextNumber = findViewById(R.id.editTextNumber);
}

// Method to check if the entered number is an Armstrong number


public void checkArmstrong(View view) {
String numberString = editTextNumber.getText().toString().trim();
if (!numberString.isEmpty()) {
int number = Integer.parseInt(numberString);
if (isArmstrong(number)) {
showToast(number + " is an Armstrong number.");
} else {
showToast(number + " is not an Armstrong number.");
}
} else {
showToast("Please enter a number.");
}
}

// Helper method to check if a number is an Armstrong number


private boolean isArmstrong(int number) {
int originalNumber = number;
int numberOfDigits = String.valueOf(number).length();
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, numberOfDigits);
number /= 10;
}
return originalNumber == sum;
}

// Helper method to display a toast message


private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
```

.Q.2] Write a program to draw GUI by using Spinner, Buttons.


[20 marks]

To create an Android application that draws a GUI using Spinner and Buttons,
you can follow these steps:
1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<Spinner

android:id="@+id/spinnerOptions"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_marginBottom="16dp"/>

<Button

android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:layout_below="@id/spinnerOptions"

android:layout_centerHorizontal="true"

android:>

<Button

android:id="@+id/buttonReset"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Reset"

android:layout_below="@id/buttonSubmit"

android:layout_centerHorizontal="true"

android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle button clicks and
spinner selection (`MainActivity.java`):
```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.Spinner;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Spinner spinnerOptions;

Button buttonSubmit;

Button buttonReset;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize views

spinnerOptions = findViewById(R.id.spinnerOptions);

buttonSubmit = findViewById(R.id.buttonSubmit);

buttonReset = findViewById(R.id.buttonReset);

// Initialize spinner with options

ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(

this, R.array.options_array, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdo
wn_item);

spinnerOptions.setAdapter(adapter);

// Set listener for spinner item selection

spinnerOptions.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView<?> parent, View view, int


position, long id) {

String selectedItem = parent.getItemAtPosition(position).toString();


Toast.makeText(MainActivity.this, "Selected option: " +
selectedItem, Toast.LENGTH_SHORT).show();

@Override

public void onNothingSelected(AdapterView<?> parent) {

});

// Method to handle submit button click

public void onSubmitClicked(View view) {

Toast.makeText(this, "Submit button clicked",


Toast.LENGTH_SHORT).show();

// Method to handle reset button click

public void onResetClicked(View view) {

spinnerOptions.setSelection(0); // Reset spinner selection to default

Toast.makeText(this, "Reset button clicked",


Toast.LENGTH_SHORT).show();

}
}

```

3. Define an array resource for spinner options (`arrays.xml`):

```xml

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

<resources>

<string-array name="options_array">

<item>Option 1</item>

<item>Option 2</item>

<item>Option 3</item>

<item>Option 4</item>

</string-array>

</resources>

```

Q.3] Viva [5 marks]


Slip 11
Q.1] Create an Android Application to accept two numbers to calculate its
Power and Average. Create two buttons: Power and Average. Display the
appropriate result on the next activity on Button click.
[10 Marks]

s To create an Android application that accepts two numbers, calculates their


power and average, and displays the results in the next activity upon button
click, you can follow these steps:

1. Define the layout for the first activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber1"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:hint="Enter first number"

android:inputType="number"/>

<EditText

android:id="@+id/editTextNumber2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber1"

android:layout_marginTop="16dp"

android:hint="Enter second number"

android:inputType="number"/>

<Button

android:id="@+id/buttonPower"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber2"

android:layout_marginTop="16dp"

android:text="Power"

android:>

<Button
android:id="@+id/buttonAverage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonPower"

android:layout_marginTop="16dp"

android:text="Average"

android:>

</RelativeLayout>

```

2. Define the layout for the second activity (`activity_result.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".ResultActivity">
<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="20sp"

android:textStyle="bold"

android:layout_centerInParent="true"/>

</RelativeLayout>

```

3. Implement the logic in the MainActivity class to handle button clicks and
pass data to the ResultActivity (`MainActivity.java`):

```java

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

public class MainActivity extends AppCompatActivity {


EditText editTextNumber1;

EditText editTextNumber2;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize views

editTextNumber1 = findViewById(R.id.editTextNumber1);

editTextNumber2 = findViewById(R.id.editTextNumber2);

// Method to handle Power button click

public void onPowerClicked(View view) {

double number1 =
Double.parseDouble(editTextNumber1.getText().toString());

double number2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = Math.pow(number1, number2);

navigateToResultActivity("Power Result: " + result);


}

// Method to handle Average button click

public void onAverageClicked(View view) {

double number1 =
Double.parseDouble(editTextNumber1.getText().toString());

double number2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = (number1 + number2) / 2;

navigateToResultActivity("Average Result: " + result);

// Method to navigate to ResultActivity and pass result data

private void navigateToResultActivity(String result) {

Intent intent = new Intent(this, ResultActivity.class);

intent.putExtra("result", result);

startActivity(intent);

```
4. Implement the logic in the ResultActivity class to display the result
(`ResultActivity.java`):

```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.TextView;

public class ResultActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_result);

// Get the result from the intent

String result = getIntent().getStringExtra("result");

// Initialize views

TextView textViewResult = findViewById(R.id.textViewResult);

textViewResult.setText(result);

}
}

Q.2] Create an Android Application to perform following string operation


according to user selection of radio button.
[20 Marks]

To create an Android application that performs string operations according to


the user's selection of radio buttons (upper case, lower case, right 5 characters,
left 5 characters), you can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextString"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a string"
android:layout_marginBottom="16dp"/>

<RadioGroup
android:id="@+id/radioGroupOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextString"
android:orientation="vertical">

<RadioButton
android:id="@+id/radioButtonUpperCase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upper Case"/>

<RadioButton
android:id="@+id/radioButtonLowerCase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lower Case"/>
<RadioButton
android:id="@+id/radioButtonRight5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right 5 Characters"/>

<RadioButton
android:id="@+id/radioButtonLeft5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left 5 Characters"/>

</RadioGroup>

<Button
android:id="@+id/buttonApply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioGroupOptions"
android:text="Apply"
android:>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to perform string operations


according to the selected radio button (`MainActivity.java`):
```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText editTextString;
RadioGroup radioGroupOptions;

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

// Initialize views
editTextString = findViewById(R.id.editTextString);
radioGroupOptions = findViewById(R.id.radioGroupOptions);
}

// Method to perform string operation according to selected radio button


public void applyOperation(View view) {
String input = editTextString.getText().toString().trim();
if (input.isEmpty()) {
Toast.makeText(this, "Please enter a string",
Toast.LENGTH_SHORT).show();
return;
}

int selectedRadioButtonId =
radioGroupOptions.getCheckedRadioButtonId();
RadioButton selectedRadioButton =
findViewById(selectedRadioButtonId);

switch (selectedRadioButton.getId()) {
case R.id.radioButtonUpperCase:
applyUpperCase(input);
break;
case R.id.radioButtonLowerCase:
applyLowerCase(input);
break;
case R.id.radioButtonRight5:
applyRight5(input);
break;
case R.id.radioButtonLeft5:
applyLeft5(input);
break;
}
}
// Method to convert string to upper case
private void applyUpperCase(String input) {
String result = input.toUpperCase();
displayResult(result);
}

// Method to convert string to lower case


private void applyLowerCase(String input) {
String result = input.toLowerCase();
displayResult(result);
}

// Method to get right 5 characters of the string


private void applyRight5(String input) {
int length = input.length();
String result = length <= 5 ? input : input.substring(length - 5);
displayResult(result);
}

// Method to get left 5 characters of the string


private void applyLeft5(String input) {
String result = input.length() <= 5 ? input : input.substring(0, 5);
displayResult(result);
}

// Method to display the result in a toast message


private void displayResult(String result) {
Toast.makeText(this, "Result: " + result,
Toast.LENGTH_SHORT).show();
}
}
```

Q.3] Viva. [5 Marks]

Slip 12
Q.1] Construct an Android app that toggles a light bulb ON and OFF
when the user clicks on toggle button.
[10 Marks]

To create an Android application that toggles a light bulb on and off when the
user clicks on a toggle button, you can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<ToggleButton

android:id="@+id/toggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textOff="OFF"

android:textOn="ON"
android:checked="false"

android:layout_centerInParent="true"

android:>

<ImageView

android:id="@+id/imageViewLightBulb"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/ic_light_bulb_off"

android:layout_below="@id/toggleButton"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"/>

</RelativeLayout>

```

2. Add the light bulb images to the drawable folder. You should have two
images: `ic_light_bulb_on.png` and `ic_light_bulb_off.png`.

3. Implement the logic in the MainActivity class to toggle the light bulb on and
off when the toggle button is clicked (`MainActivity.java`):

```java
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.ImageView;

import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

ToggleButton toggleButton;

ImageView imageViewLightBulb;

boolean isLightOn = false;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize views

toggleButton = findViewById(R.id.toggleButton);

imageViewLightBulb = findViewById(R.id.imageViewLightBulb);

}
// Method to toggle the light bulb on and off

public void toggleLight(View view) {

isLightOn = !isLightOn;

if (isLightOn) {

imageViewLightBulb.setImageResource(R.drawable.ic_light_bulb_on);

} else {

imageViewLightBulb.setImageResource(R.drawable.ic_light_bulb_off);

Q.2] Create an Android application which will ask the user to input his /
her name. A message should display the two items concatenated in a label.
Change the format of the label using radio buttons and check boxes for
selection. The user can make the label text bold, underlined or italic as
well as change its color. Also include buttons to display the message in the
label, clear the text boxes as well as label. Finally exit.

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:layout_marginBottom="16dp"/>

<RadioGroup
android:id="@+id/radioGroupFormat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="@id/editTextName">

<RadioButton
android:id="@+id/radioButtonBold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold"/>

<RadioButton
android:id="@+id/radioButtonItalic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Italic"/>

<RadioButton
android:id="@+id/radioButtonUnderline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Underline"/>
</RadioGroup>

<CheckBox
android:id="@+id/checkBoxColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change color"
android:layout_below="@id/radioGroupFormat"/>
<Button
android:id="@+id/buttonDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display"
android:layout_below="@id/checkBoxColor"
android:>

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

<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonClear"
android:layout_marginTop="16dp"/>
</RelativeLayout>
```

2. Implement the logic in the MainActivity class to handle button clicks and
customize the label's format (`MainActivity.java`):

```java
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {

EditText editTextName;
RadioGroup radioGroupFormat;
CheckBox checkBoxColor;
TextView textViewMessage;

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

// Initialize views
editTextName = findViewById(R.id.editTextName);
radioGroupFormat = findViewById(R.id.radioGroupFormat);
checkBoxColor = findViewById(R.id.checkBoxColor);
textViewMessage = findViewById(R.id.textViewMessage);
}

// Method to display the concatenated name in the label with customized


format
public void displayMessage(View view) {
String name = editTextName.getText().toString().trim();
if (name.isEmpty()) {
textViewMessage.setText("Please enter your name");
return;
}

StringBuilder formattedName = new StringBuilder();


formattedName.append("Hello, ").append(name).append("!");

// Apply text style


int selectedTextStyleId = radioGroupFormat.getCheckedRadioButtonId();
switch (selectedTextStyleId) {
case R.id.radioButtonBold:
textViewMessage.setTypeface(null, Typeface.BOLD);
break;
case R.id.radioButtonItalic:
textViewMessage.setTypeface(null, Typeface.ITALIC);
break;
case R.id.radioButtonUnderline:
textViewMessage.setPaintFlags(textViewMessage.getPaintFlags() |
android.graphics.Paint.UNDERLINE_TEXT_FLAG);
break;
default:
textViewMessage.setTypeface(null, Typeface.NORMAL);
textViewMessage.setPaintFlags(0);
}

// Apply text color


if (checkBoxColor.isChecked()) {
textViewMessage.setTextColor(Color.BLUE);
} else {
textViewMessage.setTextColor(Color.BLACK);
}

textViewMessage.setText(formattedName.toString());
}

// Method to clear the text in the label and edit text


public void clearMessage(View view) {
editTextName.setText("");
textViewMessage.setText("");
radioGroupFormat.clearCheck();
checkBoxColor.setChecked(false);
textViewMessage.setTypeface(null, Typeface.NORMAL);
textViewMessage.setTextColor(Color.BLACK);
textViewMessage.setPaintFlags(0);
}
}

Q.3] Viva. [5 Marks]

Slip 13
Q.1] Java android program to demonstrate Registration form with
validation.
[10 Marks]

1. Define the layout for the registration form (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

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

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

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextEmail"
android:layout_marginTop="16dp"
android:hint="Password"
android:inputType="textPassword"/>

<Button
android:id="@+id/buttonRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"
android:text="Register"
android:>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to handle registration and


validation (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {

EditText editTextUsername, editTextEmail, editTextPassword;

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

// Initialize views
editTextUsername = findViewById(R.id.editTextUsername);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextPassword);
}

// Method to handle registration button click


public void register(View view) {
String username = editTextUsername.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();

// Validate inputs
if (validateUsername(username) && validateEmail(email) &&
validatePassword(password)) {
// Registration successful
Toast.makeText(this, "Registration successful",
Toast.LENGTH_SHORT).show();
}
}

// Method to validate username


private boolean validateUsername(String username) {
if (username.isEmpty()) {
editTextUsername.setError("Username is required");
return false;
}
return true;
}
// Method to validate email
private boolean validateEmail(String email) {
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(email);
if (!matcher.matches()) {
editTextEmail.setError("Enter a valid email address");
return false;
}
return true;
}

// Method to validate password


private boolean validatePassword(String password) {
if (password.length() < 6) {
editTextPassword.setError("Password must be at least 6 characters");
return false;
}
return true;
}
}

Q.2] Write a Java Android Program to Demonstrate List View Activity


with all operations Such as: Insert, Delete, Search
[20 marks]
1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

```xml
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNewItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter item"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/buttonInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:layout_below="@id/editTextNewItem"
android:>

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

</RelativeLayout>
```

2. Create a custom layout for list items (`list_item.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="8dp"/>
```
3. Implement the logic in the MainActivity class to handle list operations
(`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private EditText editTextNewItem;


private ListView listViewItems;
private ArrayAdapter<String> adapter;
private ArrayList<String> items;

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

// Initialize views
editTextNewItem = findViewById(R.id.editTextNewItem);
listViewItems = findViewById(R.id.listViewItems);

// Initialize array list and adapter


items = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.list_item, R.id.textViewItem,
items);

// Set adapter to list view


listViewItems.setAdapter(adapter);
}

// Method to handle insert button click


public void insertItem(View view) {
String newItem = editTextNewItem.getText().toString().trim();
if (!newItem.isEmpty()) {
items.add(newItem);
adapter.notifyDataSetChanged();
editTextNewItem.setText("");
}
}
}
```

4. Implement delete and search functionality in MainActivity.java as follows:

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private EditText editTextNewItem;


private ListView listViewItems;
private ArrayAdapter<String> adapter;
private ArrayList<String> items;

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

// Initialize views
editTextNewItem = findViewById(R.id.editTextNewItem);
listViewItems = findViewById(R.id.listViewItems);

// Initialize array list and adapter


items = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.list_item, R.id.textViewItem,
items);
// Set adapter to list view
listViewItems.setAdapter(adapter);
}

// Method to handle insert button click


public void insertItem(View view) {
String newItem = editTextNewItem.getText().toString().trim();
if (!newItem.isEmpty()) {
items.add(newItem);
adapter.notifyDataSetChanged();
editTextNewItem.setText("");
}
}

// Method to handle delete button click


public void deleteItem(View view) {
int position = listViewItems.getPositionForView(view);
items.remove(position);
adapter.notifyDataSetChanged();
}

// Method to handle search button click


public void searchItem(View view) {
String query = editTextNewItem.getText().toString().trim();
if (!query.isEmpty()) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).equalsIgnoreCase(query)) {
listViewItems.smoothScrollToPosition(i);
return;
}
}
// If item not found
editTextNewItem.setError("Item not found");
}
}
}
Q.3] Viva. [5 Marks]

Slip 14
Q.1] Construct an Android application to accept a number and calculate
and display Factorial of a given number in TextView.
[10 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter a number"

android:inputType="number"/>

<Button
android:id="@+id/buttonCalculate"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Calculate Factorial"

android:layout_below="@id/editTextNumber"

android:layout_marginTop="16dp"

android:>

<TextView

android:id="@+id/textViewResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonCalculate"

android:layout_marginTop="16dp"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to calculate the factorial and
display the result (`MainActivity.java`):

```java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

EditText editTextNumber;

TextView textViewResult;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize views

editTextNumber = findViewById(R.id.editTextNumber);

textViewResult = findViewById(R.id.textViewResult);

// Method to calculate factorial

public void calculateFactorial(View view) {


String numberString = editTextNumber.getText().toString().trim();

if (!numberString.isEmpty()) {

int number = Integer.parseInt(numberString);

long factorial = computeFactorial(number);

textViewResult.setText("Factorial of " + number + " is " + factorial);

} else {

textViewResult.setText("Please enter a number");

// Method to compute factorial

private long computeFactorial(int n) {

if (n == 0 || n == 1) {

return 1;

long factorial = 1;

for (int i = 2; i <= n; i++) {

factorial *= i;

return factorial;

}
```

Q.2] Create an Android application, which show Login Form. After


clicking
LOGIN button display the “Login Successful…” message if username and
password is same else display “Invalid Login” message in Toast Control.
[20 Marks]

1. Define the layout for the login form (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

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

<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextUsername"
android:layout_marginTop="16dp"
android:hint="Password"
android:inputType="textPassword"/>

<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LOGIN"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"
android: ></RelativeLayout>
```

2. Implement the logic in the MainActivity class to handle the login button click
and display toast messages (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private static final String CORRECT_USERNAME = "user";


private static final String CORRECT_PASSWORD = "pass";

private EditText editTextUsername;


private EditText editTextPassword;

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

// Initialize views
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
}

// Method to handle login button click


public void login(View view) {
String username = editTextUsername.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();

if (username.equals(CORRECT_USERNAME) &&
password.equals(CORRECT_PASSWORD)) {
showToast("Login Successful");
} else {
showToast("Invalid Login");
}
}

// Method to display toast message


private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
```

Q.3] Viva. [5 Marks]

Slip 15
Q1] Construct an Android application to accept two numbers in two
EditText, with four buttons as ADD, SUB, DIV and MULT and display
Result using Toast Control.
[10 Marks]

To create an Android application that accepts two numbers, performs arithmetic


operations on them, and displays the result using Toast, you can follow these
steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber1"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:hint="Enter number 1"

android:inputType="number"/>

<EditText

android:id="@+id/editTextNumber2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber1"

android:layout_marginTop="16dp"

android:hint="Enter number 2"

android:inputType="number"/>

<Button

android:id="@+id/buttonAdd"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="ADD"

android:layout_below="@id/editTextNumber2"

android:layout_marginTop="16dp"

android:>

<Button
android:id="@+id/buttonSub"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="SUB"

android:layout_below="@id/buttonAdd"

android:layout_marginTop="16dp"

android:layout_alignStart="@id/buttonAdd"

android:>

<Button

android:id="@+id/buttonDiv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="DIV"

android:layout_below="@id/buttonSub"

android:layout_marginTop="16dp"

android:layout_alignStart="@id/buttonSub"

android:>

<Button

android:id="@+id/buttonMult"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="MULT"

android:layout_below="@id/buttonDiv"

android:layout_marginTop="16dp"

android:layout_alignStart="@id/buttonDiv"

android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle arithmetic operations


and display the result using Toast (`MainActivity.java`):

```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private EditText editTextNumber1;

private EditText editTextNumber2;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize views

editTextNumber1 = findViewById(R.id.editTextNumber1);

editTextNumber2 = findViewById(R.id.editTextNumber2);

// Method to handle addition button click

public void add(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 + num2;

showToast("Addition result: " + result);

}
// Method to handle subtraction button click

public void subtract(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 - num2;

showToast("Subtraction result: " + result);

// Method to handle division button click

public void divide(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

if (num2 != 0) {

double result = num1 / num2;

showToast("Division result: " + result);

} else {

showToast("Cannot divide by zero");

}
// Method to handle multiplication button click

public void multiply(View view) {

double num1 =
Double.parseDouble(editTextNumber1.getText().toString());

double num2 =
Double.parseDouble(editTextNumber2.getText().toString());

double result = num1 * num2;

showToast("Multiplication result: " + result);

// Method to display toast message

private void showToast(String message) {

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

Q2] Construct a bank app to display different menu like withdraw, deposit
etc.
[20 Marks]
Simple Bank App
Simple Bank Application

ACCOUNT NUMBER

ACCOUNT TYPE
BALANCE

Checking Savings

Deposit

Balance
Create
Withdraw
public class MainActivity extends AppCompatActivity {

private double balance = 1000.0; // Initial balance

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

// Method to handle deposit button click


public void deposit(View view) {
// Add deposit logic here
balance += 500.0; // Example: Deposit 500.0
showToast("Deposit successful. Current balance: " + balance);
}

// Method to handle withdraw button click


public void withdraw(View view) {
// Add withdraw logic here
if (balance >= 500.0) { // Example: Minimum withdrawal amount is 500.0
balance -= 500.0; // Example: Withdraw 500.0
showToast("Withdrawal successful. Current balance: " + balance);
} else {
showToast("Insufficient balance to withdraw");
}
}

// Method to display toast message


private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Q3. Viva [05 Marks]

Slip 16
Q1] Create a Simple Android Application Which Send ―Hello‖ message
from one activity to another with help of Button (Use Intent).
[10 Marks]

1. Define the layout for the first activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<Button

android:id="@+id/buttonSendHello"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Send Hello"

android:layout_centerInParent="true"

android:>

</RelativeLayout>

```

2. Define the layout for the second activity (`activity_display_message.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".DisplayMessageActivity">

<TextView

android:id="@+id/textViewMessage"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:textSize="24sp"

android:layout_centerInParent="true"/>

</RelativeLayout>

```

3. Implement the logic in the MainActivity class to send the "Hello" message to
the second activity (`MainActivity.java`):

```java

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

// Method to handle button click and send "Hello" message

public void sendHello(View view) {

Intent intent = new Intent(this, DisplayMessageActivity.class);

intent.putExtra("message", "Hello");

startActivity(intent);

```

4. Implement the logic in the DisplayMessageActivity class to receive and


display the "Hello" message (`DisplayMessageActivity.java`):

```java

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_display_message);

// Receive the "Hello" message from the intent

Intent intent = getIntent();

String message = intent.getStringExtra("message");

// Display the "Hello" message in a TextView

TextView textViewMessage = findViewById(R.id.textViewMessage);

textViewMessage.setText(message);

Q2] Create an Android application, with two activity first activity will
have an EditText and a Button where the user can enter player name and
after clicking on button the entered name will be display in another
Activity. Second activity has the BACK button to transition to first
activity (Using Intent).
[20 Marks]

To create an Android application with two activities where the first activity
allows the user to enter a player name and the second activity displays the
entered name, you can follow these steps:
1. Define the layout for the first activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextPlayerName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter player name"/>

<Button

android:id="@+id/buttonSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Submit"

android:layout_below="@id/editTextPlayerName"

android:layout_marginTop="16dp"

android:>

</RelativeLayout>

```

2. Define the layout for the second activity (`activity_display_name.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".DisplayNameActivity">

<TextView

android:id="@+id/textViewPlayerName"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:textSize="24sp"

android:layout_centerInParent="true"/>

<Button

android:id="@+id/buttonBack"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="BACK"

android:layout_below="@id/textViewPlayerName"

android:layout_marginTop="16dp"

android:layout_centerHorizontal="true"

android:>

</RelativeLayout>

```

3. Implement the logic in the MainActivity class to handle submission of player


name and transition to the second activity (`MainActivity.java`):

```java

import android.content.Intent;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Method to handle submission of player name

public void submitName(View view) {

EditText editTextPlayerName = findViewById(R.id.editTextPlayerName);

String playerName = editTextPlayerName.getText().toString();

Intent intent = new Intent(this, DisplayNameActivity.class);

intent.putExtra("playerName", playerName);

startActivity(intent);

}
}

```

4. Implement the logic in the DisplayNameActivity class to receive and display


the player name, and handle the "BACK" button click
(`DisplayNameActivity.java`):

```java

import android.content.Intent;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.TextView;

public class DisplayNameActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_display_name);

// Receive the player name from the intent

Intent intent = getIntent();


String playerName = intent.getStringExtra("playerName");

// Display the player name in a TextView

TextView textViewPlayerName =
findViewById(R.id.textViewPlayerName);

textViewPlayerName.setText(playerName);

// Method to handle the "BACK" button click

public void goBack(View view) {

finish(); // Close the current activity and go back to the previous one

Q3] Viva [05 Marks]


Slip 17
Q1] Write an Android Program to demonstrate Activity life Cycle. [10
Marks]
Refer to slip 8 Q1

Q2] Write a PhoneGap application to create a contact.


Options are:
• Searching for Contacts
• Cloning Contacts
• Removing Contacts. [20 Marks]

To create a PhoneGap application that allows users to search for contacts, clone
contacts, and remove contacts, you can follow these steps:

1. Create a new PhoneGap project:

```bash
phonegap create ContactManager
cd ContactManager
```

2. Add required platforms (e.g., Android):

```bash
phonegap platform add android
```

3. Define the HTML structure and JavaScript logic for the application
(`index.html`):
```html
<!DOCTYPE html>
<html>
<head>
<title>Contact Manager</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<h1>Contact Manager</h1>
<button Contacts</button>
<button Contact</button>
<button Contact</button>
</body>
</html>
```

4. Implement the JavaScript logic for the application (`js/index.js`):

```javascript
// Function to search for contacts
function searchContacts() {
navigator.contacts.find(['*'], function(contacts) {
alert('Found ' + contacts.length + ' contacts.');
}, function(error) {
alert('Error searching for contacts: ' + error);
});
}

// Function to clone a contact


function cloneContact() {
// Example: Clone the first contact found
navigator.contacts.find(['*'], function(contacts) {
if (contacts.length > 0) {
var contactToClone = contacts[0];
var clonedContact = navigator.contacts.create();
clonedContact.displayName = contactToClone.displayName + '
(Clone)';
clonedContact.save(function() {
alert('Contact cloned successfully.');
}, function(error) {
alert('Error cloning contact: ' + error);
});
} else {
alert('No contacts found to clone.');
}
}, function(error) {
alert('Error searching for contacts: ' + error);
});
}

// Function to remove a contact


function removeContact() {
// Example: Remove the first contact found
navigator.contacts.find(['*'], function(contacts) {
if (contacts.length > 0) {
var contactToRemove = contacts[0];
contactToRemove.remove(function() {
alert('Contact removed successfully.');
}, function(error) {
alert('Error removing contact: ' + error);
});
} else {
alert('No contacts found to remove.');
}
}, function(error) {
alert('Error searching for contacts: ' + error);
});
}
```

5. Build and run the PhoneGap application on your device or emulator:

```bash
phonegap run android
```
Slip 18
Q1] Create an Android Application that will change color of the screen
and change the font size of text view using xml.
[10 Marks]

To create an Android application that changes the color of the screen and the
font size of a TextView using XML, you can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

android:background="@color/background_color"

tools:context=".MainActivity">

<TextView
android:id="@+id/textViewMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, Change Me!"

android:textSize="@dimen/text_size"

android:textColor="@color/text_color"

android:layout_centerInParent="true"/>

</RelativeLayout>

```

2. Define colors and dimensions in the resource files (`res/values/colors.xml`


and `res/values/dimens.xml`):

`colors.xml`:

```xml

<resources>

<color name="background_color">#FFFFFF</color> <!-- White background


color -->

<color name="text_color">#000000</color> <!-- Black text color -->

</resources>

```
`dimens.xml`:

```xml

<resources>

<dimen name="text_size">24sp</dimen> <!-- Default text size -->

</resources>

Q2] Create table Project (id, name, dept, city). Create Application to
perform the following operations. (using SQLite database) i] Add at
least 5 records.
ii] Display all the records.
[20 Marks]

To create an Android application that performs operations on a SQLite database


for a "Project" table, including adding records and displaying all records, you
can follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"
tools:context=".MainActivity">

<Button

android:id="@+id/buttonAddRecord"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Add Record"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:>

<Button

android:id="@+id/buttonDisplayRecords"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Display Records"

android:layout_below="@id/buttonAddRecord"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:>

<TextView
android:id="@+id/textViewRecords"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=""

android:layout_below="@id/buttonDisplayRecords"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle adding records and
displaying all records (`MainActivity.java`):

```java

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.TextView;

import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

private DatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

dbHelper = new DatabaseHelper(this);

// Method to add a record

public void addRecord(View view) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", "Project X");

values.put("dept", "IT");

values.put("city", "New York");


long newRowId = db.insert("Project", null, values);

if (newRowId != -1) {

Toast.makeText(this, "Record added successfully",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "Error adding record",


Toast.LENGTH_SHORT).show();

// Method to display all records

public void displayRecords(View view) {

SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM Project", null);

StringBuilder stringBuilder = new StringBuilder();

while (cursor.moveToNext()) {

int id = cursor.getInt(cursor.getColumnIndex("id"));

String name = cursor.getString(cursor.getColumnIndex("name"));

String dept = cursor.getString(cursor.getColumnIndex("dept"));

String city = cursor.getString(cursor.getColumnIndex("city"));

stringBuilder.append("ID: ").append(id)
.append(", Name: ").append(name)

.append(", Dept: ").append(dept)

.append(", City: ").append(city)

.append("\n");

cursor.close();

TextView textViewRecords = findViewById(R.id.textViewRecords);

textViewRecords.setText(stringBuilder.toString());

@Override

protected void onDestroy() {

dbHelper.close();

super.onDestroy();

```

3. Create a DatabaseHelper class to manage the SQLite database


(`DatabaseHelper.java`):
```java

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

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

private static final int DATABASE_VERSION = 1;

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE Project (" +

"id INTEGER PRIMARY KEY AUTOINCREMENT," +

"name TEXT," +

"dept TEXT," +

"city TEXT)");

}
@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS Project");

onCreate(db);

Q3] Viva [5 Marks]


Slip 19
Q1] Write an Android Program to Change the Image Displayed on the
Screen.
[10 Marks]

1. Add images to the drawable folder in your project's resources. For this
example, let's assume you have two images named "image1.jpg" and
"image2.jpg".

2. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<ImageView

android:id="@+id/imageView"
android:layout_width="match_parent"

android:layout_height="match_parent"

android:scaleType="fitCenter"

android:src="@drawable/image1"/>

<Button

android:id="@+id/buttonChangeImage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Change Image"

android:layout_centerInParent="true"

android:>

</RelativeLayout>

```

3. Implement the logic in the MainActivity class to handle changing the image
(`MainActivity.java`):

```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;

import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

private ImageView imageView;

private int currentImage = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

imageView = findViewById(R.id.imageView);

// Method to change the image displayed

public void changeImage(View view) {

if (currentImage == 1) {

imageView.setImageResource(R.drawable.image2);

currentImage = 2;

} else {
imageView.setImageResource(R.drawable.image1);

currentImage = 1;

Q2] Construct an Android Application to create two option menu as Find


Factorial and Find Sum of Digits. Accept a number and calculate Factorial
and Sum of Digits of a given number by clicking Menu.
[20 Marks]

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"/>

<Button
android:id="@+id/buttonCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:>

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="@id/buttonCalculate"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"/>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to calculate factorial and sum
of digits (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber;


private TextView textViewResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextNumber = findViewById(R.id.editTextNumber);
textViewResult = findViewById(R.id.textViewResult);
}

// Method to calculate factorial of a number


private int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

// Method to calculate sum of digits of a number


private int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}

// Method to handle click on Calculate button


public void calculate(View view) {
try {
int number = Integer.parseInt(editTextNumber.getText().toString());
int result = factorial(number); // Default: calculate factorial
textViewResult.setText("Factorial: " + result);
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_SHORT).show();
}
}

// Method to create option menu


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}

// Method to handle option menu item selection


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuFactorial:
calculateFactorial();
return true;
case R.id.menuSumOfDigits:
calculateSumOfDigits();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

// Method to calculate factorial of a number


private void calculateFactorial() {
try {
int number = Integer.parseInt(editTextNumber.getText().toString());
int result = factorial(number);
textViewResult.setText("Factorial: " + result);
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_SHORT).show();
}
}

// Method to calculate sum of digits of a number


private void calculateSumOfDigits() {
try {
int number = Integer.parseInt(editTextNumber.getText().toString());
int result = sumOfDigits(number);
textViewResult.setText("Sum of Digits: " + result);
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_SHORT).show();
}
}
}
```

3. Create a menu resource file for the option menu


(`res/menu/main_menu.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menuFactorial"
android:title="Find Factorial"/>
<item
android:id="@+id/menuSumOfDigits"
android

:title="Find Sum of Digits"/>


</menu>
Slip 20
Q1] Write an application to accept two numbers from the user and
displays them. But Reject input if both numbers are greater than 20 and
asks for two new numbers.
[10 marks]

To create an Android application that accepts two numbers from the user and
displays them, rejecting the input if both numbers are greater than 20, you can
follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextNumber1"
android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter first number"

android:inputType="number"/>

<EditText

android:id="@+id/editTextNumber2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextNumber1"

android:layout_marginTop="16dp"

android:hint="Enter second number"

android:inputType="number"/>

<Button

android:id="@+id/buttonSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:layout_below="@id/editTextNumber2"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"
android:>

<TextView

android:id="@+id/textViewNumbers"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonSubmit"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:text=""

android:textSize="18sp"/>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle input validation and
display numbers (`MainActivity.java`):

```java

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.EditText;
import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber1, editTextNumber2;

private TextView textViewNumbers;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editTextNumber1 = findViewById(R.id.editTextNumber1);

editTextNumber2 = findViewById(R.id.editTextNumber2);

textViewNumbers = findViewById(R.id.textViewNumbers);

// Method to handle click on Submit button

public void submit(View view) {

try {

int num1 = Integer.parseInt(editTextNumber1.getText().toString());


int num2 = Integer.parseInt(editTextNumber2.getText().toString());

if (num1 > 20 && num2 > 20) {

Toast.makeText(this, "Both numbers are greater than 20. Enter new


numbers.", Toast.LENGTH_SHORT).show();

editTextNumber1.setText("");

editTextNumber2.setText("");

textViewNumbers.setText("");

} else {

textViewNumbers.setText("Number 1: " + num1 + "\nNumber 2: " +


num2);

} catch (NumberFormatException e) {

Toast.makeText(this, "Please enter valid numbers.",


Toast.LENGTH_SHORT).show();

Q2] Java Android Program to send email with attachment.


[20 marks]

To create an Android application that sends an email with an attachment, you


can follow these steps:
1. Add permissions to the AndroidManifest.xml file for sending email:

```xml

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

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

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

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

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

```

2. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">
<Button

android:id="@+id/buttonSendEmail"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send Email"

android:layout_centerInParent="true"

android:>

</RelativeLayout>

```

3. Implement the logic in the MainActivity class to send email with an


attachment (`MainActivity.java`):

```java

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.support.v7.app.AppCompatActivity;

import android.view.View;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

private static final String EMAIL_ADDRESS = "recipient@example.com";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Method to send email with attachment

public void sendEmail(View view) {

try {

Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setType("text/plain");

emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]


{EMAIL_ADDRESS});

emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");


emailIntent.putExtra(Intent.EXTRA_TEXT, "Email Body");

// Attach file

File file = new File(Environment.getExternalStorageDirectory(),


"example.txt");

Uri uri = Uri.fromFile(file);

emailIntent.putExtra(Intent.EXTRA_STREAM, uri);

startActivity(Intent.createChooser(emailIntent, "Send Email"));

} catch (Exception e) {

Toast.makeText(this, "Error sending email",


Toast.LENGTH_SHORT).show();

Q3] Viva [05 marks]


Slip 21
Q.1] Write an Android Program to demonstrate Activity life Cycle.
[10 Marks]

Refer to slip 8 Q1

Q.2] Create an Android Application that writes data to the SD Card


[ 20 Marks]

To create an Android application that writes data to the SD card, follow these
steps:

1. Add permissions to the AndroidManifest.xml file to write to external


storage:

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

2. Define the layout for the activity (`activity_main.xml`):


```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/buttonWriteToSDCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write to SD Card"
android:layout_centerInParent="true"
android:>

</RelativeLayout>
```

3. Implement the logic in the MainActivity class to write data to the SD card
(`MainActivity.java`):

```java
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private static final String FILE_NAME = "data.txt";


private static final String DATA_TO_WRITE = "Hello, this is data to be
written to the SD card.";

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

// Method to write data to the SD card


public void writeToSDCard(View view) {
try {
File directory = new File(Environment.getExternalStorageDirectory(),
"MyAppData");
if (!directory.exists()) {
directory.mkdirs();
}

File file = new File(directory, FILE_NAME);


FileOutputStream fos = new FileOutputStream(file);
fos.write(DATA_TO_WRITE.getBytes());
fos.close();

Toast.makeText(this, "Data written to SD card",


Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error writing data to SD card",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
Slip22
Q.1] Write an Java Android Program to Change the Image on the Screen.
[10 Marks]

Refer to slip 19 Q1

Q.2] Perform following numeric operation according to user selection of


radio button.
[20 Marks]

To create an Android application that performs numeric operations according to


the user's selection of radio buttons, follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"/>

<RadioGroup
android:id="@+id/radioGroupOperations"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp">

<RadioButton
android:id="@+id/radioButtonOddEven"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Odd/Even"/>

<RadioButton
android:id="@+id/radioButtonPositiveNegative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Positive/Negative"/>

<RadioButton
android:id="@+id/radioButtonSquare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Square"/>
</RadioGroup>

<Button
android:id="@+id/buttonPerformOperation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Perform Operation"
android:layout_below="@id/radioGroupOperations"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:>

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonPerformOperation"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text=""
android:textSize="18sp"/>
</RelativeLayout>
```

2. Implement the logic in the MainActivity class to perform the selected


numeric operation (`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber;


private RadioGroup radioGroupOperations;
private TextView textViewResult;

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

editTextNumber = findViewById(R.id.editTextNumber);
radioGroupOperations = findViewById(R.id.radioGroupOperations);
textViewResult = findViewById(R.id.textViewResult);
}

// Method to perform the selected numeric operation


public void performOperation(View view) {
try {
int number = Integer.parseInt(editTextNumber.getText().toString());
int operationId = radioGroupOperations.getCheckedRadioButtonId();

switch (operationId) {
case R.id.radioButtonOddEven:
checkOddEven(number);
break;
case R.id.radioButtonPositiveNegative:
checkPositiveNegative(number);
break;
case R.id.radioButtonSquare:
calculateSquare(number);
break;
default:
Toast.makeText(this, "Please select an operation",
Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_SHORT).show();
}
}

// Method to check if a number is odd or even


private void checkOddEven(int number) {
if (number % 2 == 0) {
textViewResult.setText(number + " is even");
} else {
textViewResult.setText(number + " is odd");
}
}

// Method to check if a number is positive or negative


private void checkPositiveNegative(int number) {
if (number >= 0) {
textViewResult.setText(number + " is positive");
} else {
textViewResult.setText(number + " is negative");
}
}

// Method to calculate the square of a number


private void calculateSquare(int number) {
int square = number * number;
textViewResult.setText("Square of " + number + " is " + square);
}
}

Q.3] Viva. [5 Marks]

Slip 23
Q. 1] Write a Java android program to demonstrate implicit intent.
[10 Marks]

To demonstrate implicit intent in an Android program, you can create an


application that opens a web page when a button is clicked. Here's how you can
do it:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<Button

android:id="@+id/buttonOpenWebpage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Open Webpage"

android:layout_centerInParent="true"
android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle the button click and
open a web page (`MainActivity.java`):

```java

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

// Method to handle button click to open a web page

public void openWebpage(View view) {

String url = "https://www.example.com"; // Replace with the desired URL

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse(url));

// Check if there's an app to handle the intent

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

startActivity(intent);

} else {

Toast.makeText(this, "No app to handle this intent",


Toast.LENGTH_SHORT).show();

Q.2] Create an Android application which will ask the user to input his /
her name. A message should display the two items concatenated in a
label. Change the format of the label using radio buttons and check
boxes for selection. The user can make the label text bold, underlined
or italic as well as change its color. Also include buttons to display the
message in the label, clear the text boxes as well as label. Finally exit.
[20 Marks]

To create an Android application with the described functionality, you can


follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:inputType="text"/>
<Button

android:id="@+id/buttonDisplay"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Display"

android:layout_below="@id/editTextName"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:>

<TextView

android:id="@+id/textViewMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/buttonDisplay"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:text=""

android:textSize="18sp"/>

<CheckBox

android:id="@+id/checkBoxBold"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Bold"

android:layout_below="@id/textViewMessage"

android:layout_marginTop="16dp"/>

<CheckBox

android:id="@+id/checkBoxUnderline"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Underline"

android:layout_below="@id/checkBoxBold"

android:layout_marginTop="16dp"/>

<CheckBox

android:id="@+id/checkBoxItalic"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Italic"

android:layout_below="@id/checkBoxUnderline"

android:layout_marginTop="16dp"/>
<RadioGroup

android:id="@+id/radioGroupColor"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/checkBoxItalic"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp">

<RadioButton

android:id="@+id/radioButtonRed"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Red"/>

<RadioButton

android:id="@+id/radioButtonBlue"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Blue"/>

<RadioButton

android:id="@+id/radioButtonGreen"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Green"/>

</RadioGroup>

<Button

android:id="@+id/buttonClear"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Clear"

android:layout_below="@id/radioGroupColor"

android:layout_marginTop="16dp"

android:layout_marginRight="8dp"

android:layout_alignParentRight="true"

android:>

<Button

android:id="@+id/buttonExit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Exit"

android:layout_below="@id/radioGroupColor"
android:layout_marginTop="16dp"

android:layout_marginLeft="8dp"

android:layout_toLeftOf="@id/buttonClear"

android:>

</RelativeLayout>

```

2. Implement the logic in the MainActivity class to handle button clicks and
change the format of the label (`MainActivity.java`):

```java

import android.graphics.Color;

import android.graphics.Typeface;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.CheckBox;

import android.widget.RadioButton;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


private TextView textViewMessage;

private CheckBox checkBoxBold;

private CheckBox checkBoxUnderline;

private CheckBox checkBoxItalic;

private RadioButton radioButtonRed;

private RadioButton radioButtonBlue;

private RadioButton radioButtonGreen;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textViewMessage = findViewById(R.id.textViewMessage);

checkBoxBold = findViewById(R.id.checkBoxBold);

checkBoxUnderline = findViewById(R.id.checkBoxUnderline);

checkBoxItalic = findViewById(R.id.checkBoxItalic);

radioButtonRed = findViewById(R.id.radioButtonRed);

radioButtonBlue = findViewById(R.id.radioButtonBlue);

radioButtonGreen = findViewById(R.id.radioButtonGreen);

}
// Method to display the message with selected formatting

public void displayMessage(View view) {

String name = ((TextView)


findViewById(R.id.editTextName)).getText().toString();

String message = name;

// Apply formatting based on selected options

if (checkBoxBold.isChecked()) {

textViewMessage.setTypeface(null, Typeface.BOLD);

} else {

textViewMessage.setTypeface(null, Typeface.NORMAL);

if (checkBoxUnderline.isChecked()) {

message = "<u>" + message + "</u>";

if (checkBoxItalic.isChecked()) {

message = "<i>" + message + "</i>";

}
if (radioButtonRed.isChecked()) {

textViewMessage.setTextColor(Color.RED);

} else if (radioButtonBlue.isChecked()) {

textViewMessage.setTextColor(Color.BLUE);

} else if (radioButtonGreen.isChecked()) {

textViewMessage.setTextColor(Color.GREEN);

textViewMessage.setText(android.text.Html.fromHtml(message));

// Method to clear the message and text formatting

public void clearMessage(View view) {

textViewMessage.setText("");

checkBoxBold.setChecked(false);

checkBoxUnderline.setChecked(false);

checkBoxItalic.setChecked(false);

radioButtonRed.setChecked(false);

radioButtonBlue.setChecked(false);

radioButtonGreen.setChecked(false);

textViewMessage.setTypeface(null, Typeface.NORMAL);

textViewMessage.setTextColor(Color.BLACK);
}

// Method to exit the application

public void exitApp(View view) {

finish();

Slip 24
Q.1] Write an application to accept a string from the user. With two
buttons to display the string in Uppercase and Lowercase using the toast
message.
[10 Marks]

To create an Android application that accepts a string from the user and
displays it in both uppercase and lowercase using toast messages, you can
follow these steps:

1. Define the layout for the activity (`activity_main.xml`):

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextString"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a string"
android:inputType="text"/>
<Button
android:id="@+id/buttonUpperCase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Uppercase"
android:layout_below="@id/editTextString"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:>

<Button
android:id="@+id/buttonLowerCase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lowercase"
android:layout_below="@id/buttonUpperCase"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:>

</RelativeLayout>
```

2. Implement the logic in the MainActivity class to handle button clicks and
display the string in uppercase and lowercase using toast messages
(`MainActivity.java`):

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextString;


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

editTextString = findViewById(R.id.editTextString);
}

// Method to display the string in uppercase


public void displayUpperCase(View view) {
String inputString = editTextString.getText().toString();
if (!inputString.isEmpty()) {
String upperCaseString = inputString.toUpperCase();
showToast(upperCaseString);
} else {
showToast("Please enter a string");
}
}

// Method to display the string in lowercase


public void displayLowerCase(View view) {
String inputString = editTextString.getText().toString();
if (!inputString.isEmpty()) {
String lowerCaseString = inputString.toLowerCase();
showToast(lowerCaseString);
} else {
showToast("Please enter a string");
}
}

// Method to display toast message


private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Q.2] Create table Car (id, name, type, color). Create Java Android
Application for performing the following operation on the table. (Using
SQLite database) i) Insert 5 New Car Details.
ii) Show All the Car Details
[20 Marks]
To create a Java Android application for performing operations on the Car table
in an SQLite database, you can follow these steps:

1. Set up the SQLite database with a Car table containing columns for id, name,
type, and color.

2. Define layout for the activity (`activity_main.xml`), including buttons to


insert new car details and show all car details.

3. Implement logic in the MainActivity class to handle button clicks, insert new
car details, and display all car details.

Here's the step-by-step implementation:

### 1. SQLite Database Setup

Create a SQLiteOpenHelper class to manage the database creation and version


management, and define the Car table structure:

```java
public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "car_database";


private static final int DATABASE_VERSION = 1;

// Table name and column names


private static final String TABLE_CAR = "Car";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_TYPE = "type";
private static final String COLUMN_COLOR = "color";

// SQL statement to create the Car table


private static final String CREATE_CAR_TABLE = "CREATE TABLE " +
TABLE_CAR + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_TYPE + " TEXT,"
+ COLUMN_COLOR + " TEXT"
+ ")";

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
// Create the Car table
db.execSQL(CREATE_CAR_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAR);
// Create tables again
onCreate(db);
}

// Method to add a new car


public long addCar(Car car) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, car.getName());
values.put(COLUMN_TYPE, car.getType());
values.put(COLUMN_COLOR, car.getColor());
// Insert row
long id = db.insert(TABLE_CAR, null, values);
db.close();
return id;
}

// Method to get all cars


public List<Car> getAllCars() {
List<Car> carList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_CAR;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Loop through all rows and add to list
if (cursor.moveToFirst()) {
do {
Car car = new Car();
car.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_ID)));

car.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));

car.setType(cursor.getString(cursor.getColumnIndex(COLUMN_TYPE)));

car.setColor(cursor.getString(cursor.getColumnIndex(COLUMN_COLOR)));
carList.add(car);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return carList;
}
}
```

### 2. Car Model Class

Create a Car class to represent a car entity:

```java
public class Car {

private int id;


private String name;
private String type;
private String color;

// Getters and setters


public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getType() {


return type;
}

public void setType(String type) {


this.type = type;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}
}
```

### 3. MainActivity Implementation

Implement the MainActivity class to handle button clicks, insert new car details,
and display all car details:

```java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private DatabaseHelper databaseHelper;

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

databaseHelper = new DatabaseHelper(this);


}

// Method to insert 5 new car details


public void insertCarDetails(View view) {
for (int i = 0; i < 5; i++) {
Car car = new Car();
car.setName("Car " + (i + 1));
car.setType("Type " + (i + 1));
car.setColor("Color " + (i + 1));
long id = databaseHelper.addCar(car);
if (id != -1) {
showToast("Car details inserted successfully!");
} else {
showToast("Failed to insert car details!");
}
}
}

// Method to show all car details


public void showAllCarDetails(View view) {
List<Car> carList = databaseHelper.getAllCars();
StringBuilder stringBuilder = new StringBuilder();
for (Car car : carList) {
stringBuilder.append("ID: ").append(car.getId()).append(", ")
.append("Name: ").append(car.getName()).append(", ")
.append("Type: ").append(car.getType()).append(", ")
.append("Color: ").append(car.getColor()).append("\n");
}
showToast(stringBuilder.toString());
}

// Method to display toast message


private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
```

### 4. Layout XML (activity_main.xml)

```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/buttonInsertCarDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Car Details"
android:layout_centerHorizontal="true"
android:>

<Button
android:id="@+id/buttonShowAllCarDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show All Car Details"
android:layout_below="@id/buttonInsertCarDetails"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:>

</RelativeLayout>

Q.3] Viva. [5 Marks]


Slip 25
Q.1] Create an android application for SMS activity.
[10 Marks]

### 1. Layout XML (activity_main.xml)

```xml

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp"

tools:context=".MainActivity">

<EditText

android:id="@+id/editTextPhoneNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Phone Number"

android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/editTextPhoneNumber"

android:layout_marginTop="16dp"

android:hint="Enter Message" />

<Button

android:id="@+id/buttonSendSMS"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/editTextMessage"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:text="Send SMS"

android: />

</RelativeLayout>

```

### 2. MainActivity Implementation


Implement the MainActivity class to handle sending SMS messages:

```java

import android.Manifest;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.support.v4.app.ActivityCompat;

import android.support.v7.app.AppCompatActivity;

import android.telephony.SmsManager;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText editTextPhoneNumber;

private EditText editTextMessage;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize EditText fields

editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);

editTextMessage = findViewById(R.id.editTextMessage);

// Method to send SMS message

public void sendSMS(View view) {

String phoneNumber = editTextPhoneNumber.getText().toString();

String message = editTextMessage.getText().toString();

// Check for SMS permission

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)

!= PackageManager.PERMISSION_GRANTED) {

// Request permission if not granted

ActivityCompat.requestPermissions(this,

new String[]{Manifest.permission.SEND_SMS}, 1);

return;

try {
// Send SMS message

SmsManager smsManager = SmsManager.getDefault();

smsManager.sendTextMessage(phoneNumber, null, message, null, null);

showToast("SMS sent successfully!");

} catch (Exception e) {

showToast("Failed to send SMS: " + e.getMessage());

e.printStackTrace();

// Method to display toast message

private void showToast(String message) {

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

Q.2] Create an Android application, which show Login Form in table


layout. After clicking LOGIN button display the “Login Successful…”
message if username and password is same else display “Invalid Login”
message in Toast Control.
[20 Marks]
Refer to slip 14 Q2

Q.3] Viva. [5 Marks]

You might also like