0% found this document useful (0 votes)
25 views74 pages

Andriod Practicle Easy Ansers

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)
25 views74 pages

Andriod Practicle Easy Ansers

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/ 74

create a simple application which shows life cycle of activity

import android.os.Bundle

import android.util.Log

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

logLifecycleEvent("onCreate")

override fun onStart() {

super.onStart()

logLifecycleEvent("onStart")

override fun onResume() {

super.onResume()

logLifecycleEvent("onResume")

override fun onPause() {

super.onPause()

logLifecycleEvent("onPause")

override fun onStop() {

super.onStop()

logLifecycleEvent("onStop")
}

override fun onDestroy() {

super.onDestroy()

logLifecycleEvent("onDestroy")

private fun logLifecycleEvent(eventName: String) {

Log.d("Lifecycle", "Event: $eventName")

Create a simple application which send Hello message from one activity to another with help of
Button(use Intent)
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">

<Button

android:id="@+id/btnSendMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send Hello Message"

android:layout_centerInParent="true"

android:onClick="sendMessage" />

</RelativeLayout>

Modify the MainActivity class: Open the MainActivity.kt file, and replace its
content with the following code:
import android.content.Intent

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.view.View

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

fun sendMessage(view: View) {

val intent = Intent(this, SecondActivity::class.java)

intent.putExtra("message", "Hello from MainActivity!")

startActivity(intent)

} import android.content.Intent

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.view.View

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

fun sendMessage(view: View) {

val intent = Intent(this, SecondActivity::class.java)

intent.putExtra("message", "Hello from MainActivity!")


startActivity(intent)

Create the second activity: Create a new Kotlin class named SecondActivity :

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.TextView

class SecondActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_second)

val messageTextView = findViewById<TextView>(R.id.textViewMessage)

val message = intent.getStringExtra("message")

messageTextView.text = message

Design the layout for the second activity: Open the activity_second.xml
file in the res/layout directory, and replace its content with the following XML
code:

<?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=".SecondActivity">

<TextView

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

android:layout_height="wrap_content"

android:text="Hello Message"

android:layout_centerInParent="true" />

</RelativeLayout>

Create simple application to display details of selected list item on second activity(use fragmentation)

1. Create a new Android Studio Project: Open Android Studio, click


on "Start a new Android Studio project," and choose an Empty
Activity template.
2. Design the layout for the first activity (MainActivity): Open the
activity_main.xml file in the res/layout directory, and replace its
content with the following XML code:
<?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">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/darker_gray"
android:dividerHeight="0.5dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_below="@id/textView" />

</RelativeLayout>

Modify the MainActivity class: Open the MainActivity.kt file, and replace
its content with the following code

import android.content.Intent
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {

private lateinit var listView: ListView

private val items = listOf(


ListItem(1, "Item 1", "Details for Item 1"),
ListItem(2, "Item 2", "Details for Item 2"),
// Add more items as needed
)

override fun onCreate(savedInstanceState: Bundle?) {


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

listView = findViewById(R.id.listView)
val adapter = ArrayAdapter(this,
android.R.layout.simple_list_item_1, items.map { it.title })
listView.adapter = adapter

listView.setOnItemClickListener { _, _, position, _ ->


val selectedItem = items[position]
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("selectedItem", selectedItem)
startActivity(intent)
}
}
}

Design the layout for the second activity (SecondActivity):


<?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=".SecondActivity">

<TextView
android:id="@+id/textViewDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />

</RelativeLayout>

<?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=".SecondActivity">

<TextView
android:id="@+id/textViewDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />

</RelativeLayout>

Modify the SecondActivity class:


import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class SecondActivity : AppCompatActivity() {

private lateinit var textViewDetails: TextView

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)

textViewDetails = findViewById(R.id.textViewDetails)

val selectedItem = intent.getSerializableExtra("selectedItem") as


ListItem
textViewDetails.text = "Details for ${selectedItem.title}:\n$
{selectedItem.details}"
}
}

create simple application with login screen. on successful login gives message go to
next acitivity(without using database)

Design the layout for the login screen (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">

<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

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

<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/editTextPassword"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:onClick="login"/>

</RelativeLayout>

Design the layout for the success screen (activity_success.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=".SuccessActivity">

<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login Successful!"
android:layout_centerInParent="true"/>

</RelativeLayout>

Modify the MainActivity class:


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText

class MainActivity : AppCompatActivity() {

private lateinit var editTextUsername: EditText


private lateinit var editTextPassword: EditText

override fun onCreate(savedInstanceState: Bundle?) {


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

editTextUsername = findViewById(R.id.editTextUsername)
editTextPassword = findViewById(R.id.editTextPassword)
}

fun login(view: android.view.View) {


val username = editTextUsername.text.toString()
val password = editTextPassword.text.toString()

// Hardcoded credentials for demonstration purposes


if (username == "user" && password == "password") {
val intent = Intent(this, SuccessActivity::class.java)
startActivity(intent)
}
Create the SuccessActivity class: import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

class SuccessActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_success)
}
}

create first activity to accept information like student first name, middle name
last name, date of birth, address, email ID and display all information on
seocnd acitivity when user click on submit button

Design the layout for the first activity (activity_main.xml):


<!-- res/layout/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">

<EditText
android:id="@+id/editTextFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="First Name"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<!-- Similar EditText views for Middle Name, Last Name, DOB,
Address, and Email ID -->

<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="@id/editTextEmail"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:onClick="onSubmit"/>
</RelativeLayout>

Modify the MainActivity class (MainActivity.java):


// MainActivity.java
package com.example.studentinfo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextFirstName;


private EditText editTextMiddleName;
private EditText editTextLastName;
private EditText editTextDOB;
private EditText editTextAddress;
private EditText editTextEmail;

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

editTextFirstName = findViewById(R.id.editTextFirstName);
editTextMiddleName = findViewById(R.id.editTextMiddleName);
editTextLastName = findViewById(R.id.editTextLastName);
editTextDOB = findViewById(R.id.editTextDOB);
editTextAddress = findViewById(R.id.editTextAddress);
editTextEmail = findViewById(R.id.editTextEmail);
}

public void onSubmit(View view) {


String firstName = editTextFirstName.getText().toString();
String middleName = editTextMiddleName.getText().toString();
String lastName = editTextLastName.getText().toString();
String dob = editTextDOB.getText().toString();
String address = editTextAddress.getText().toString();
String email = editTextEmail.getText().toString();

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


intent.putExtra("firstName", firstName);
intent.putExtra("middleName", middleName);
intent.putExtra("lastName", lastName);
intent.putExtra("dob", dob);
intent.putExtra("address", address);
intent.putExtra("email", email);
startActivity(intent);
}
}

Design the layout for the second activity (activity_second.xml):


<!-- res/layout/activity_second.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=".SecondActivity">

<TextView
android:id="@+id/textViewDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>

</RelativeLayout>
Modify the SecondActivity class (SecondActivity.java):
// SecondActivity.java
package com.example.studentinfo;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

private TextView textViewDetails;

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

textViewDetails = findViewById(R.id.textViewDetails);

Intent intent = getIntent();


String firstName = intent.getStringExtra("firstName");
String middleName = intent.getStringExtra("middleName");
String lastName = intent.getStringExtra("lastName");
String dob = intent.getStringExtra("dob");
String address = intent.getStringExtra("address");
String email = intent.getStringExtra("email");

String detailsText = "Student Details:\n\n" +


"First Name: " + firstName + "\n" +
"Middle Name: " + middleName + "\n" +
"Last Name: " + lastName + "\n" +
"Date of Birth: " + dob + "\n" +
"Address: " + address + "\n" +
"Email ID: " + email;

textViewDetails.setText(detailsText);
}
}

Design following screen using intents on second activity take button.


On clicking it, it should show information of profile on third acitivity.
(without using database)

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


<!-- res/layout/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">

<EditText
android:id="@+id/editTextAadharNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Aadhar Number"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextAadharNo"
android:layout_marginTop="8dp"
android:hint="Name"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<EditText
android:id="@+id/editTextDOB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:layout_marginTop="8dp"
android:hint="Date of Birth (MM/DD/YYYY)"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<EditText
android:id="@+id/editTextGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextDOB"
android:layout_marginTop="8dp"
android:hint="Gender"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<EditText
android:id="@+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextGender"
android:layout_marginTop="8dp"
android:hint="Address"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<EditText
android:id="@+id/editTextContact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextAddress"
android:layout_marginTop="8dp"
android:hint="Contact Number"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"/>

<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="@id/editTextContact"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:onClick="onSubmit"/>
</RelativeLayout>

2. Modify the MainActivity class (MainActivity.java):

// MainActivity.java
package com.example.profileapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextAadharNo;


private EditText editTextName;
private EditText editTextDOB;
private EditText editTextGender;
private EditText editTextAddress;
private EditText editTextContact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextAadharNo = findViewById(R.id.editTextAadharNo);
editTextName = findViewById(R.id.editTextName);
editTextDOB = findViewById(R.id.editTextDOB);
editTextGender = findViewById(R.id.editTextGender);
editTextAddress = findViewById(R.id.editTextAddress);
editTextContact = findViewById(R.id.editTextContact);
}

public void onSubmit(View view) {


String aadharNo = editTextAadharNo.getText().toString();
String name = editTextName.getText().toString();
String dob = editTextDOB.getText().toString();
String gender = editTextGender.getText().toString();
String address = editTextAddress.getText().toString();
String contact = editTextContact.getText().toString();

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


intent.putExtra("aadharNo", aadharNo);
intent.putExtra("name", name);
intent.putExtra("dob", dob);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
intent.putExtra("contact", contact);
startActivity(intent);
}
}
3. Design the layout for the second activity (activity_second.xml):

<!-- res/layout/activity_second.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=".SecondActivity">

<Button
android:id="@+id/btnShowProfile"
android:layout_width="wrap_content"
android:layout

design an android portrait and landscape screen layout example

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

<ImageView
android:id="@+id/weatherIcon"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_weather_sunny" />

<TextView
android:id="@+id/temperatureTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/weatherIcon"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="25°C"
android:textSize="24sp" />

<TextView
android:id="@+id/cityNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/temperatureTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="City Name"
android:textSize="18sp" />
</RelativeLayout>

<?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="horizontal"
android:padding="16dp">

<ImageView
android:id="@+id/weatherIcon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_weather_sunny" />

<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center_vertical">

<TextView
android:id="@+id/temperatureTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="25°C"
android:textSize="24sp" />

<TextView
android:id="@+id/cityNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City Name"
android:textSize="18sp" />

</LinearLayout>
</LinearLayout>

Create a simple calculator shown below also perform appropriate


operation

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="0"
android:textSize="24sp"
android:gravity="end"/>

<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/resultTextView"
android:layout_marginTop="16dp"
android:columnCount="4"
android:rowCount="5"
android:layout_marginBottom="16dp">

<!-- Buttons for digits -->


<Button
android:text="1"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="2"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="3"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="C"
android:onClick="onClearClick"
style="@style/CalculatorButton" />

<Button
android:text="4"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="5"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="6"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="/"
android:onClick="onOperatorClick"
style="@style/CalculatorButton" />

<Button
android:text="7"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />
<Button
android:text="8"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="9"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="*"
android:onClick="onOperatorClick"
style="@style/CalculatorButton" />

<Button
android:text="0"
android:layout_columnSpan="2"
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="."
android:onClick="onDigitClick"
style="@style/CalculatorButton" />

<Button
android:text="-"
android:onClick="onOperatorClick"
style="@style/CalculatorButton" />

<Button
android:text="+"
android:onClick="onOperatorClick"
style="@style/CalculatorButton" />

<Button
android:text="="
android:layout_columnSpan="2"
android:onClick="onEqualClick"
style="@style/CalculatorButton" />
</GridLayout>
</RelativeLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private TextView resultTextView;


private StringBuilder currentInput = new StringBuilder();
private String currentOperator;
private double operand1;

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

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

public void onDigitClick(View view) {


if (view instanceof Button) {
currentInput.append(((Button) view).getText());
updateResult();
}
}

public void onOperatorClick(View view) {


if (view instanceof Button) {
if (currentInput.length() > 0) {
operand1 = Double.parseDouble(currentInput.toString());
currentInput.setLength(0);
currentOperator = ((Button) view).getText().toString();
}
}
}

public void onEqualClick(View view) {


if (currentInput.length() > 0 && currentOperator != null) {
double operand2 =
Double.parseDouble(currentInput.toString());
double result = performOperation(operand1, operand2,
currentOperator);
resultTextView.setText(String.valueOf(result));
currentInput.setLength(0);
currentOperator = null;
}
}

public void onClearClick(View view) {


currentInput.setLength(0);
currentOperator = null;
updateResult();
}

private double performOperation(double operand1, double


operand2, String operator) {
switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
return operand1 / operand2;
default:
throw new IllegalArgumentException("Invalid operator");
}
}

private void updateResult() {


resultTextView.setText(currentInput.toString());
}
}

Create android app for addition of two numbers using relative layout
and peform operation

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

<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter number 1"
android:inputType="numberDecimal" />

<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber1"
android:layout_marginTop="8dp"
android:hint="Enter number 2"
android:inputType="numberDecimal" />

<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber2"
android:layout_marginTop="16dp"
android:onClick="onAddClick"
android:text="Add" />

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/addButton"
android:layout_marginTop="16dp"
android:text=""
android:textSize="18sp" />
</RelativeLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber1;


private EditText editTextNumber2;
private TextView resultTextView;

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

editTextNumber1 = findViewById(R.id.editTextNumber1);
editTextNumber2 = findViewById(R.id.editTextNumber2);
resultTextView = findViewById(R.id.resultTextView);
}

public void onAddClick(View view) {


try {
double number1 =
Double.parseDouble(editTextNumber1.getText().toString());
double number2 =
Double.parseDouble(editTextNumber2.getText().toString());
double result = number1 + number2;

resultTextView.setText(getString(R.string.result, result));
} catch (NumberFormatException e) {
resultTextView.setText(R.string.invalid_input);
}
}
}

Using scrollview create application to scroll the button in horizontal


direction

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

<ScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true">

<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
</LinearLayout>
</ScrollView>
</RelativeLayout>

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 {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Dynamically add buttons to the horizontal LinearLayout
addButtonsToScrollView();
}

private void addButtonsToScrollView() {


// Get the horizontal LinearLayout inside the ScrollView
HorizontalScrollView horizontalScrollView =
findViewById(R.id.horizontalScrollView);
LinearLayout linearLayout = findViewById(R.id.linearLayout);

// Add buttons dynamically


for (int i = 1; i <= 10; i++) {
Button button = new Button(this);
button.setText("Button " + i);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Display a toast when a button is clicked
Toast.makeText(MainActivity.this, "Button Clicked: " +
((Button) view).getText(), Toast.LENGTH_SHORT).show();
}
});

// Add the button to the LinearLayout


linearLayout.addView(button);
}
}
}

Create following layout which is changing android spinner text size with
styles

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

<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter a number"
android:inputType="numberDecimal" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber"
android:layout_marginTop="16dp"
android:orientation="vertical">

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

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

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

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

<Button
android:id="@+id/calculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/radioGroup"
android:layout_marginTop="16dp"
android:onClick="onCalculateClick"
android:text="Calculate" />

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/calculateButton"
android:layout_marginTop="16dp"
android:text=""
android:textSize="18sp" />

</RelativeLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText editTextNumber;


private RadioGroup radioGroup;
private TextView resultTextView;

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

editTextNumber = findViewById(R.id.editTextNumber);
radioGroup = findViewById(R.id.radioGroup);
resultTextView = findViewById(R.id.resultTextView);
}

public void onCalculateClick(View view) {


try {
double number =
Double.parseDouble(editTextNumber.getText().toString());
double result = performOperation(number);

// Display the result


resultTextView.setText(getString(R.string.result, result));
} catch (NumberFormatException e) {
Toast.makeText(this, R.string.invalid_input,
Toast.LENGTH_SHORT).show();
}
}

private double performOperation(double number) {


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

switch (selectedRadioButton.getText().toString()) {
case "Odd/Even":
return checkOddEven(number);
case "Positive/Negative":
return checkPositiveNegative(number);
case "Square":
return calculateSquare(number);
case "Factorial":
return calculateFactorial(number);
default:
throw new IllegalArgumentException("Invalid operation");
}
}

private double checkOddEven(double number) {


return number % 2 == 0 ? 1 : 0;
}

private double checkPositiveNegative(double number) {


return number >= 0 ? 1 : 0;
}

private double calculateSquare(double number) {


return number * number;
}

private double calculateFactorial(double number) {


if (number < 0) {
return 0; // Factorial is not defined for negative numbers
}

double factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
return factorial;
}
}

By using spinner, Buttons. Write a program to draw following GUI

Enter item
Add to spinner and remove from spinner
See response below

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

<EditText
android:id="@+id/editTextItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter item"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"/>

<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextItem"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:onClick="onAddButtonClick"
android:text="Add to Spinner"/>

<Button
android:id="@+id/removeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/addButton"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:onClick="onRemoveButtonClick"
android:text="Remove from Spinner"/>

<Spinner
android:id="@+id/spinnerItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/removeButton"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"/>

<TextView
android:id="@+id/responseTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/spinnerItems"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text=""
android:textSize="18sp"/>
</RelativeLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private EditText editTextItem;


private Spinner spinnerItems;
private Button addButton;
private Button removeButton;
private TextView responseTextView;

private List<String> itemList;

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

editTextItem = findViewById(R.id.editTextItem);
spinnerItems = findViewById(R.id.spinnerItems);
addButton = findViewById(R.id.addButton);
removeButton = findViewById(R.id.removeButton);
responseTextView = findViewById(R.id.responseTextView);

itemList = new ArrayList<>();

// Set up the spinner with an empty list


ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, itemList);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_d
ropdown_item);
spinnerItems.setAdapter(adapter);
}

public void onAddButtonClick(View view) {


String newItem = editTextItem.getText().toString().trim();

if (!newItem.isEmpty()) {
// Add the item to the list and update the spinner
itemList.add(newItem);
updateSpinner();

// Clear the input field


editTextItem.getText().clear();

// Display a response
responseTextView.setText("Item added: " + newItem);
} else {
responseTextView.setText("Please enter an item.");
}
}

public void onRemoveButtonClick(View view) {


String selectedItem = spinnerItems.getSelectedItem().toString();

if (!selectedItem.isEmpty()) {
// Remove the selected item from the list and update the
spinner
itemList.remove(selectedItem);
updateSpinner();

// Display a response
responseTextView.setText("Item removed: " + selectedItem);
} else {
responseTextView.setText("No item selected.");
}
}

private void updateSpinner() {


ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, itemList);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_d
ropdown_item);
spinnerItems.setAdapter(adapter);
}
}

Create application to demonstrate date and time picker


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

<Button
android:id="@+id/dateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Pick Date" />

<Button
android:id="@+id/timeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/dateButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Pick Time" />

</RelativeLayout>

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private Button dateButton;


private Button timeButton;

private Calendar calendar;


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

dateButton = findViewById(R.id.dateButton);
timeButton = findViewById(R.id.timeButton);

calendar = Calendar.getInstance();

dateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDatePickerDialog();
}
});

timeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTimePickerDialog();
}
});
}

private void showDatePickerDialog() {


DatePickerDialog datePickerDialog = new DatePickerDialog(
this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int
month, int day) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);

updateDateButton();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}

private void showTimePickerDialog() {


TimePickerDialog timePickerDialog = new TimePickerDialog(
this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int
minute) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);

updateTimeButton();
}
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
false
);
timePickerDialog.show();
}

private void updateDateButton() {


SimpleDateFormat dateFormat = new SimpleDateFormat("MMM
dd, yyyy", Locale.getDefault());
dateButton.setText(dateFormat.format(calendar.getTime()));
}

private void updateTimeButton() {


SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm
a", Locale.getDefault());
timeButton.setText(timeFormat.format(calendar.getTime()));
}
}

Construct an app that toggles a light bulb on and off when the user
clicks on toggle button.

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

<ImageView
android:id="@+id/lightBulbImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:src="@drawable/light_off" />

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/lightBulbImageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:textOn="Turn Off"
android:textOff="Turn On" />

</RelativeLayout>

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private ImageView lightBulbImageView;


private ToggleButton toggleButton;

private boolean isLightOn = false;

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

lightBulbImageView = findViewById(R.id.lightBulbImageView);
toggleButton = findViewById(R.id.toggleButton);

// Set initial state of the light bulb


updateLightBulbState();

toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toggle the light bulb state
isLightOn = !isLightOn;

// Update the UI to reflect the new state


updateLightBulbState();
}
});
}

private void updateLightBulbState() {


if (isLightOn) {
lightBulbImageView.setImageResource(R.drawable.light_on);
} else {
lightBulbImageView.setImageResource(R.drawable.light_off);
}
}
}

Create gallery application to display all images date wise(Use Grid


View)

res/layout/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">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="120dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:padding="8dp" />

</RelativeLayout>

res/layout/grid_item.xml:

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="120dp"
android:scaleType="centerCrop" />

</LinearLayout>

MainActivity.java:

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private static final int PERMISSION_REQUEST_CODE = 1;

private GridView gridView;


private ImageAdapter imageAdapter;
private List<String> allImages;

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

gridView = findViewById(R.id.gridView);
imageAdapter = new ImageAdapter(this);
gridView.setAdapter(imageAdapter);

if (checkPermissions()) {
loadImages();
}
}

private boolean checkPermissions() {


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]
{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
return false;
}
}
return true;
}

private void loadImages() {


allImages = getAllImages();
Map<String, List<String>> groupedImages =
groupImagesByDate(allImages);
imageAdapter.setData(groupedImages);
imageAdapter.notifyDataSetChanged();

gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String selectedImagePath = (String)
parent.getItemAtPosition(position);
// Handle image click (e.g., open in full-screen view)
Toast.makeText(MainActivity.this, "Clicked: " +
selectedImagePath, Toast.LENGTH_SHORT).show();
}
});
}

private List<String> getAllImages() {


List<String> imagePaths = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);

if (cursor != null && cursor.moveToFirst()) {


int pathColumn =
cursor.getColumnIndex(MediaStore.Images.Media.DATA);

do {
String imagePath = cursor.getString(pathColumn);
imagePaths.add(imagePath);

} while (cursor.moveToNext());

cursor.close();
}

return imagePaths;
}

private Map<String, List<String>>


groupImagesByDate(List<String> imagePaths) {
Map<String, List<String>> groupedImages = new HashMap<>();

for (String imagePath : imagePaths) {


Date date = getDateFromImagePath(imagePath);

if (date != null) {
String formattedDate = formatDate(date);

if (!groupedImages.containsKey(formattedDate)) {
groupedImages.put(formattedDate, new
ArrayList<String>());
}
groupedImages.get(formattedDate).add(imagePath);
}
}

return sortGroupedImagesByDate(groupedImages);
}

private Date getDateFromImagePath(String imagePath) {


try {
ExifDataExtractor exifDataExtractor = new ExifDataExtractor();
String dateString = exifDataExtractor.extractDate(imagePath);

if (dateString != null) {
SimpleDateFormat dateFormat = new
SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
return dateFormat.parse(dateString);
}
} catch (Exception e) {
Log.e("Error", "Error getting date from image path: " +
e.getMessage());
}
return null;
}

private String formatDate(Date date) {


SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-
MM-dd", Locale.getDefault());
return dateFormat.format(date);
}

private Map<String, List<String>>


sortGroupedImagesByDate(Map<String, List<String>>
groupedImages) {
// Sort the map by date
List<Map.Entry<String, List<String>>> sortedList = new
ArrayList<>(groupedImages.entrySet());
Collections.sort(sortedList, new Comparator<Map.Entry<String,
List<String>>>() {
@Override
public int compare(Map.Entry<String, List<String>> o1,
Map.Entry<String, List<String>> o2) {
return o2.getKey().compareTo(o1.getKey());
}
});

// Create a new map from the sorted list


Map<String, List<String>> sortedMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : sortedList) {
sortedMap.put(entry.getKey(), entry.getValue());
}

return sortedMap;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, load images
loadImages();
} else {
Toast.makeText(this, "Permission Denied",
Toast.LENGTH_SHORT).show();
}
}
}
}

ImageAdapter.java:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ImageAdapter extends BaseAdapter {

private Context context;


private Map<String, List<String>> groupedImages;
private List<String> dates;

public ImageAdapter(Context context) {


this.context = context;
this.groupedImages = new Map<>();
this.dates = new ArrayList<>();
}

public void setData(Map<String, List<String>> groupedImages) {


this.groupedImages = groupedImages;
this.dates = new ArrayList<>(groupedImages.keySet());
}

@Override
public int getCount() {
return groupedImages.size();
}

@Override
public Object getItem(int position) {
return dates.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup
parent) {
ViewHolder viewHolder;

if (convertView == null) {
convertView =
LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView =
convertView.findViewById(R.id.imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}

String date = dates.get(position);


List<String> imagePaths = groupedImages.get(date);

if (imagePaths != null && !imagePaths.isEmpty()) {


String firstImagePath = imagePaths.get(0); // Display the first
image as a thumbnail
Glide.with(context)
.load(firstImagePath)
.centerCrop()
.into(viewHolder.imageView);
}

return convertView;
}

static class ViewHolder

create registration form given below. also perform appropriate validation and display
the message using dialog fragment (name , email, password, age, mobile number)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

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

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

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

<EditText
android:id="@+id/ageEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/passwordEditText"
android:layout_marginTop="16dp"
android:hint="Age"
android:inputType="number" />

<EditText
android:id="@+id/mobileNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ageEditText"
android:layout_marginTop="16dp"
android:hint="Mobile Number"
android:inputType="phone" />

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

</RelativeLayout>

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

public class MainActivity extends AppCompatActivity {

private EditText nameEditText;


private EditText emailEditText;
private EditText passwordEditText;
private EditText ageEditText;
private EditText mobileNumberEditText;
private Button registerButton;

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

nameEditText = findViewById(R.id.nameEditText);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
ageEditText = findViewById(R.id.ageEditText);
mobileNumberEditText =
findViewById(R.id.mobileNumberEditText);
registerButton = findViewById(R.id.registerButton);

registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validateAndRegister();
}
});
}

private void validateAndRegister() {


String name = nameEditText.getText().toString().trim();
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
String ageStr = ageEditText.getText().toString().trim();
String mobileNumber =
mobileNumberEditText.getText().toString().trim();

if (TextUtils.isEmpty(name) || TextUtils.isEmpty(email) ||
TextUtils.isEmpty(password)
|| TextUtils.isEmpty(ageStr) ||
TextUtils.isEmpty(mobileNumber)) {
showErrorDialog("Please fill in all fields");
} else if (!isValidEmail(email)) {
showErrorDialog("Invalid email address");
} else if (password.length() < 6) {
showErrorDialog("Password must be at least 6 characters");
} else if (!isValidAge(ageStr)) {
showErrorDialog("Invalid age");
} else if (!isValidMobileNumber(mobileNumber)) {
showErrorDialog("Invalid mobile number");
} else {
// Perform registration or further actions here
showSuccessDialog("Registration successful!");
}
}

private boolean isValidEmail(CharSequence target) {


return
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

private boolean isValidAge(String ageStr) {


try {
int age = Integer.parseInt(ageStr);
return age > 0 && age < 150; // Assuming a reasonable age
range
} catch (NumberFormatException e) {
return false;
}
}

private boolean isValidMobileNumber(String mobileNumber) {


// Assuming a basic check for a valid mobile number
return mobileNumber.matches("\\d{10}");
}
private void showErrorDialog(String message) {
DialogFragment errorDialogFragment =
ErrorDialogFragment.newInstance(message);
errorDialogFragment.show(getSupportFragmentManager(),
"error_dialog");
}

private void showSuccessDialog(String message) {


DialogFragment successDialogFragment =
SuccessDialogFragment.newInstance(message);
successDialogFragment.show(getSupportFragmentManager(),
"success_dialog");
}
}

Construct a bank app to display different menuslike withdraw, deposit


etc.

<?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="wrap_content"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter deposit amount:"
android:textSize="18sp" />

<EditText
android:id="@+id/amountEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:hint="Amount" />

</LinearLayout>

MainActivity.java:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

public class MainActivity extends AppCompatActivity {

private BankAccount bankAccount;


private TextView balanceTextView;

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

// Initialize bank account with an initial balance


bankAccount = new BankAccount(1000);

balanceTextView = findViewById(R.id.balanceTextView);
updateBalanceDisplay();

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


depositButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDepositDialog();
}
});

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


withdrawButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showWithdrawDialog();
}
});
}

private void showDepositDialog() {


DepositDialogFragment depositDialog = new
DepositDialogFragment();
depositDialog.show(getSupportFragmentManager(),
"deposit_dialog");
depositDialog.setOnDepositListener(new
DepositDialogFragment.OnDepositListener() {
@Override
public void onDeposit(double amount) {
bankAccount.deposit(amount);
updateBalanceDisplay();
}
});
}

private void showWithdrawDialog() {


WithdrawDialogFragment withdrawDialog = new
WithdrawDialogFragment();
withdrawDialog.show(getSupportFragmentManager(),
"withdraw_dialog");
withdrawDialog.setOnWithdrawListener(new
WithdrawDialogFragment.OnWithdrawListener() {
@Override
public void onWithdraw(double amount) {
if (bankAccount.withdraw(amount)) {
updateBalanceDisplay();
} else {
showInsufficientFundsDialog();
}
}
});
}

private void showInsufficientFundsDialog() {


DialogFragment insufficientFundsDialog = new
InsufficientFundsDialogFragment();
insufficientFundsDialog.show(getSupportFragmentManager(),
"insufficient_funds_dialog");
}

private void updateBalanceDisplay() {


balanceTextView.setText(String.format("Balance: $%.2f",
bankAccount.getBalance()));
}
}

BankAccount.java:

public class BankAccount {

private double balance;

public BankAccount(double initialBalance) {


balance = initialBalance;
}

public double getBalance() {


return balance;
}
public void deposit(double amount) {
balance += amount;
}

public boolean withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
return true;
} else {
return false;
}
}
}

DepositDialogFragment.java:

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import androidx.fragment.app.DialogFragment;

public class DepositDialogFragment extends DialogFragment {

private OnDepositListener onDepositListener;

public interface OnDepositListener {


void onDeposit(double amount);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_deposit, null);

final EditText amountEditText =


view.findViewById(R.id.amountEditText);

builder.setView(view)
.setTitle("Deposit")
.setPositiveButton("Deposit", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String amountString =
amountEditText.getText().toString();
if (!amountString.isEmpty()) {
double amount =
Double.parseDouble(amountString);
onDepositListener.onDeposit(amount);
}
}
})
.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

return builder.create();
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
onDepositListener = (OnDepositListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must
implement OnDepositListener");
}
}
}

create table company(id, name, address, phno). Create application for performing
the following operation on the table. 1. insert new company Details. 2.show all the
company details.

res/layout/activity_main.xml:

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Company Details:"
android:textSize="18sp" />

<Button
android:id="@+id/insertButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/resultTextView"
android:layout_marginTop="16dp"
android:text="Insert New Company" />

</RelativeLayout>

CompanyModel.java:

public class CompanyModel {


private int id;
private String name;
private String address;
private String phoneNumber;

// Constructors, getters, and setters...

// Default constructor
public CompanyModel() {
}

// Parameterized constructor
public CompanyModel(String name, String address, String
phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}

// Getters and setters...


}

DatabaseHelper.java:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "company_database";


private static final int DATABASE_VERSION = 1;

// Company table
private static final String TABLE_COMPANY = "company";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_ADDRESS = "address";
private static final String KEY_PHONE_NUMBER = "phno";

private static final String CREATE_TABLE_COMPANY =


"CREATE TABLE " + TABLE_COMPANY + "(" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_NAME + " TEXT," +
KEY_ADDRESS + " TEXT," +
KEY_PHONE_NUMBER + " TEXT" +
")";

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_COMPANY);
}

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

CompanyDataSource.java:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class CompanyDataSource {

private SQLiteDatabase database;


private DatabaseHelper dbHelper;

public CompanyDataSource(Context context) {


dbHelper = new DatabaseHelper(context);
}

public void open() throws SQLException {


database = dbHelper.getWritableDatabase();
}

public void close() {


dbHelper.close();
}

public long insertCompany(CompanyModel company) {


ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_NAME, company.getName());
values.put(DatabaseHelper.KEY_ADDRESS,
company.getAddress());
values.put(DatabaseHelper.KEY_PHONE_NUMBER,
company.getPhoneNumber());

return database.insert(DatabaseHelper.TABLE_COMPANY, null,


values);
}

public List<CompanyModel> getAllCompanies() {


List<CompanyModel> companies = new ArrayList<>();

String[] allColumns = {
DatabaseHelper.KEY_ID,
DatabaseHelper.KEY_NAME,
DatabaseHelper.KEY_ADDRESS,
DatabaseHelper.KEY_PHONE_NUMBER
};

Cursor cursor = database.query(


DatabaseHelper.TABLE_COMPANY,
allColumns,
null,
null,
null,
null,
null
);

if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
CompanyModel company = cursorToCompany(cursor);
companies.add(company);
cursor.moveToNext();
}
cursor.close();
}

return companies;
}

private CompanyModel cursorToCompany(Cursor cursor) {


CompanyModel company = new CompanyModel();

company.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.K
EY_ID)));

company.setName(cursor.getString(cursor.getColumnIndex(DatabaseH
elper.KEY_NAME)));

company.setAddress(cursor.getString(cursor.getColumnIndex(Databas
eHelper.KEY_ADDRESS)));

company.setPhoneNumber(cursor.getString(cursor.getColumnIndex(Da
tabaseHelper.KEY_PHONE_NUMBER)));
return company;
}
}

MainActivity.java:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;
public class MainActivity extends AppCompatActivity {

private CompanyDataSource dataSource;


private TextView resultTextView;

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

dataSource = new CompanyDataSource(this);


dataSource.open();

resultTextView = findViewById(R.id.resultTextView);

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


insertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertCompany();
displayCompanies();
}
});

displayCompanies();
}

private void insertCompany() {


CompanyModel company = new CompanyModel("ABC Corp", "123
Main St", "555-1234");
dataSource.insertCompany(company);
}

private void displayCompanies() {


List<CompanyModel> companies =
dataSource.getAllCompanies();
StringBuilder result = new StringBuilder();

for (CompanyModel company : companies) {


result.append("ID: ").append(company.getId())
.append(", Name: ").append(company.getName())
.append(", Address: ").append(company.getAddress())
.append(", Phone: ").append(company.getPhoneNumber())
.append("\n");
}

resultTextView.setText(result.toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
dataSource.close();
}
}

Create tale student(sno,s_name,s_class,a_addr)


Teacher (tno, t_name,qualification,experience)
Student-teacher has manay to many relationship. Using above
database write application to accept a teacher name from user and
display the names of students along with subjects to whom teacher is
teaching.

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

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"

TeachingRelationship.java:

public class TeachingRelationship {


private int sno;
private int tno;

// Constructors, getters, and setters...

public TeachingRelationship() {
}

public TeachingRelationship(int sno, int tno) {


this.sno = sno;
this.tno = tno;
}

// Getters and setters...


}

DatabaseHelper.java:

public class DatabaseHelper extends SQLiteOpenHelper {

// ...

// TeachingRelationship table
private static final String TABLE_TEACHING_RELATIONSHIP =
"teaching_relationship";
private static final String KEY_SNO = "sno";
private static final String KEY_TNO = "tno";

private static final String CREATE_TABLE_TEACHING_RELATIONSHIP


=
"CREATE TABLE " + TABLE_TEACHING_RELATIONSHIP + "(" +
KEY_SNO + " INTEGER," +
KEY_TNO + " INTEGER," +
"PRIMARY KEY (" + KEY_SNO + ", " + KEY_TNO + ")," +
"FOREIGN KEY (" + KEY_SNO + ") REFERENCES " +
TABLE_STUDENT + "(" + KEY_SNO + ")," +
"FOREIGN KEY (" + KEY_TNO + ") REFERENCES " +
TABLE_TEACHER + "(" + KEY_TNO + ")" +
")";

// ...
}

TeachingRelationshipDataSource.java:

public class TeachingRelationshipDataSource {

private SQLiteDatabase database;


private DatabaseHelper dbHelper;

// ...

public long insertTeachingRelationship(TeachingRelationship


relationship) {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_SNO, relationship.getSno());
values.put(DatabaseHelper.KEY_TNO, relationship.getTno());
return
database.insert(DatabaseHelper.TABLE_TEACHING_RELATIONSHIP, null,
values);
}

public List<StudentModel> getStudentsByTeacherName(String


teacherName) {
List<StudentModel> students = new ArrayList<>();

String query = "SELECT " +


DatabaseHelper.TABLE_STUDENT + "." +
DatabaseHelper.KEY_SNO + ", " +
DatabaseHelper.TABLE_STUDENT + "." +
DatabaseHelper.KEY_NAME +
" FROM " +
DatabaseHelper.TABLE_STUDENT + ", " +
DatabaseHelper.TABLE_TEACHER + ", " +
DatabaseHelper.TABLE_TEACHING_RELATIONSHIP +
" WHERE " +
DatabaseHelper.TABLE_TEACHER + "." +
DatabaseHelper.KEY_TNO + " = " +
DatabaseHelper.TABLE_TEACHING_RELATIONSHIP + "." +
DatabaseHelper.KEY_TNO +
" AND " +
DatabaseHelper.TABLE_STUDENT + "." +
DatabaseHelper.KEY_SNO + " = " +
DatabaseHelper.TABLE_TEACHING_RELATIONSHIP + "." +
DatabaseHelper.KEY_SNO +
" AND " +
DatabaseHelper.TABLE_TEACHER + "." +
DatabaseHelper.KEY_NAME + " = '" + teacherName + "'";

Cursor cursor = database.rawQuery(query, null);

if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
StudentModel student = cursorToStudent(cursor);
students.add(student);
cursor.moveToNext();
}
cursor.close();
}

return students;
}

// ...
}
MainActivity.java:

public class MainActivity extends AppCompatActivity {

private TeachingRelationshipDataSource relationshipDataSource;


private StudentDataSource studentDataSource;

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

relationshipDataSource = new
TeachingRelationshipDataSource(this);
relationshipDataSource.open();

studentDataSource = new StudentDataSource(this);


studentDataSource.open();

// Assume you have a button or input field to get teacher's name


from the user
// For simplicity, let's assume the teacher's name is obtained and
stored in a variable called 'teacherName'

String teacherName = "John Doe"; // Replace this with the actual


teacher's name

List<StudentModel> students =
relationshipDataSource.getStudentsByTeacherName(teacherName);

StringBuilder result = new StringBuilder("Students taught by " +


teacherName + ":\n");

for (StudentModel student : students) {


result.append("ID: ").append(student.getSno())
.append(", Name: ").append(student.getName())
.append("\n");
}

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


resultTextView.setText(result.toString());
}

@Override
protected void onDestroy() {
super.onDestroy();
relationshipDataSource.close();
studentDataSource.close();
}
}

Create following table:


Emp(emp_no,emp_name,address,phone,salary)
Dept(dept_no,dept_name,location)
Emp-dept is related with one-many relationship.
Create application for performing the following operation on the table
1.Add records into emp and dept table.
2.accept department name from user and delete employee information
which belongs to that department.

EmpModel.java:

public class EmpModel {


private int empNo;
private String empName;
private String address;
private String phone;
private double salary;
private int deptNo;

// Constructors, getters, and setters...

public EmpModel() {
}

public EmpModel(String empName, String address, String phone,


double salary, int deptNo) {
this.empName = empName;
this.address = address;
this.phone = phone;
this.salary = salary;
this.deptNo = deptNo;
}

// Getters and setters...


}

DeptModel.java:

public class DeptModel {


private int deptNo;
private String deptName;
private String location;
// Constructors, getters, and setters...

public DeptModel() {
}

public DeptModel(String deptName, String location) {


this.deptName = deptName;
this.location = location;
}

// Getters and setters...


}

DatabaseHelper.java:

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "company_database";


private static final int DATABASE_VERSION = 1;

// Emp table
private static final String TABLE_EMP = "emp";
private static final String KEY_EMP_NO = "emp_no";
private static final String KEY_EMP_NAME = "emp_name";
private static final String KEY_ADDRESS = "address";
private static final String KEY_PHONE = "phone";
private static final String KEY_SALARY = "salary";
private static final String KEY_DEPT_NO_EMP = "dept_no";

// Dept table
private static final String TABLE_DEPT = "dept";
private static final String KEY_DEPT_NO_DEPT = "dept_no";
private static final String KEY_DEPT_NAME = "dept_name";
private static final String KEY_LOCATION = "location";

private static final String CREATE_TABLE_EMP =


"CREATE TABLE " + TABLE_EMP + "(" +
KEY_EMP_NO + " INTEGER PRIMARY KEY
AUTOINCREMENT," +
KEY_EMP_NAME + " TEXT," +
KEY_ADDRESS + " TEXT," +
KEY_PHONE + " TEXT," +
KEY_SALARY + " REAL," +
KEY_DEPT_NO_EMP + " INTEGER," +
"FOREIGN KEY (" + KEY_DEPT_NO_EMP + ") REFERENCES "
+ TABLE_DEPT + "(" + KEY_DEPT_NO_DEPT + ")" +
")";
private static final String CREATE_TABLE_DEPT =
"CREATE TABLE " + TABLE_DEPT + "(" +
KEY_DEPT_NO_DEPT + " INTEGER PRIMARY KEY
AUTOINCREMENT," +
KEY_DEPT_NAME + " TEXT," +
KEY_LOCATION + " TEXT" +
")";

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_DEPT);
db.execSQL(CREATE_TABLE_EMP);
}

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

EmpDataSource.java:

public class EmpDataSource {

private SQLiteDatabase database;


private DatabaseHelper dbHelper;

// ...

public long insertEmp(EmpModel emp) {


ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_EMP_NAME, emp.getEmpName());
values.put(DatabaseHelper.KEY_ADDRESS, emp.getAddress());
values.put(DatabaseHelper.KEY_PHONE, emp.getPhone());
values.put(DatabaseHelper.KEY_SALARY, emp.getSalary());
values.put(DatabaseHelper.KEY_DEPT_NO_EMP,
emp.getDeptNo());

return database.insert(DatabaseHelper.TABLE_EMP, null, values);


}
// ...
}

DeptDataSource.java:

public class DeptDataSource {

private SQLiteDatabase database;


private DatabaseHelper dbHelper;

// ...

public long insertDept(DeptModel dept) {


ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_DEPT_NAME,
dept.getDeptName());
values.put(DatabaseHelper.KEY_LOCATION, dept.getLocation());

return database.insert(DatabaseHelper.TABLE_DEPT, null, values);


}

public void deleteEmpByDeptName(String deptName) {


int deptNo = getDeptNoByName(deptName);
if (deptNo != -1) {
database.delete(DatabaseHelper.TABLE_EMP,
DatabaseHelper.KEY_DEPT_NO_EMP + " = ?", new String[]
{String.valueOf(deptNo)});
}
}

private int getDeptNoByName(String deptName) {


String[] columns = {DatabaseHelper.KEY_DEPT_NO_DEPT};
String selection = DatabaseHelper.KEY_DEPT_NAME + " = ?";
String[] selectionArgs = {deptName};

Cursor cursor = database.query(DatabaseHelper.TABLE_DEPT,


columns, selection, selectionArgs, null, null, null);

if (cursor != null && cursor.moveToFirst()) {


int deptNo =
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.KEY_DEPT_NO_D
EPT));
cursor.close

create simple application with login module(check username and


password). On successful login, pass username to next screen and on
failing login, alert user using Toast(Hind: user
login(username,password)table.

MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText usernameEditText, passwordEditText;


private Button loginButton;

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

usernameEditText = findViewById(R.id.usernameEditText);
passwordEditText = findViewById(R.id.passwordEditText);
loginButton = findViewById(R.id.loginButton);

loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});
}

private void login() {


String username = usernameEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();

// Replace these hardcoded values with your actual authentication


logic
String correctUsername = "user";
String correctPassword = "password";

if (username.equals(correctUsername) &&
password.equals(correctPassword)) {
// Successful login, move to the next screen
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("username", username);
startActivity(intent);
} else {
// Failed login, show a Toast message
Toast.makeText(MainActivity.this, "Login failed. Please check
your credentials.", Toast.LENGTH_SHORT).show();
}
}
}

NextActivity.java
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class NextActivity extends AppCompatActivity {

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

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

// Get the username from the intent


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

// Display the username in the TextView


usernameTextView.setText("Welcome, " + username + "!");
}
}

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

<EditText
android:id="@+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:layout_marginTop="50dp"
android:layout_marginHorizontal="16dp"/>
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/usernameEditText"
android:layout_marginTop="16dp"
android:hint="Password"
android:layout_marginHorizontal="16dp"
android:inputType="textPassword"/>

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

</RelativeLayout>

activity_next.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=".NextActivity">

<TextView
android:id="@+id/usernameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Welcome!"
android:textSize="18sp"/>

</RelativeLayout>

Create Table project(pno,p_name,ptype,duaration) and


employee(id,e_name,qualification, joindate)
Project_employee have many to many relationship.
Using database perform following operations
1.add new record into table.
2.accept a project name from user and display information of employee
working on the project.

1. Create Database Helper Class (DBHelper.java):


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

public class DBHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "company.db";
private static final int DATABASE_VERSION = 1;

public DBHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
// Create Project table
db.execSQL("CREATE TABLE Project (pno INTEGER PRIMARY KEY,
p_name TEXT, ptype TEXT, duration TEXT)");

// Create Employee table


db.execSQL("CREATE TABLE Employee (id INTEGER PRIMARY KEY,
e_name TEXT, qualification TEXT, joindate TEXT)");

// Create Project_Employee table for many-to-many relationship


db.execSQL("CREATE TABLE Project_Employee (project_id
INTEGER, employee_id INTEGER, " +
"FOREIGN KEY(project_id) REFERENCES Project(pno), " +
"FOREIGN KEY(employee_id) REFERENCES Employee(id), " +
"PRIMARY KEY(project_id, employee_id))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Upgrade logic here if needed
}
}
2. Perform Operations (MainActivity.java):

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

private EditText projectNameEditText;


private TextView resultTextView;
private DBHelper dbHelper;

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

projectNameEditText = findViewById(R.id.projectNameEditText);
resultTextView = findViewById(R.id.resultTextView);

dbHelper = new DBHelper(this);


}

public void addRecord(View view) {


SQLiteDatabase db = dbHelper.getWritableDatabase();

// Add a new project


ContentValues projectValues = new ContentValues();
projectValues.put("p_name", "Project A");
projectValues.put("ptype", "Software");
projectValues.put("duration", "6 months");
long projectId = db.insert("Project", null, projectValues);

// Add a new employee


ContentValues employeeValues = new ContentValues();
employeeValues.put("e_name", "John Doe");
employeeValues.put("qualification", "Bachelor's");
employeeValues.put("joindate", "2024-03-04");
long employeeId = db.insert("Employee", null, employeeValues);

// Associate the employee with the project in Project_Employee


table
ContentValues projectEmployeeValues = new ContentValues();
projectEmployeeValues.put("project_id", projectId);
projectEmployeeValues.put("employee_id", employeeId);
db.insert("Project_Employee", null, projectEmployeeValues);

db.close();
Toast.makeText(this, "Record added successfully",
Toast.LENGTH_SHORT).show();
}

public void displayEmployeeInfo(View view) {


SQLiteDatabase db = dbHelper.getReadableDatabase();
String projectName =
projectNameEditText.getText().toString().trim();

// Query to get information of employees working on the specified


project
String query = "SELECT Employee.* FROM Employee " +
"JOIN Project_Employee ON Employee.id =
Project_Employee.employee_id " +
"JOIN Project ON Project_Employee.project_id = Project.pno "
+
"WHERE Project.p_name = ?";
Cursor cursor = db.rawQuery(query, new String[]{projectName});

StringBuilder result = new StringBuilder();


while (cursor.moveToNext()) {
String employeeName =
cursor.getString(cursor.getColumnIndex("e_name"));
String qualification =
cursor.getString(cursor.getColumnIndex("qualification"));
String joinDate =
cursor.getString(cursor.getColumnIndex("joindate"));

result.append("Employee Name:
").append(employeeName).append("\n");
result.append("Qualification: ").append(qualification).append("\
n");
result.append("Join Date: ").append(joinDate).append("\n\n");
}

cursor.close();
db.close();

if (result.length() > 0) {
resultTextView.setText(result.toString());
} else {
resultTextView.setText("No employees found for the specified
project.");
}
}
}

3. Layout File (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">

<EditText
android:id="@+id/projectNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Project Name"
android:layout_marginTop="50dp"
android:layout_marginHorizontal="16dp"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/projectNameEditText"
android:layout_marginTop="16dp"
android:onClick="addRecord"
android:text="Add Record"
android:layout_marginHorizontal="16dp"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/projectNameEditText"
android:layout_marginTop="16dp"
android:onClick="displayEmployeeInfo"
android:text="Display Employee Info"
android:layout_marginHorizontal="16dp"/>

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/projectNameEditText"
android:layout_marginTop="16dp"
android:layout_marginHorizontal="16dp"/>
</RelativeLayout>

create simple application shown below. create table student(sid,s_name,phno).use


autoincrement for sid and perform following operation.
1.add student and display its information.
2.delete student

1. Database Helper Class (DBHelper.java):

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {

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


private static final int DATABASE_VERSION = 1;

public DBHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
// Create Student table
db.execSQL("CREATE TABLE Student (sid INTEGER PRIMARY KEY
AUTOINCREMENT, s_name TEXT, phno TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Upgrade logic here if needed
}

public long addStudent(String studentName, String phoneNumber) {


SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put("s_name", studentName);
values.put("phno", phoneNumber);

long studentId = db.insert("Student", null, values);

db.close();

return studentId;
}

public Cursor getStudentInfo(long studentId) {


SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {"s_name", "phno"};
String selection = "sid=?";
String[] selectionArgs = {String.valueOf(studentId)};

return db.query("Student", columns, selection, selectionArgs, null,


null, null);
}

public boolean deleteStudent(long studentId) {


SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "sid=?";
String[] whereArgs = {String.valueOf(studentId)};

int affectedRows = db.delete("Student", whereClause,


whereArgs);

db.close();

return affectedRows > 0;


}
}
2. MainActivity (MainActivity.java):

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText studentNameEditText, phoneNumberEditText,


studentIdEditText;
private TextView resultTextView;
private DBHelper dbHelper;

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

studentNameEditText = findViewById(R.id.studentNameEditText);
phoneNumberEditText =
findViewById(R.id.phoneNumberEditText);
studentIdEditText = findViewById(R.id.studentIdEditText);
resultTextView = findViewById(R.id.resultTextView);

dbHelper = new DBHelper(this);


}

public void addStudent(View view) {


String studentName =
studentNameEditText.getText().toString().trim();
String phoneNumber =
phoneNumberEditText.getText().toString().trim();
long studentId = dbHelper.addStudent(studentName,
phoneNumber);

if (studentId != -1) {
displayStudentInfo(studentId);
Toast.makeText(this, "Student added with ID: " + studentId,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to add student",
Toast.LENGTH_SHORT).show();
}
}

public void deleteStudent(View view) {


String studentIdString =
studentIdEditText.getText().toString().trim();

if (!studentIdString.isEmpty()) {
long studentId = Long.parseLong(studentIdString);

if (dbHelper.deleteStudent(studentId)) {
Toast.makeText(this, "Student deleted successfully",
Toast.LENGTH_SHORT).show();
clearFields();
} else {
Toast.makeText(this, "Failed to delete student",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Please enter a valid student ID",
Toast.LENGTH_SHORT).show();
}
}

private void displayStudentInfo(long studentId) {


Cursor cursor = dbHelper.getStudentInfo(studentId);

if (cursor.moveToFirst()) {
String studentName =
cursor.getString(cursor.getColumnIndex("s_name"));
String phoneNumber =
cursor.getString(cursor.getColumnIndex("phno"));

resultTextView.setText("Student Name: " + studentName + "\


nPhone Number: " + phoneNumber);
}

cursor.close();
}

private void clearFields() {


studentNameEditText.getText().clear();
phoneNumberEditText.getText().clear();
studentIdEditText.getText().clear();
resultTextView.setText("");
}
}

3. Layout File (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">

<EditText
android:id="@+id/studentNameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Student Name"
android:layout_marginTop="50dp"
android:layout_marginHorizontal="16dp"/>

<EditText
android:id="@+id/phoneNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/studentNameEditText"
android:layout_marginTop="16dp"
android:hint="Phone Number"
android:layout_marginHorizontal="16dp"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phoneNumberEditText"
android:layout_marginTop="16dp"
android:onClick="addStudent"
android:text="Add Student"
android:layout_marginHorizontal="16dp"/>

<EditText
android:id="@+id/studentIdEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phoneNumberEditText"
android:layout_marginTop="16dp"
android:hint="Student ID for Deletion"
android:layout_marginHorizontal="16dp"/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/studentIdEditText"
android:layout_marginTop="16dp"
android:onClick="deleteStudent"
android:text="Delete Student"
android:layout_marginHorizontal="16dp"/>

<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/studentIdEditText"
android:layout_marginTop="16dp"
android:layout_marginHorizontal="16dp"/>
</RelativeLayout>

You might also like