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

codes

The document provides various examples of Android app development, including displaying paired Bluetooth devices, controlling Bluetooth functionality, converting temperatures, and creating layouts using LinearLayout, FrameLayout, GridView, and TableLayout. It includes XML layout files and Java code snippets for each example, along with explanations of key components and attributes. The document serves as a beginner-friendly guide for building simple Android applications.

Uploaded by

esla4517
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

codes

The document provides various examples of Android app development, including displaying paired Bluetooth devices, controlling Bluetooth functionality, converting temperatures, and creating layouts using LinearLayout, FrameLayout, GridView, and TableLayout. It includes XML layout files and Java code snippets for each example, along with explanations of key components and attributes. The document serves as a beginner-friendly guide for building simple Android applications.

Uploaded by

esla4517
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Here’s a much simpler and shorter version of the Java code for displaying

paired Bluetooth devices in an Android app.

1. Permissions in AndroidManifest.xml:

xml

CopyEdit

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

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

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

2. Simple activity_main.xml:

xml

CopyEdit

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

<ListView

android:id="@+id/pairingListView"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

</LinearLayout>

3. Simplified MainActivity.java:

java

CopyEdit

package com.example.bluetoothdevices;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.os.Bundle;
import android.widget.ArrayAdapter;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Set;

public class MainActivity extends AppCompatActivity {

BluetoothAdapter mBluetoothAdapter;

ListView mListView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mListView = findViewById(R.id.pairingListView);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {

Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1);

for (BluetoothDevice device : pairedDevices) {

adapter.add(device.getName() + "\n" + device.getAddress());

mListView.setAdapter(adapter);

Here’s a simple example for turning Bluetooth ON and OFF in an Android


application using the BluetoothAdapter class. I'll provide both the Java
code and the necessary permission tags.

1. Permissions in AndroidManifest.xml:

In your AndroidManifest.xml, you need to add the following permissions to


allow the app to use Bluetooth features.

xml

CopyEdit

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

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

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

 BLUETOOTH: Grants access to Bluetooth features.

 BLUETOOTH_ADMIN: Allows enabling and disabling Bluetooth.

 ACCESS_FINE_LOCATION: Required for Bluetooth scanning on


devices with Android 6.0 and above.

2. Activity Layout activity_main.xml:

In your layout file, you need two buttons to turn on and turn off
Bluetooth.

xml

CopyEdit

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

android:gravity="center">

<Button

android:id="@+id/btnTurnOn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Turn ON Bluetooth"

android:layout_marginBottom="20dp"/>

<Button

android:id="@+id/btnTurnOff"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Turn OFF Bluetooth"/>

</LinearLayout>

Explanation:

 Button 1 (btnTurnOn): Turns on Bluetooth.

 Button 2 (btnTurnOff): Turns off Bluetooth.

3. Java Code in MainActivity.java:

Here’s the code that controls the Bluetooth functionality.

java

CopyEdit

package com.example.bluetoothcontrol;

import android.bluetooth.BluetoothAdapter;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

BluetoothAdapter mBluetoothAdapter;

@Override

protected void onCreate(Bundle savedInstanceState) {

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

// Initialize BluetoothAdapter

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Check if Bluetooth is supported

if (mBluetoothAdapter == null) {

Toast.makeText(this, "Bluetooth is not supported on this device.",


Toast.LENGTH_SHORT).show();

return;

// Button to Turn ON Bluetooth

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

btnTurnOn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (!mBluetoothAdapter.isEnabled()) {

mBluetoothAdapter.enable(); // Turn Bluetooth ON

Toast.makeText(MainActivity.this, "Bluetooth is now ON",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "Bluetooth is already ON",


Toast.LENGTH_SHORT).show();

});

// Button to Turn OFF Bluetooth

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

btnTurnOff.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable(); // Turn Bluetooth OFF

Toast.makeText(MainActivity.this, "Bluetooth is now OFF",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "Bluetooth is already OFF",


Toast.LENGTH_SHORT).show();

});

Here's a beginner-friendly Android app to convert temperature between


Celsius and Fahrenheit using a ToggleButton.

You will get:

 XML layout file (UI)

 Java code (MainActivity.java)

 Explanation of each part

✅ Converts:

 Celsius to Fahrenheit when toggle is ON

 Fahrenheit to Celsius when toggle is OFF

🔹 Step 1: XML Layout (res/layout/activity_main.xml)

xml

CopyEdit

<?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="24dp"

android:gravity="center">

<EditText

android:id="@+id/temperatureInput"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Temperature"

android:inputType="numberDecimal" />

<ToggleButton

android:id="@+id/toggleConvert"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textOff="F to C"

android:textOn="C to F"

android:layout_marginTop="16dp"/>

<Button

android:id="@+id/convertButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Convert"

android:layout_marginTop="16dp"/>

<TextView

android:id="@+id/resultText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Result: "

android:textSize="18sp"

android:layout_marginTop="16dp"/>

</LinearLayout>
🔹 Step 2: Java Code (MainActivity.java)

java

CopyEdit

package com.example.temperatureconverter;

import android.os.Bundle;

import android.view.View;

import android.widget.*;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText temperatureInput;

ToggleButton toggleConvert;

Button convertButton;

TextView resultText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

temperatureInput = findViewById(R.id.temperatureInput);

toggleConvert = findViewById(R.id.toggleConvert);

convertButton = findViewById(R.id.convertButton);

resultText = findViewById(R.id.resultText);

convertButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String input = temperatureInput.getText().toString();


if (input.isEmpty()) {

resultText.setText("Please enter a value.");

return;

double temp = Double.parseDouble(input);

double result;

if (toggleConvert.isChecked()) {

// Celsius to Fahrenheit

result = (temp * 9 / 5) + 32;

resultText.setText("Result: " + result + " °F");

} else {

// Fahrenheit to Celsius

result = (temp - 32) * 5 / 9;

resultText.setText("Result: " + result + " °C");

});

🌼 1. LinearLayout

This arranges its child views in a single direction — either vertically or


horizontally.

🔹 Main properties:

 android:orientation="vertical" or "horizontal"

 Child views appear one after the other in the specified direction.

🔹 Example:

xml

CopyEdit

<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:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Enter Name" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit" />

</LinearLayout>

✅ What this does:

 Displays TextView → EditText → Button in a vertical column.

 Easy to read and arrange one element after another.

🌼 2. FrameLayout

This is used to stack views on top of each other. Only one view is visible at
a time usually, and the others are hidden or behind.

🔹 Main idea:

 Think of it like placing items on top of each other.

 Used often for fragment containers, splash screens, image overlays.

🔹 Example:

xml

CopyEdit

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"

android:layout_height="match_parent">

<ImageView

android:layout_width="match_parent"

android:layout_height="match_parent"

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

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Welcome!"

android:textSize="24sp"

android:textColor="#FFFFFF"

android:layout_gravity="center"/>

</FrameLayout>

✅ What this does:

 Shows a full-screen image.

 Displays a TextView on top of the image at the center.

💠 What is GridView?

GridView is a layout that displays items in a two-dimensional, scrollable


grid. It’s often used to display images, icons, or items in rows and columns
— like a gallery.

🧩 Key Attributes of GridView:

Attribute Description

android:numColumns Number of columns to display (e.g. 2, 3,


Attribute Description

auto_fit)

android:horizontalSpa
Space between columns
cing

android:verticalSpacin
Space between rows
g

android:stretchMode Defines how columns fill the space

android:gravity Aligns items in the grid

android:columnWidth Sets fixed width for columns

📱 Example: Display a grid of country flags or item names

🔹 Step 1: XML layout (res/layout/activity_main.xml)

xml

CopyEdit

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

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

android:id="@+id/gridView"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:numColumns="2"

android:verticalSpacing="10dp"

android:horizontalSpacing="10dp"

android:gravity="center"

android:columnWidth="100dp"

android:stretchMode="columnWidth"/>

🔹 Step 2: Java Code (MainActivity.java)

java

CopyEdit

package com.example.gridviewexample;

import android.os.Bundle;

import android.widget.ArrayAdapter;
import android.widget.GridView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

GridView gridView;

String[] items = {"India", "USA", "Japan", "France", "Brazil", "UK"};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

gridView = findViewById(R.id.gridView);

ArrayAdapter<String> adapter = new ArrayAdapter<>(

this,

android.R.layout.simple_list_item_1,

items

);

gridView.setAdapter(adapter);

🎨 What is Property Animation?

Property Animation is a powerful animation system introduced in Android


that lets you animate any property of a View object — like size, position,
rotation, color, transparency, etc.

📌 Common Methods Used:

 ObjectAnimator.ofFloat()

 ObjectAnimator.ofInt()
 AnimatorSet (to combine multiple animations)

 setDuration(), start(), etc.

🧾 Step 1: activity_main.xml (Design layout)

xml

CopyEdit

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

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:layout_centerInParent="true"/>

</RelativeLayout>

🧾 Step 2: MainActivity.java (Java code)

java

CopyEdit

package com.example.animationdemo;

import android.animation.ObjectAnimator;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


Button myButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

myButton = findViewById(R.id.myButton);

myButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Move button 200 pixels to the right

ObjectAnimator animator = ObjectAnimator.ofFloat(myButton,


"translationX", 200f);

animator.setDuration(1000); // 1 second

animator.start();

});

✅ What this does:

 When you click the button, it slides 200 pixels to the right smoothly
in 1 second.

 Super basic: just one line to animate it.

🎯 Goal: A basic login screen with username, password fields, and a login
button using TableLayout.

📄 1. XML File: activity_main.xml


Paste this inside res/layout/activity_main.xml:

xml

CopyEdit

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

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

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:padding="24dp"

android:stretchColumns="1">

<!-- Username Row -->

<TableRow>

<TextView

android:text="Username:"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

android:id="@+id/editTextUsername"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Username" />

</TableRow>

<!-- Password Row -->

<TableRow>

<TextView

android:text="Password:"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

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

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Password"

android:inputType="textPassword" />

</TableRow>

<!-- Login Button Row -->

<TableRow>

<View

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1" />

<Button

android:id="@+id/buttonLogin"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Login" />

</TableRow>

</TableLayout>

🧠 What This Layout Does:

 Puts each label and input in a separate row.

 Username and password go in column 1.

 The login button is right-aligned in the last row.

 It’s clean, symmetrical, and easy to understand.

💻 2. Java Code (optional): MainActivity.java

You can add this to handle the login click:

java

CopyEdit
package com.example.loginpage;

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 {

EditText editTextUsername, editTextPassword;

Button buttonLogin;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editTextUsername = findViewById(R.id.editTextUsername);

editTextPassword = findViewById(R.id.editTextPassword);

buttonLogin = findViewById(R.id.buttonLogin);

buttonLogin.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

String user = editTextUsername.getText().toString();

String pass = editTextPassword.getText().toString();

if (user.equals("admin") && pass.equals("1234")) {

Toast.makeText(MainActivity.this, "Login Successful!",


Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(MainActivity.this, "Invalid Credentials",
Toast.LENGTH_SHORT).show();

});

📘 b) List UI Components in Android:

Some common UI components in Android are:

 TextView – displays text

 EditText – takes user input

 Button – clickable action button

 ImageView – displays images

 CheckBox – toggles true/false

 RadioButton – for single selection in a group

 Spinner – dropdown list

 ListView – displays a scrollable list

 RecyclerView – advanced version of ListView

 ProgressBar – shows loading progress

📌 Now let’s explain one:

🟡 Component: Button

A Button lets the user perform an action when tapped or clicked.

🔸 Example: Show a Toast when Button is clicked

1️⃣ XML (res/layout/activity_main.xml):

xml

CopyEdit

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


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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center"

android:padding="20dp">

<Button

android:id="@+id/buttonClick"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me!" />

</LinearLayout>

2️⃣ Java (MainActivity.java):

java

CopyEdit

package com.example.uicomponent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

Button buttonClick;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
buttonClick = findViewById(R.id.buttonClick);

buttonClick.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Toast.makeText(MainActivity.this, "Button Clicked!",


Toast.LENGTH_SHORT).show();

});

✅ Output:
When the user taps the “Click Me!” button, a Toast message pops up
saying “Button Clicked!”

What is RelativeLayout?

RelativeLayout is a type of layout that lets you position UI components


relative to each other. You can align elements to the left, right, top,
bottom, or center relative to other elements or the parent container.

 Relative positioning: Elements are placed based on their


relationships with other UI elements.

 Common Attributes:

o android:layout_alignParentTop: Aligns the view to the top of


the parent.

o android:layout_alignParentLeft: Aligns the view to the left of


the parent.

o android:layout_below: Places a view below another view.

Example: A Simple Login Form using RelativeLayout


Let's create a simple login screen where the TextViews and EditTexts
are aligned relative to each other and the parent layout.

1. XML (activity_main.xml)

xml

CopyEdit

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

<!-- Username -->

<TextView

android:id="@+id/usernameLabel"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Username:"

android:layout_alignParentTop="true" />

<!-- Username Input -->

<EditText

android:id="@+id/usernameField"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/usernameLabel"

android:hint="Enter Username" />

<!-- Password -->

<TextView

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

android:layout_height="wrap_content"

android:text="Password:"

android:layout_below="@id/usernameField"

android:layout_marginTop="16dp" />

<!-- Password Input -->

<EditText

android:id="@+id/passwordField"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/passwordLabel"

android:hint="Enter Password"

android:inputType="textPassword" />

<!-- Login Button -->

<Button

android:id="@+id/loginButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Login"

android:layout_below="@id/passwordField"

android:layout_marginTop="16dp" />

</RelativeLayout>

What is ScrollView in Android?


A ScrollView is a layout container that allows users to scroll through a
large amount of content when it doesn't fit on the screen. It’s particularly
useful when you have a long list of items or forms that extend beyond the
screen's view.

 Vertical scrolling: ScrollView only supports vertical scrolling (one-


directional).

 It can contain only one child view, but that child can be any layout
or view that supports multiple elements (like LinearLayout or
RelativeLayout).

Attributes of ScrollView:

 android:layout_width: Defines the width of the ScrollView.

 android:layout_height: Defines the height of the ScrollView.

 android:fillViewport: When set to true, this makes the ScrollView fill


the entire screen (important when you want the content to stretch
and fill the available space).

 android:scrollbars: You can customize the scrollbar's appearance


(e.g., vertical or none).

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:fillViewport="true">

<!-- LinearLayout to hold multiple views inside the ScrollView -->

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:padding="16dp">

<!-- Name Label -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Full Name:" />


<!-- Name Input -->

<EditText

android:id="@+id/nameField"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Full Name" />

<!-- Email Label -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Email:" />

<!-- Email Input -->

<EditText

android:id="@+id/emailField"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Email" />

<!-- Phone Number Label -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Phone Number:" />

<!-- Phone Number Input -->

<EditText

android:id="@+id/phoneField"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter Phone Number"


android:inputType="phone" />

<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:layout_gravity="center_horizontal"

android:layout_marginTop="20dp" />

</LinearLayout>

</ScrollView>

What is a Fragment in Android?

A Fragment is a reusable portion of the user interface (UI) in an Android


application. It represents a single screen or part of a screen within an
activity. A fragment can be thought of as a modular section of an activity,
which can be independently added, removed, or replaced.

Fragments are used to create flexible and dynamic UIs, especially for
devices with varying screen sizes (e.g., phones and tablets). You can
combine multiple fragments within a single activity to create a more
dynamic UI, enabling better user experience.

Key Features of Fragments:

 Modularity: Fragments allow you to split your UI into separate


components.

 Reusability: You can reuse fragments across different activities.

 Separation of Concerns: Fragments allow better separation


between the UI and the functionality.

 Lifecycle Management: Fragments have their own lifecycle, which


is tied to the lifecycle of the activity that hosts them.

Fragment Lifecycle:
Fragments have their own lifecycle methods, which are similar to the
activity lifecycle but with some additional methods specific to fragments:

 onCreate()

 onCreateView()

 onStart()

 onResume()

 onPause()

 onStop()

 onDestroy()

1. Main Activity Layout (activity_main.xml)

In this layout, we will add a Fragment directly inside the LinearLayout.

xml

CopyEdit

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center">

<!-- Fragment container -->

<fragment

android:id="@+id/myFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:name="com.example.myapp.MyFragment" />

</LinearLayout>

2. Fragment Layout (fragment_my.xml)

Here is the layout for the fragment, where it displays a simple message
using a TextView.
xml

CopyEdit

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@android:color/holo_blue_light">

<!-- TextView inside Fragment -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:gravity="center"

android:text="Hello, This is Fragment!"

android:textSize="30sp"

android:textColor="@android:color/white" />

</FrameLayout>

1. XML Layout (activity_main.xml)

This layout contains RadioButtons and a Button to show the selected


option.

xml

CopyEdit

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center">
<!-- Radio Buttons to select an option -->

<RadioButton

android:id="@+id/radioButton1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 1" />

<RadioButton

android:id="@+id/radioButton2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 2" />

<RadioButton

android:id="@+id/radioButton3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 3" />

<!-- Button to show the selected option -->

<Button

android:id="@+id/btnShowSelection"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Selection" />

<!-- TextView to display the selected option -->

<TextView

android:id="@+id/tvSelectedOption"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Selected Option will appear here"

android:textSize="18sp" />
</LinearLayout>

2. Java Code (MainActivity.java)

Here’s the Java code to handle the selection and display the result.

java

CopyEdit

package com.example.radiobuttonexample;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.RadioButton;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// Declare the views

RadioButton radioButton1, radioButton2, radioButton3;

Button btnShowSelection;

TextView tvSelectedOption;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the views

radioButton1 = findViewById(R.id.radioButton1);

radioButton2 = findViewById(R.id.radioButton2);

radioButton3 = findViewById(R.id.radioButton3);

btnShowSelection = findViewById(R.id.btnShowSelection);

tvSelectedOption = findViewById(R.id.tvSelectedOption);
// Set button click listener

btnShowSelection.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Check which radio button is selected and display the text

if (radioButton1.isChecked()) {

tvSelectedOption.setText("Selected: Option 1");

} else if (radioButton2.isChecked()) {

tvSelectedOption.setText("Selected: Option 2");

} else if (radioButton3.isChecked()) {

tvSelectedOption.setText("Selected: Option 3");

} else {

tvSelectedOption.setText("No option selected");

});

Customized Permissions – Easy Steps

1) App Signing:

 Every Android app must be signed.

 The signature helps Android know who made the app.

 You can use your own certificate (self-signed).

2) Signature Permissions (Android 12+):

 Android 12 lets apps get special permissions based on who signed


them.

 You don’t need to sign the app during phone manufacturing.

 Just mention trusted signatures in your app, and Android will check
them.

3) App User ID and Data Access:


 When you install an app, Android gives it a unique ID (UID).

 This keeps app data private.

 To protect certain features, you can create your own permission like
this:

For example, an app that needs to control which other apps can
start one of its activities can declare a permission for this
operation as follows:

<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" > <permission
android:name="com.example.myapp.permission.DEADLY_ACTIVIT
Y" android:label="@string/permlab_deadlyActivity"
android:description="@string/permdesc_deadlyActivity"
android:permissionGroup="android.permission-
group.COST_MONEY" android:protectionLevel="dangerous" /> ...
</manifest>

a) Design a employee registration form using UI component.


activity_main.xml

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

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView

android:text="Employee Registration Form"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"
android:id="@+id/textView"

android:gravity="center"

android:textSize="20dp"

android:textColor="#000000"/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="ID"

android:id="@+id/editid"

android:layout_below="@+id/textView"/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="Name"

android:id="@+id/editname"

android:layout_below="@+id/editid"/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="Mobile No."

android:id="@+id/editmobile"

android:layout_below="@+id/editname"/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="Address"

android:lines="3"

android:id="@+id/editaddress"

android:layout_below="@+id/editmobile"/>

<EditText

android:layout_width="fill_parent"
android:hint="Pin Code"

android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>

<Button

android:text="Submit Details"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_below="@+id/editpincode"

android:layout_centerHorizontal="true"

android:id="@+id/button" />

</RelativeLayout>

c) Design a student registration form.XML Layout


(activity_main.xml):

xml

CopyEdit

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

<!-- Student Name EditText -->

<EditText

android:id="@+id/edtName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Name"/>

<!-- Email EditText -->

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

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Email"/>

<!-- Submit Button -->

<Button

android:id="@+id/btnSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"/>

</LinearLayout>

Java Code (MainActivity.java):

java

CopyEdit

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 {

EditText edtName, edtEmail;

Button btnSubmit;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize UI components
edtName = findViewById(R.id.edtName);

edtEmail = findViewById(R.id.edtEmail);

btnSubmit = findViewById(R.id.btnSubmit);

// Handle Submit Button Click

btnSubmit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

// Get values entered by user

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

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

// Show entered data in Toast

Toast.makeText(MainActivity.this, "Name: " + name + "\nEmail: "


+ email, Toast.LENGTH_LONG).show();

});

Here's a simple implementation of a ListView that displays 6 items in an


Android app. This example will use a basic array to display data in the
list.

Step 1: Create the XML layout for the activity.

activity_main.xml

xml

CopyEdit

<?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 to display the list of items -->

<ListView

android:id="@+id/listView"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

</LinearLayout>

Step 2: Create the Java code for MainActivity.

MainActivity.java

java

CopyEdit

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ListView listView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the ListView

listView = findViewById(R.id.listView);

// Create an array of items to display in the ListView

String[] items = {

"Item 1",

"Item 2",

"Item 3",
"Item 4",

"Item 5",

"Item 6"

};

// Create an ArrayAdapter to bind the data to the ListView

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1, items);

// Set the adapter for the ListView

listView.setAdapter(adapter);

program to display the list of sensors available on the device:

Java Code (MainActivity.java):

java

CopyEdit

package com.example.sensordisplay;

import android.hardware.Sensor;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize SensorManager

SensorManager sensorManager = (SensorManager)


getSystemService(SENSOR_SERVICE);

// Get the list of sensors

List<Sensor> sensorList =
sensorManager.getSensorList(Sensor.TYPE_ALL);

// Set up ListView to display sensors

ListView listView = findViewById(R.id.sensorListView);

ArrayAdapter<Sensor> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_list_item_1, sensorList);

listView.setAdapter(adapter);

Explanation:

1. SensorManager sensorManager = (SensorManager)


getSystemService(SENSOR_SERVICE);: This line gets access to
the SensorManager, which is used to interact with sensors.

2. sensorManager.getSensorList(Sensor.TYPE_ALL);: This gets a


list of all available sensors on the device.

3. ArrayAdapter<Sensor>: This adapter converts the list of sensors


into a simple list view format for display.

4. ListView: Displays the list of sensors in a scrollable list.

XML Layout (activity_main.xml):

xml

CopyEdit

<?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 to show the sensors -->

<ListView

android:id="@+id/sensorListView"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

</LinearLayout>

Text-to-Speech (TTS) in Android:

Text-to-Speech (TTS) is a feature that converts written text into spoken


words. In Android, this is done using the TextToSpeech class. When you
provide a string (text), the system converts it to audible speech, making it
useful for accessibility features or any application that requires voice
output.

Steps to Implement Text-to-Speech:

1. Create the TextToSpeech object: You initialize the TextToSpeech


engine.

2. Set the language: You can set the language for the speech, for
example, English.

3. Convert Text to Speech: Once the text and language are set, you
can trigger the speech conversion.

1. Add Text-to-Speech in your app

2. Create a Button: When clicked, it will speak the word "Thanks".

1. Java Code (MainActivity.java):

java

CopyEdit

package com.example.texttospeechdemo;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;

import android.speech.tts.TextToSpeech.OnInitListener;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements


OnInitListener {

private TextToSpeech textToSpeech;

private Button speakButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize Text-to-Speech engine

textToSpeech = new TextToSpeech(this, this);

// Find the button by its ID

speakButton = findViewById(R.id.speakButton);

// Set the button click listener to speak text

speakButton.setOnClickListener(v -> textToSpeech.speak("Thanks",


TextToSpeech.QUEUE_FLUSH, null, null));

@Override

public void onInit(int status) {

// Check if initialization is successful

if (status == TextToSpeech.SUCCESS) {

// Set language to US English


textToSpeech.setLanguage(Locale.US);

@Override

protected void onDestroy() {

// Clean up when the activity is destroyed

if (textToSpeech != null) {

textToSpeech.stop();

textToSpeech.shutdown();

super.onDestroy();

2. XML Layout (activity_main.xml):

xml

CopyEdit

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center"

android:padding="16dp">

<!-- Text that will be converted to speech -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Thanks"

android:textSize="30sp"

android:textStyle="bold"/>
<!-- Button to trigger text-to-speech -->

<Button

android:id="@+id/speakButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click to Speak"

android:textSize="18sp"/>

</LinearLayout>

Explanation:

 TextToSpeech object: This is used to convert text to speech.

 Button click listener: When the button is clicked, the app speaks
the text "Thanks".

 Language Setup: The language is set to English (Locale.US).

 Clean up: In onDestroy(), the TextToSpeech object is stopped and


cleaned up to prevent memory leaks.

a) Develop android application to enter one number and display factorial


of a number once click on button.

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

<RelativeLayout
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:layout_width="wrap_content"

android:layout_height=" wrap_content "

android:hint="Enter a number"

android:id="@+id/number"
android:inputType="number"

android:textSize="30dp"

/>

<Button

android:layout_width=" wrap_content "

android:layout_height="wrap_content"

android:id="@+id/btn1"

android:layout_below="@id/number"

android:textSize="20dp"

android:text="Calculate Factorial"

/>

<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:id="@+id/tv"
android:layout_below="@id/btn1"
android:textSize="20dp"/>
</RelativeLayout>
MainActivity.java
package com.example.factorial;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText number;
Button btn1;
TextView tv;
int num;
int factor;
String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number=(EditText)findViewById(R.id.number);
btn1=(Button)findViewById(R.id.btn1);

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

btn1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String strnum;
strnum = number.getText().toString();

num = Integer.parseInt(strnum);

factorial(num);

});

private void factorial(int num) {

int i = 1;

factor = i;

while (i <= num) {

factor = factor * i;

i++;

s = ”Factorial of Number is : ”+ factor;

tv.setText(s);

Develop the android application for student marksheets using table layout
atleast five subject marks with total and percentage (Write both Java and
xml code)1. Java Code (MainActivity.java):

java

CopyEdit

package com.example.marksheetapp;

import android.os.Bundle;

import android.view.View;
import android.widget.Button;

import android.widget.EditText;

import android.widget.TableRow;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText subject1, subject2, subject3, subject4, subject5;

Button calculateButton;

TextView totalText, percentageText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the UI elements

subject1 = findViewById(R.id.subject1);

subject2 = findViewById(R.id.subject2);

subject3 = findViewById(R.id.subject3);

subject4 = findViewById(R.id.subject4);

subject5 = findViewById(R.id.subject5);

calculateButton = findViewById(R.id.calculateButton);

totalText = findViewById(R.id.totalText);

percentageText = findViewById(R.id.percentageText);

// Set onClickListener for the Calculate button

calculateButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get marks from EditText fields

int marks1 = Integer.parseInt(subject1.getText().toString());


int marks2 = Integer.parseInt(subject2.getText().toString());

int marks3 = Integer.parseInt(subject3.getText().toString());

int marks4 = Integer.parseInt(subject4.getText().toString());

int marks5 = Integer.parseInt(subject5.getText().toString());

// Calculate total and percentage

int total = marks1 + marks2 + marks3 + marks4 + marks5;

float percentage = (total / 500.0f) * 100;

// Display total and percentage

totalText.setText("Total: " + total);

percentageText.setText("Percentage: " + String.format("%.2f",


percentage) + "%");

});

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

android:gravity="center">

<!-- Title of the Application -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Student Marksheet"

android:textSize="20sp"

android:layout_marginBottom="20dp"
android:gravity="center"/>

<!-- Table Layout to arrange marks and results -->

<TableLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

<!-- Row for Subject 1 -->

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subject 1:"/>

<EditText

android:id="@+id/subject1"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:inputType="number"

android:hint="Marks"/>

</TableRow>

<!-- Row for Subject 2 -->

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subject 2:"/>

<EditText

android:id="@+id/subject2"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"
android:inputType="number"

android:hint="Marks"/>

</TableRow>

<!-- Row for Subject 3 -->

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subject 3:"/>

<EditText

android:id="@+id/subject3"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:inputType="number"

android:hint="Marks"/>

</TableRow>

<!-- Row for Subject 4 -->

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subject 4:"/>

<EditText

android:id="@+id/subject4"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:inputType="number"

android:hint="Marks"/>

</TableRow>
<!-- Row for Subject 5 -->

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Subject 5:"/>

<EditText

android:id="@+id/subject5"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:inputType="number"

android:hint="Marks"/>

</TableRow>

</TableLayout>

<!-- Button to Calculate Total and Percentage -->

<Button

android:id="@+id/calculateButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Calculate"/>

<!-- Text Views to Display Total and Percentage -->

<TextView

android:id="@+id/totalText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Total: "/>

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

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Percentage: "/>

</LinearLayout>

Write a program to show five checkboxes and total selected checkboxes


using linear layout.

1. XML Layout (res/layout/activity_main.xml)

xml

CopyEdit

<?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="20dp">

<CheckBox

android:id="@+id/checkbox1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 1" />

<CheckBox

android:id="@+id/checkbox2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 2" />


<CheckBox

android:id="@+id/checkbox3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 3" />

<CheckBox

android:id="@+id/checkbox4"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 4" />

<CheckBox

android:id="@+id/checkbox5"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Option 5" />

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Count" />

<TextView

android:id="@+id/resultText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Selected count will appear here"

android:layout_marginTop="10dp"/>

</LinearLayout>

2. Java Code (MainActivity.java)


java

CopyEdit

import android.os.Bundle;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

CheckBox c1, c2, c3, c4, c5;

Button button;

TextView resultText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

c1 = findViewById(R.id.checkbox1);

c2 = findViewById(R.id.checkbox2);

c3 = findViewById(R.id.checkbox3);

c4 = findViewById(R.id.checkbox4);

c5 = findViewById(R.id.checkbox5);

button = findViewById(R.id.button);

resultText = findViewById(R.id.resultText);

button.setOnClickListener(v -> {

int count = 0;

if (c1.isChecked()) count++;

if (c2.isChecked()) count++;

if (c3.isChecked()) count++;

if (c4.isChecked()) count++;
if (c5.isChecked()) count++;

resultText.setText("You selected " + count + " options.");

});

Develop an android application for taking student feedback with


database
connectivity.

Ans activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Feedback Form" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll No."

android:id="@+id/editrollno"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Class"
android:id="@+id/editclass"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your Feedback"
android:lines="3"
android:id="@+id/editfeedback"/>
<Button
android:text="Submit Feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
</LinearLayout>
MapsActivity.java
package com.example.feedback;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
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;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabaseObj;
Button submitBtn;
EditText std_name, std_rollno, std_class, std_feedback;
String sname, srollno, sclass, sfeedback, sql_query;
@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button)findViewById(R.id.button);
std_name = (EditText)findViewById(R.id.editname);
std_rollno = (EditText)findViewById(R.id.editrollno);
std_class = (EditText)findViewById(R.id.editclass);
std_class = (EditText)findViewById(R.id.editfeedback);
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("FeedbaseDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS
Student(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name
VARCHAR, rollno VARCHAR, class VARCHAR, feedback VARCHAR);");
sname = std_name.getText().toString();
srollno = std_rollno.getText().toString() ;
sclass = std_class.getText().toString();
sfeedback = std_class.getText().toString();
sql_query = "INSERT INTO Student (name, rollno, class, feedback)
VALUES('"+sname+"', '"+srollno+"', '"+sclass+"', '"+sfeedback+"')";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Feedback Submitted
Successfully", Toast.LENGTH_LONG).show();
}
});
}
}

You might also like