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:
[Link] 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"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />
</[Link]>
Step 3: Modify [Link]
Now, modify the [Link] to handle the logic of taking user input and displaying the
greeting message.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Find references to the EditText, Button, and TextView
EditText nameEditText = findViewById([Link]);
Button greetButton = findViewById([Link]);
TextView greetingTextView = findViewById([Link]);
// Set an onClickListener on the greetButton
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Get the name entered by the user
String name = [Link]().toString();
// If the name is not empty, update the TextView with the greeting message
if (![Link]()) {
[Link]("Hello, " + name + "!");
} else {
[Link]("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"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />
</[Link]>
3. Modify the MainActivity ([Link])
Now, open [Link] 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 [Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Get references to UI elements
EditText nameEditText = findViewById([Link]);
Button okButton = findViewById([Link]);
TextView greetingTextView = findViewById([Link]);
// Set an OnClickListener on the OK button
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Get the text entered by the user in the EditText
String name = [Link]().toString();
// If the name is not empty, update the greeting message
if (![Link]()) {
[Link]("Hello, " + name + "!");
} else {
// If no name is entered, display a default greeting
[Link]("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"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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" />
</[Link]>
3. Modify the MainActivity ([Link])
Now, open [Link] 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 [Link]:
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Get references to UI elements
EditText nameEditText = findViewById([Link]);
Button okButton = findViewById([Link]);
TextView greetingTextView =
findViewById([Link]);
// Set an OnClickListener on the OK button
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Get the text entered by the user in the EditText
String name = [Link]().toString();
// If the name is not empty, update the greeting
message
if (![Link]()) {
[Link]("Hello, " + name + "!");
} else {
// If no name is entered, display a default
greeting
[Link]("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!".
[Link] 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="[Link]
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="[Link]
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="[Link]
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. [Link]
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Get references to the UI elements
EditText username = findViewById([Link]);
EditText password = findViewById([Link]);
EditText address = findViewById([Link]);
EditText age = findViewById([Link]);
DatePicker dob = findViewById([Link]);
RadioGroup genderGroup = findViewById([Link]);
Spinner stateSpinner = findViewById([Link]);
TextView displayData = findViewById([Link]);
Button submitButton = findViewById([Link]);
// Set up state spinner with example data
ArrayAdapter<CharSequence> adapter =
[Link](this,
[Link], [Link].simple_spinner_item);
[Link]([Link].simple_spinner_dropdo
wn_item);
[Link](adapter);
// OnSubmit button click
[Link](new [Link]() {
@Override
public void onClick(View v) {
// Get user input
String usernameText = [Link]().toString();
String passwordText = [Link]().toString();
String addressText = [Link]().toString();
String ageText = [Link]().toString();
int selectedGenderId =
[Link]();
RadioButton selectedGender =
findViewById(selectedGenderId);
String genderText = selectedGender != null ?
[Link]().toString() : "Not selected";
String dobText = [Link]() + "/" +
([Link]() + 1) + "/" + [Link]();
String stateText =
[Link]().toString();
// Display data in TextView
[Link]("User Name: " + usernameText +
"\n" +
"Password: " + passwordText + "\n" +
"Address: " + addressText + "\n" +
"Age: " + ageText + "\n" +
"Gender: " + genderText + "\n" +
"Date of Birth: " + dobText + "\n" +
"State: " + stateText);
});
}
}
[Link] 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="[Link]
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 ([Link])
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 = [Link]([Link].fragment_list,
container, false);
ListView listView = [Link]([Link]);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(getActivity(), [Link].simple_list_item_1,
names);
[Link](adapter);
[Link]((parent, view1, position,
id) -> {
String selectedName = names[position];
DetailsFragment detailsFragment =
[Link](selectedName);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
// Portrait mode: Start new activity or replace
fragment
getActivity().getSupportFragmentManager().beginTransaction()
.replace([Link].fragment_container,
detailsFragment)
.addToBackStack(null)
.commit();
} else {
// Landscape mode: Replace the fragment directly
getActivity().getSupportFragmentManager().beginTransaction()
.replace([Link].fragment_container,
detailsFragment)
.commit();
}
});
return view;
}
}
4. DetailsFragment ([Link])
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();
[Link](ARG_NAME, name);
[Link](args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
if (getArguments() != null) {
name = getArguments().getString(ARG_NAME);
}
View view = [Link]([Link].fragment_details,
container, false);
TextView nameTextView =
[Link]([Link]);
Button backButton = [Link]([Link]);
[Link]("Name: " + name);
// Handle back button in portrait mode
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
[Link]([Link]);
[Link](v ->
getActivity().getSupportFragmentManager().popBackStack());
} else {
[Link]([Link]);
}
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="[Link]
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="[Link]
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 [Link] to Handle Fragments
In [Link], we handle fragment transactions and rotation events.
java
Copy code
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
// Portrait: Display ListFragment
getSupportFragmentManager().beginTransaction()
.replace([Link].fragment_container, new
ListFragment())
.commit();
} else {
// Landscape: Display both ListFragment and
DetailsFragment
getSupportFragmentManager().beginTransaction()
.replace([Link].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.
.
[Link] 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="[Link]
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="[Link]
<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 [Link]
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].menu_main, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link].dial_number:
dialNumber();
return true;
case [Link].open_website:
openWebsite();
return true;
case [Link].send_sms:
sendSMS();
return true;
default:
return [Link](item);
private void dialNumber() {
Intent dialIntent = new Intent(Intent.ACTION_DIAL,
[Link]("[Link]
startActivity(dialIntent);
private void openWebsite() {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
[Link]("[Link]
startActivity(webIntent);
private void sendSMS() {
Intent smsIntent = new Intent(Intent.ACTION_VIEW,
[Link]("[Link]
[Link]("sms_body", "Hello!");
startActivity(smsIntent);
5. Permissions ([Link])
xml
Copy code
<uses-permission android:name="[Link].SEND_SMS" />
How It Works:
● Dial a Number: Opens the dialer with a preset number (1234567890).
● Open Website: Opens the specified website ([Link]
● Send SMS: Opens the SMS app with a preset message to the specified number.
[Link] 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="[Link]
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. [Link]
Ensure no special permissions are required for notifications, but here's the basic manifest structure.
xml
Copy code
<manifest xmlns:android="[Link]
package="[Link]">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/[Link]">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category
android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
3. [Link]
Create the notification and show the toast when the button is clicked.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "example_channel";
private NotificationManager notificationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
// Create Notification Channel (Android 8.0+)
if ([Link].SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(CHANNEL_ID, "Example Channel",
NotificationManager.IMPORTANCE_DEFAULT);
[Link](channel);
}
Button btnNotify = findViewById([Link]);
[Link](v -> sendNotification());
}
private void sendNotification() {
Notification notification = new [Link](this,
CHANNEL_ID)
.setContentTitle("New Notification")
.setContentText("This is a sample notification.")
.setSmallIcon([Link].ic_dialog_info)
.build();
// Show Notification
[Link](1, notification);
// Show Toast with Notification details
[Link](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.
[Link] 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="[Link]
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 ([Link]) in assets folder
txt
Copy code
john_doe password123
jane_smith 1234abcd
3. [Link]
Handles reading the text file, verifying credentials, and showing a dialog.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private EditText edtUsername, edtPassword;
private Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
edtUsername = findViewById([Link]);
edtPassword = findViewById([Link]);
btnLogin = findViewById([Link]);
[Link](v -> {
String username = [Link]().toString();
String password = [Link]().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("[Link]")));
String line;
while ((line = [Link]()) != null) {
String[] credentials = [Link]("\t");
if (credentials[0].equals(username) &&
credentials[1].equals(password)) {
[Link]();
return true;
}
}
[Link]();
} catch (IOException e) {
[Link]();
}
return false;
}
private void showDialog(String title, String message) {
new [Link](this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", null)
.show();
}
}
Key Points:
● The verifyCredentials() method reads the [Link] 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.
[Link] 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 [Link] class to handle database operations.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
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) {
[Link](TABLE_CREATE);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
[Link]("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="[Link]
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 [Link]
In [Link], handle the user registration logic.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private EditText edtName, edtEmail, edtPassword;
private Button btnRegister;
private DatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
edtName = findViewById([Link]);
edtEmail = findViewById([Link]);
edtPassword = findViewById([Link]);
btnRegister = findViewById([Link]);
dbHelper = new DatabaseHelper(this);
[Link](v -> {
String name = [Link]().toString();
String email = [Link]().toString();
String password = [Link]().toString();
if ([Link]() || [Link]() ||
[Link]()) {
[Link]([Link], "Please fill all
fields", Toast.LENGTH_SHORT).show();
} else {
registerUser(name, email, password);
});
private void registerUser(String name, String email, String
password) {
SQLiteDatabase db = [Link]();
String insertQuery = "INSERT INTO " +
DatabaseHelper.TABLE_USERS +
" (" + DatabaseHelper.COLUMN_NAME + ", " +
DatabaseHelper.COLUMN_EMAIL + ", " + DatabaseHelper.COLUMN_PASSWORD +
") " +
"VALUES ('" + name + "', '" + email + "', '" +
password + "')";
[Link](insertQuery);
[Link](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.
[Link] 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 [Link];
import [Link];
import [Link];
import [Link];
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) {
[Link](TABLE_CREATE);
// Insert initial data
[Link]("INSERT INTO " + TABLE_USERS + " (" +
COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ") VALUES ('user1',
'pass1')");
[Link]("INSERT INTO " + TABLE_USERS + " (" +
COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ") VALUES ('user2',
'pass2')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
[Link]("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="[Link]
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 ([Link])
Handle login verification by checking the entered credentials against the database.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private EditText edtUsername, edtPassword;
private Button btnLogin;
private DatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
edtUsername = findViewById([Link]);
edtPassword = findViewById([Link]);
btnLogin = findViewById([Link]);
dbHelper = new DatabaseHelper(this);
[Link](v -> {
String username = [Link]().toString();
String password = [Link]().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 = [Link]();
String query = "SELECT * FROM " + DatabaseHelper.TABLE_USERS
+ " WHERE " +
DatabaseHelper.COLUMN_USERNAME + "=? AND " +
DatabaseHelper.COLUMN_PASSWORD + "=?";
Cursor cursor = [Link](query, new String[]{username,
password});
if ([Link]()) {
[Link]();
return true;
} else {
[Link]();
return false;
}
}
private void showDialog(String title, String message) {
new [Link](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.