0% found this document useful (0 votes)
218 views

Android Application Development Lab 2024-25

Uploaded by

pkjangid0025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
218 views

Android Application Development Lab 2024-25

Uploaded by

pkjangid0025
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Android Application Development

LAB MANUAL

Department of Computer Science & Engineering


Session 2024-2025

SHRI JAGDISHPRASAD JHABARMAL TIBREWALA UNIVERSITY


Vidya Nagari, Jhunjhunu-Churu Road, Village-Chudela, Dist.-Jhunjhunu, Rajasthan
333010
Conducted by-Shri Rajasthani Seva Sangh (Mumbai)

Faculty Name: Student Name:


Roll No.:
Semester:
Batch:
1.a.Create an Android application that shows Hello + name of the user and run it on an emulator.

Step-by-Step Guide to Create the Android App:

Step 1: Set Up a New Project

1. Open Android Studio and select "Create New Project."


2. Choose the "Empty Activity" template and click Next.
3. Enter the name of your application (e.g., HelloUserApp).
4. Select a language as Java or Kotlin (I’ll use Java for this guide).
5. Set the Minimum API level (e.g., API 21: Android 5.0 (Lollipop)).
6. Click Finish to create the project.

Step 2: Modify activity_main.xml

This XML file defines the user interface. Open res/layout/activity_main.xml and modify it to
include an EditText for entering the user's name and a TextView to display the greeting message.

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

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

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

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<EditText

android:id="@+id/nameEditText"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:layout_marginTop="100dp"
android:padding="16dp"

android:inputType="text"

android:textSize="18sp"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/>

<Button

android:id="@+id/greetButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Greet Me"

android:layout_marginTop="30dp"

app:layout_constraintTop_toBottomOf="@id/nameEditText"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<TextView

android:id="@+id/greetingTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello!"

android:textSize="24sp"

android:layout_marginTop="50dp"
app:layout_constraintTop_toBottomOf="@id/greetButton"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Modify MainActivity.java

Now, modify the MainActivity.java to handle the logic of taking user input and displaying the
greeting message.

package com.example.hellouserapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Find references to the EditText, Button, and TextView

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

Button greetButton = findViewById(R.id.greetButton);

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

// Set an onClickListener on the greetButton

greetButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get the name entered by the user

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

// If the name is not empty, update the TextView with the greeting message

if (!name.isEmpty()) {

greetingTextView.setText("Hello, " + name + "!");

} else {

greetingTextView.setText("Hello!");

});

Step 4: Run the Application on the Emulator


1. Build the Application: Click the Build button or go to Build > Make Project.
2. Set Up Emulator:
○ If you don't have an emulator set up, go to Tools > AVD Manager and create a new
virtual device (e.g., Pixel 5).
○ Select the device and click the Play button to start the emulator.
3. Run the Application: Click the Run button (green triangle) or press Shift + F10 to run the app
on the emulator.

Step 5: Interact with the Application

Once the app is running on the emulator, follow these steps:

1. The user will be prompted to enter their name in the EditText field.
2. When the user clicks the Greet Me button, the greeting message will appear below the button
with the text: "Hello, [user's name]!"

If the user doesn't enter a name, the message will remain as "Hello!".

(b) Create an application that takes the name from a text box and shows hello message along
with the name entered in text box, when the user clicks the OK button

To create an Android application that takes the name from a text box and displays a "Hello" message with
the entered name when the user clicks the "OK" button, you can follow these steps:

1. Set up a New Project


1. Open Android Studio.
2. Choose "Create New Project".
3. Select "Empty Activity" and click Next.
4. Name your project (e.g., HelloNameApp).
5. Choose Java as the programming language.
6. Set the Minimum API level (for this example, you can use API 21: Android 5.0 Lollipop).
7. Click Finish.

2. Modify the Layout (activity_main.xml)

In this file, we will define the user interface, which includes:

● An EditText to take input (the user's name).


● A Button that the user will click to display the greeting message.
● A TextView to display the "Hello" message with the user's name.

Open res/layout/activity_main.xml and replace the content with the following:

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

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

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

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<!-- EditText for user input -->

<EditText

android:id="@+id/nameEditText"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="Enter your name"


android:layout_marginTop="100dp"

android:padding="16dp"

android:textSize="18sp"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<!-- Button to show greeting -->

<Button

android:id="@+id/okButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="OK"

android:layout_marginTop="30dp"

app:layout_constraintTop_toBottomOf="@id/nameEditText"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<!-- TextView to display greeting message -->

<TextView

android:id="@+id/greetingTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello!"
android:textSize="24sp"

android:layout_marginTop="50dp"

app:layout_constraintTop_toBottomOf="@id/okButton"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Modify the MainActivity (MainActivity.java)

Now, open MainActivity.java and add the logic for handling user input and displaying the greeting
message. You’ll need to get the name from the EditText, and when the user clicks the OK button, the
app will update the TextView to say "Hello, [name]".

Here’s the code for MainActivity.java:

package com.example.hellonameapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Get references to UI elements

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

Button okButton = findViewById(R.id.okButton);

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

// Set an OnClickListener on the OK button

okButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get the text entered by the user in the EditText

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

// If the name is not empty, update the greeting message

if (!name.isEmpty()) {

greetingTextView.setText("Hello, " + name + "!");

} else {

// If no name is entered, display a default greeting

greetingTextView.setText("Hello!");

}
});

To create an Android application that takes the name from a text box and displays a "Hello" message with
the entered name when the user clicks the "OK" button, you can follow these steps:

1. Set up a New Project

1. Open Android Studio.


2. Choose "Create New Project".
3. Select "Empty Activity" and click Next.
4. Name your project (e.g., HelloNameApp).
5. Choose Java as the programming language.
6. Set the Minimum API level (for this example, you can use API 21: Android 5.0 Lollipop).
7. Click Finish.

2. Modify the Layout (activity_main.xml)

In this file, we will define the user interface, which includes:

● An EditText to take input (the user's name).


● A Button that the user will click to display the greeting message.
● A TextView to display the "Hello" message with the user's name.

Open res/layout/activity_main.xml and replace the content with the following:

xml

Copy code

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

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

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

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

tools:context=".MainActivity">

<!-- EditText for user input -->

<EditText

android:id="@+id/nameEditText"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:layout_marginTop="100dp"

android:padding="16dp"

android:textSize="18sp"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<!-- Button to show greeting -->

<Button

android:id="@+id/okButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="OK"

android:layout_marginTop="30dp"
app:layout_constraintTop_toBottomOf="@id/nameEditText"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

<!-- TextView to display greeting message -->

<TextView

android:id="@+id/greetingTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello!"

android:textSize="24sp"

android:layout_marginTop="50dp"

app:layout_constraintTop_toBottomOf="@id/okButton"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Modify the MainActivity (MainActivity.java)

Now, open MainActivity.java and add the logic for handling user input and displaying the greeting
message. You’ll need to get the name from the EditText, and when the user clicks the OK button, the
app will update the TextView to say "Hello, [name]".

Here’s the code for MainActivity.java:

java
Copy code

package com.example.hellonameapp;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Get references to UI elements

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

Button okButton = findViewById(R.id.okButton);

TextView greetingTextView =
findViewById(R.id.greetingTextView);
// Set an OnClickListener on the OK button

okButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get the text entered by the user in the EditText

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

// If the name is not empty, update the greeting


message

if (!name.isEmpty()) {

greetingTextView.setText("Hello, " + name + "!");

} else {

// If no name is entered, display a default


greeting

greetingTextView.setText("Hello!");

});

4. Run the Application

1. Build the Application: In Android Studio, click Build > Make Project to ensure there are no
errors.
2. Set up an Emulator (if you don't have a real device):
○ Go to Tools > AVD Manager (Android Virtual Device Manager) and create a new virtual
device.
○ Select a device, then choose the Android version (system image) you want to use.
○ After the emulator is created, click the Play button to launch the emulator.
3. Run the App: Click the Run button (green triangle) or press Shift + F10 to run the app.
4. Test the App:
○ Enter a name in the EditText field.
○ Tap the OK button to see the greeting message displayed below, like "Hello, [name]".

5. What the App Does

● The user types their name in the EditText field.


● When the user presses the OK button, the app displays a greeting in the TextView that says
"Hello, [name]", where [name] is the text entered by the user. If the user doesn't enter any text,
it will display just "Hello!".

Q.2.Create a screen that has input boxes for User Name, Password, Address, Gender (radio buttons
for male and female), Age (numeric), Date of Birth (Date Picket), State (Spinner) and a Submit
button. On clicking the submit button, print all the data below the Submit Button. Use (a) Linear
Layout , (b) Relative Layout and (c) Grid Layout or Table Layout.

To create a screen that includes input boxes for User Name, Password, Address, Gender (radio buttons for
Male and Female), Age (numeric), Date of Birth (Date Picker), State (Spinner), and a Submit button, we'll
create three versions of the same layout using different types of layouts: LinearLayout, RelativeLayout,
and GridLayout or TableLayout.

1. Using LinearLayout

In this layout, all the components are stacked vertically. We'll use LinearLayout with vertical
orientation for this purpose.

activity_main.xml (LinearLayout)

xml

Copy code

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


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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<!-- User Name -->

<EditText

android:id="@+id/username"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="User Name"

android:inputType="text" />

<!-- Password -->

<EditText

android:id="@+id/password"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Password"

android:inputType="textPassword" />
<!-- Address -->

<EditText

android:id="@+id/address"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Address"

android:inputType="text" />

<!-- Gender (Radio buttons) -->

<RadioGroup

android:id="@+id/genderGroup"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

<RadioButton

android:id="@+id/maleRadio"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Male" />

<RadioButton

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

android:layout_height="wrap_content"

android:text="Female" />

</RadioGroup>

<!-- Age -->

<EditText

android:id="@+id/age"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Age"

android:inputType="number" />

<!-- Date of Birth -->

<DatePicker

android:id="@+id/dob"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<!-- State Spinner -->

<Spinner

android:id="@+id/stateSpinner"

android:layout_width="match_parent"
android:layout_height="wrap_content" />

<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Submit" />

<!-- Display Submitted Data -->

<TextView

android:id="@+id/displayData"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Submitted data will appear here"

android:textSize="16sp"

android:layout_marginTop="16dp" />

</LinearLayout>

2. Using RelativeLayout

In this layout, elements are positioned relative to each other using RelativeLayout. This allows for
more flexible positioning of UI elements.
activity_main.xml (RelativeLayout)

xml

Copy code

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<!-- User Name -->

<EditText

android:id="@+id/username"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="User Name"

android:inputType="text"

android:layout_alignParentTop="true" />

<!-- Password -->

<EditText

android:id="@+id/password"

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

android:hint="Password"

android:inputType="textPassword"

android:layout_below="@id/username"

android:layout_marginTop="16dp" />

<!-- Address -->

<EditText

android:id="@+id/address"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Address"

android:inputType="text"

android:layout_below="@id/password"

android:layout_marginTop="16dp" />

<!-- Gender (Radio buttons) -->

<RadioGroup

android:id="@+id/genderGroup"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="horizontal"

android:layout_below="@id/address"
android:layout_marginTop="16dp">

<RadioButton

android:id="@+id/maleRadio"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Male" />

<RadioButton

android:id="@+id/femaleRadio"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Female" />

</RadioGroup>

<!-- Age -->

<EditText

android:id="@+id/age"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Age"

android:inputType="number"

android:layout_below="@id/genderGroup"
android:layout_marginTop="16dp" />

<!-- Date of Birth -->

<DatePicker

android:id="@+id/dob"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/age"

android:layout_marginTop="16dp" />

<!-- State Spinner -->

<Spinner

android:id="@+id/stateSpinner"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/dob"

android:layout_marginTop="16dp" />

<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

android:layout_width="match_parent"

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

android:layout_below="@id/stateSpinner"

android:layout_marginTop="16dp" />

<!-- Display Submitted Data -->

<TextView

android:id="@+id/displayData"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Submitted data will appear here"

android:textSize="16sp"

android:layout_below="@id/submitButton"

android:layout_marginTop="16dp" />

</RelativeLayout>

3. Using GridLayout or TableLayout

GridLayout or TableLayout arranges the UI elements in a grid-like fashion. I'll use a GridLayout
for this example. You could also use TableLayout in a similar way.

activity_main.xml (GridLayout)

xml

Copy code

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


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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:columnCount="2"

android:padding="16dp">

<!-- User Name -->

<TextView

android:text="User Name"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

android:id="@+id/username"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="text" />

<!-- Password -->

<TextView

android:text="Password"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

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

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="textPassword" />

<!-- Address -->

<TextView

android:text="Address"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

android:id="@+id/address"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="text" />

<!-- Gender -->

<TextView

android:text="Gender"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<RadioGroup

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

android:layout_height="wrap_content"

android:orientation="horizontal">

<RadioButton

android:id="@+id/maleRadio"

android:text="Male" />

<RadioButton

android:id="@+id/femaleRadio"

android:text="Female" />

</RadioGroup>

<!-- Age -->

<TextView

android:text="Age"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

android:id="@+id/age"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:inputType="number" />

<!-- Date of Birth -->


<TextView

android:text="Date of Birth"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<DatePicker

android:id="@+id/dob"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<!-- State Spinner -->

<TextView

android:text="State"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<Spinner

android:id="@+id/stateSpinner"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

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

android:text="Submit"

android:layout_columnSpan="2" />

<!-- Display Submitted Data -->

<TextView

android:id="@+id/displayData"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Submitted data will appear here"

android:textSize="16sp"

android:layout_columnSpan="2"

android:layout_marginTop="16dp" />

</GridLayout>

4. MainActivity.java

Now, we'll implement the logic for handling the form submission. When the Submit button is clicked, it
should collect the entered data and display it in the TextView.

java

Copy code

package com.example.formsubmission;
import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Spinner;

import android.widget.TextView;

import android.widget.DatePicker;

import android.widget.ArrayAdapter;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Get references to the UI elements

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

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


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

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

DatePicker dob = findViewById(R.id.dob);

RadioGroup genderGroup = findViewById(R.id.genderGroup);

Spinner stateSpinner = findViewById(R.id.stateSpinner);

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

Button submitButton = findViewById(R.id.submitButton);

// Set up state spinner with example data

ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this,

R.array.states, android.R.layout.simple_spinner_item);

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

stateSpinner.setAdapter(adapter);

// OnSubmit button click

submitButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get user input

String usernameText = username.getText().toString();

String passwordText = password.getText().toString();


String addressText = address.getText().toString();

String ageText = age.getText().toString();

int selectedGenderId =
genderGroup.getCheckedRadioButtonId();

RadioButton selectedGender =
findViewById(selectedGenderId);

String genderText = selectedGender != null ?


selectedGender.getText().toString() : "Not selected";

String dobText = dob.getDayOfMonth() + "/" +


(dob.getMonth() + 1) + "/" + dob.getYear();

String stateText =
stateSpinner.getSelectedItem().toString();

// Display data in TextView

displayData.setText("User Name: " + usernameText +


"\n" +

"Password: " + passwordText + "\n" +

"Address: " + addressText + "\n" +

"Age: " + ageText + "\n" +

"Gender: " + genderText + "\n" +

"Date of Birth: " + dobText + "\n" +

"State: " + stateText);

});

}
}

Q.3.Develop an application that shows names as a list and on selecting a name it should show
the details of the candidate on the next screen with a “Back” button. If the screen is rotated to
landscape mode (width greater than height), then the screen should show list on left fragment
and details on right fragment instead of second screen with back button. Use Fragment
transactions and Rotation event listener

1. Create the Project

● Open Android Studio and create a new project with an Empty Activity.
● Select Java as the language and API 21 as the minimum SDK.

2. Define Layout for activity_main.xml

In portrait mode, we show the list and details in separate screens, but in landscape, both fragments
(list and details) will be shown side by side.

xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>

3. ListFragment (ListFragment.java)

This fragment displays the list of names. When a name is selected, it triggers the display of the
details in the next screen or fragment.

java
Copy code
public class ListFragment extends Fragment {

private String[] names = {"John", "Jane", "Tom", "Alice"};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list,
container, false);
ListView listView = view.findViewById(R.id.listView);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,
names);
listView.setAdapter(adapter);

listView.setOnItemClickListener((parent, view1, position,


id) -> {
String selectedName = names[position];
DetailsFragment detailsFragment =
DetailsFragment.newInstance(selectedName);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
// Portrait mode: Start new activity or replace
fragment

getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,
detailsFragment)
.addToBackStack(null)
.commit();
} else {
// Landscape mode: Replace the fragment directly

getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,
detailsFragment)
.commit();
}
});

return view;
}
}

4. DetailsFragment (DetailsFragment.java)

This fragment shows the details of the selected name. It has a "Back" button in portrait mode.

java
Copy code
public class DetailsFragment extends Fragment {

private static final String ARG_NAME = "name";


private String name;

public static DetailsFragment newInstance(String name) {


DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putString(ARG_NAME, name);
fragment.setArguments(args);
return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
if (getArguments() != null) {
name = getArguments().getString(ARG_NAME);
}

View view = inflater.inflate(R.layout.fragment_details,


container, false);
TextView nameTextView =
view.findViewById(R.id.nameTextView);
Button backButton = view.findViewById(R.id.backButton);

nameTextView.setText("Name: " + name);

// Handle back button in portrait mode


if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
backButton.setVisibility(View.VISIBLE);
backButton.setOnClickListener(v ->
getActivity().getSupportFragmentManager().popBackStack());
} else {
backButton.setVisibility(View.GONE);
}

return view;
}
}
5. Layout for fragment_list.xml

A simple list layout for the ListFragment.

xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

6. Layout for fragment_details.xml

The layout for the DetailsFragment.

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

<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
android:textSize="20sp" />

<Button
android:id="@+id/backButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:visibility="gone"/>
</LinearLayout>

7. Modify MainActivity.java to Handle Fragments

In MainActivity.java, we handle fragment transactions and rotation events.

java
Copy code
public class MainActivity extends AppCompatActivity {

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

if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
// Portrait: Display ListFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new
ListFragment())
.commit();
} else {
// Landscape: Display both ListFragment and
DetailsFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new
ListFragment())
.commit();
// Optionally, show details fragment by default in
landscape mode
}
}
}

8. Handle Screen Rotation (Landscape Mode)

When the screen rotates to landscape, the list and details will be shown side by side. If the user
selects a name, the right fragment will update with the details.

.
Q.4.Develop an application that uses a menu with 3 options for dialing a number, opening a
website and to send an SMS. On selecting an option, the appropriate action should be invoked
using intents.

1. Create the Project

● Open Android Studio and create a new project with an Empty Activity.
● Choose Java as the language and API 21 as the minimum SDK.

2. Define Layout (activity_main.xml)

xml

Copy code

<?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">

<TextView

android:id="@+id/welcomeText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Select an option from the menu"

android:textSize="18sp"

android:layout_centerInParent="true"/>

</RelativeLayout>
3. Create Menu (res/menu/menu_main.xml)

xml

Copy code

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

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

<item android:id="@+id/dial_number" android:title="Dial a Number"


android:icon="@android:drawable/ic_menu_call"/>

<item android:id="@+id/open_website" android:title="Open Website"


android:icon="@android:drawable/ic_menu_info_details"/>

<item android:id="@+id/send_sms" android:title="Send SMS"


android:icon="@android:drawable/ic_menu_send"/>

</menu>

4. Handle Menu in MainActivity.java

java

Copy code

package com.example.intentmenu;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.telephony.SmsManager;
import android.view.Menu;

import android.view.MenuItem;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case R.id.dial_number:

dialNumber();

return true;

case R.id.open_website:

openWebsite();

return true;

case R.id.send_sms:

sendSMS();

return true;

default:

return super.onOptionsItemSelected(item);

private void dialNumber() {

Intent dialIntent = new Intent(Intent.ACTION_DIAL,


Uri.parse("tel:1234567890"));

startActivity(dialIntent);

private void openWebsite() {


Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.example.com"));

startActivity(webIntent);

private void sendSMS() {

Intent smsIntent = new Intent(Intent.ACTION_VIEW,


Uri.parse("sms:1234567890"));

smsIntent.putExtra("sms_body", "Hello!");

startActivity(smsIntent);

5. Permissions (AndroidManifest.xml)

xml

Copy code

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

How It Works:

● Dial a Number: Opens the dialer with a preset number (1234567890).


● Open Website: Opens the specified website (https://www.example.com).
● Send SMS: Opens the SMS app with a preset message to the specified number.
Q.5.Develop an application that inserts some notifications into Notification area and whenever a
notification is inserted, it should show a toast with details of the notification.

To develop an Android application that inserts notifications into the notification area and displays a
toast with the notification details when the notification is inserted, follow these steps:

1. Layout (activity_main.xml)

A simple button to trigger the notification.

xml
Copy code
<?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">

<Button
android:id="@+id/btnNotify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:layout_centerInParent="true"/>
</RelativeLayout>

2. AndroidManifest.xml

Ensure no special permissions are required for notifications, but here's the basic manifest structure.

xml
Copy code
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notifications">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.DayNight">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

3. MainActivity.java

Create the notification and show the toast when the button is clicked.

java
Copy code
package com.example.notifications;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

private static final String CHANNEL_ID = "example_channel";


private NotificationManager notificationManager;

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

notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

// Create Notification Channel (Android 8.0+)


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(CHANNEL_ID, "Example Channel",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}

Button btnNotify = findViewById(R.id.btnNotify);


btnNotify.setOnClickListener(v -> sendNotification());
}

private void sendNotification() {


Notification notification = new Notification.Builder(this,
CHANNEL_ID)
.setContentTitle("New Notification")
.setContentText("This is a sample notification.")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.build();

// Show Notification
notificationManager.notify(1, notification);

// Show Toast with Notification details


Toast.makeText(this, "Notification inserted: New
Notification", Toast.LENGTH_SHORT).show();
}
}

4. Key Points:

● Notification Channel: Created for Android 8.0+ (required for notifications).


● Notification Builder: Used to build and display the notification.
● Toast: A toast is displayed to show notification details when the button is clicked.

Q.6.Create an application that uses a text file to store user names and passwords (tab separated
fields and one record per line). When the user submits a login name and password through a
screen, the details should be verified with the text file data and if
they match, show a dialog saying that login is successful. Otherwise, show the dialog with Login
Failed message.
1. Layout (activity_main.xml)

Simple UI with username, password input, and login button.

xml
Copy code
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

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

<EditText
android:id="@+id/edtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>

2. Text File (users.txt) in assets folder


txt
Copy code
john_doe password123
jane_smith 1234abcd

3. MainActivity.java

Handles reading the text file, verifying credentials, and showing a dialog.

java
Copy code
package com.example.loginwithfile;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

private EditText edtUsername, edtPassword;


private Button btnLogin;

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

edtUsername = findViewById(R.id.edtUsername);
edtPassword = findViewById(R.id.edtPassword);
btnLogin = findViewById(R.id.btnLogin);

btnLogin.setOnClickListener(v -> {
String username = edtUsername.getText().toString();
String password = edtPassword.getText().toString();
if (verifyCredentials(username, password)) {
showDialog("Login Successful", "Welcome " +
username);
} else {
showDialog("Login Failed", "Invalid username or
password.");
}
});
}

private boolean verifyCredentials(String username, String


password) {
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(getAssets().open("users.txt")));
String line;
while ((line = reader.readLine()) != null) {
String[] credentials = line.split("\t");
if (credentials[0].equals(username) &&
credentials[1].equals(password)) {
reader.close();
return true;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

private void showDialog(String title, String message) {


new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", null)
.show();
}
}

Key Points:

● The verifyCredentials() method reads the users.txt file from the assets folder,
checks if the entered username and password match, and returns true or false.
● A dialog is displayed based on whether the credentials are correct.

Q.7.Create a user registration application that stores the user details in a database
table.

To create a user registration application that stores user details in a database table, follow these steps:

1. Project Setup

● Create a new project in Android Studio with Empty Activity.


● Choose Java as the language and set the minimum SDK.

2. Add Database Helper Class

Create a DatabaseHelper.java class to handle database operations.

java

Copy code

package com.example.registrationapp;

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 = "user_database";

private static final int DATABASE_VERSION = 1;

public static final String TABLE_USERS = "users";

public static final String COLUMN_ID = "id";

public static final String COLUMN_NAME = "name";

public static final String COLUMN_EMAIL = "email";

public static final String COLUMN_PASSWORD = "password";

private static final String TABLE_CREATE =

"CREATE TABLE " + TABLE_USERS + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_NAME + " TEXT, " +


COLUMN_EMAIL + " TEXT, " +

COLUMN_PASSWORD + " TEXT);";

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(TABLE_CREATE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int


newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);

onCreate(db);

3. Define the Layout (activity_main.xml)

Create a simple registration form with EditText fields for name, email, password, and a Button to
submit.

xml

Copy code
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<EditText

android:id="@+id/edtName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Name" />

<EditText

android:id="@+id/edtEmail"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Email"

android:inputType="textEmailAddress" />

<EditText

android:id="@+id/edtPassword"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Password"
android:inputType="textPassword" />

<Button

android:id="@+id/btnRegister"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Register" />

</LinearLayout>

4. Handle Registration in MainActivity.java

In MainActivity.java, handle the user registration logic.

java

Copy code

package com.example.registrationapp;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private EditText edtName, edtEmail, edtPassword;

private Button btnRegister;

private DatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

edtName = findViewById(R.id.edtName);

edtEmail = findViewById(R.id.edtEmail);

edtPassword = findViewById(R.id.edtPassword);

btnRegister = findViewById(R.id.btnRegister);

dbHelper = new DatabaseHelper(this);

btnRegister.setOnClickListener(v -> {

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

String email = edtEmail.getText().toString();

String password = edtPassword.getText().toString();

if (name.isEmpty() || email.isEmpty() ||
password.isEmpty()) {
Toast.makeText(MainActivity.this, "Please fill all
fields", Toast.LENGTH_SHORT).show();

} else {

registerUser(name, email, password);

});

private void registerUser(String name, String email, String


password) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

String insertQuery = "INSERT INTO " +


DatabaseHelper.TABLE_USERS +

" (" + DatabaseHelper.COLUMN_NAME + ", " +


DatabaseHelper.COLUMN_EMAIL + ", " + DatabaseHelper.COLUMN_PASSWORD +
") " +

"VALUES ('" + name + "', '" + email + "', '" +


password + "')";

db.execSQL(insertQuery);

Toast.makeText(this, "Registration Successful",


Toast.LENGTH_SHORT).show();

5. Key Points
● Database Helper: DatabaseHelper manages SQLite database operations (create, upgrade,
insert).
● Layout: Simple form with fields for name, email, and password.

Q.8.Create a database and a user table where the details of login names and passwords are
stored. Insert some names and passwords initially. Now the login details entered by the user
should be verified with the database and an appropriate dialog should be shown to the user.

Here's how to create an Android app with a database to store login details (username and password),
verify the user's input, and show an appropriate dialog based on the verification.

1. Create Database Helper Class

We create a DatabaseHelper class to manage SQLite database creation and CRUD operations.

java
Copy code
package com.example.loginapp;

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 = "user_db";


private static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD = "password";

private static final String TABLE_CREATE =


"CREATE TABLE " + TABLE_USERS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT, " +
COLUMN_PASSWORD + " TEXT);";

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
// Insert initial data
db.execSQL("INSERT INTO " + TABLE_USERS + " (" +
COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ") VALUES ('user1',
'pass1')");
db.execSQL("INSERT INTO " + TABLE_USERS + " (" +
COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ") VALUES ('user2',
'pass2')");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
onCreate(db);
}
}

2. Layout (activity_main.xml)

Create a simple login form with EditText for username and password and a Button for login.

xml
Copy code
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

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

<EditText
android:id="@+id/edtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />

</LinearLayout>

3. MainActivity Logic (MainActivity.java)


Handle login verification by checking the entered credentials against the database.

java
Copy code
package com.example.loginapp;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText edtUsername, edtPassword;


private Button btnLogin;
private DatabaseHelper dbHelper;

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

edtUsername = findViewById(R.id.edtUsername);
edtPassword = findViewById(R.id.edtPassword);
btnLogin = findViewById(R.id.btnLogin);

dbHelper = new DatabaseHelper(this);


btnLogin.setOnClickListener(v -> {
String username = edtUsername.getText().toString();
String password = edtPassword.getText().toString();

if (verifyCredentials(username, password)) {
showDialog("Login Successful", "Welcome " +
username);
} else {
showDialog("Login Failed", "Invalid username or
password.");
}
});
}

private boolean verifyCredentials(String username, String


password) {
SQLiteDatabase db = dbHelper.getReadableDatabase();

String query = "SELECT * FROM " + DatabaseHelper.TABLE_USERS


+ " WHERE " +
DatabaseHelper.COLUMN_USERNAME + "=? AND " +
DatabaseHelper.COLUMN_PASSWORD + "=?";
Cursor cursor = db.rawQuery(query, new String[]{username,
password});

if (cursor.moveToFirst()) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}

private void showDialog(String title, String message) {


new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", null)
.show();
}
}
4. Key Points

● DatabaseHelper: This class creates the SQLite database with a users table and inserts some
initial user data (user1, pass1 and user2, pass2).
● Login Verification: The verifyCredentials method checks if the entered username and
password match any record in the users table.
● Dialog: After verifying credentials, the app shows a success or failure dialog.

5. Result
● On entering correct login details, a success dialog will appear.
● On entering incorrect details, a failure dialog will appear.

You might also like