0% found this document useful (0 votes)
13 views47 pages

Android App with GUI and Event Listeners

Uploaded by

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

Android App with GUI and Event Listeners

Uploaded by

naveen.27csb
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] an application that uses GUI components, Font and Colors.

Activity_xml.xml

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


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#282c34"
android:padding="16dp">

<!-- Welcome Label -->


<TextView
android:id="@+id/welcomeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to My Application"
android:textSize="24sp"
android:textColor="#61dafb"
android:fontFamily="sans-serif-medium"
android:layout_gravity="center_horizontal"
android:paddingBottom="16dp" />

<!-- Name Input Label -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name:"
android:textSize="16sp"
android:textColor="#ffffff"
android:paddingBottom="8dp" />

<!-- Name Input Field -->


<EditText
android:id="@+id/nameInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3a3f47"
android:textColor="#ffffff"
android:textColorHint="#8a8a8a"
android:padding="12dp"
android:hint="Your name" />

<!-- Greet Button -->


<Button
android:id="@+id/greetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Greet Me"
android:layout_gravity="center_horizontal"
android:padding="12dp"
android:textColor="#ffffff"
android:backgroundTint="#61dafb"
android:fontFamily="sans-serif-medium"
android:layout_marginTop="16dp" />

<!-- Greeting Label -->


<TextView
android:id="@+id/greetingLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#98c379"
android:layout_gravity="center_horizontal"
android:layout_marginTop="24dp" />
</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Find components by their IDs


EditText nameInput = findViewById([Link]);
Button greetButton = findViewById([Link]);
TextView greetingLabel = findViewById([Link]);

// Set onClickListener for the button


[Link](new [Link]() {
@Override
public void onClick(View view) {
String name = [Link]().toString();
if (![Link]()) {
[Link]("Hello, " + name + "!");
} else {
[Link]("Please enter your name!");
}
}
});
}
}
2. Develop an application that uses Layout Managers and event listeners.

Activity_xml.xml

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


<LinearLayout
xmlns:android="[Link]
xmlns:app="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- LinearLayout with a Button -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Button 2" />
</LinearLayout>

<!-- RelativeLayout with an EditText and Button -->


<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="@id/editText"
android:text="Submit"
android:layout_marginTop="8dp" />
</RelativeLayout>

<!-- ConstraintLayout with ImageView and TextView -->


<[Link]
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="16dp">

<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@android:drawable/ic_menu_gallery"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Preview"
app:layout_constraintTop_toBottomOf="@id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="8dp"/>
</[Link]>
</LinearLayout>

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {

private Button button1, button2, button3;


private EditText editText;
private ImageView imageView;
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Initialize views
button1 = findViewById([Link].button1);
button2 = findViewById([Link].button2);
button3 = findViewById([Link].button3);
editText = findViewById([Link]);
imageView = findViewById([Link]);
textView = findViewById([Link]);

// Set event listeners


[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link]([Link], "Button 1 Clicked",
Toast.LENGTH_SHORT).show();
}
});

[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link]([Link], "Button 2 Clicked",
Toast.LENGTH_SHORT).show();
}
});

[Link](new [Link]() {
@Override
public void onClick(View v) {
String inputText = [Link]().toString();
if (![Link]()) {
[Link](inputText);
[Link]([Link], "Submitted: " +
inputText, Toast.LENGTH_SHORT).show();
} else {
[Link]([Link], "Please enter text",
Toast.LENGTH_SHORT).show();
}
}
});

// ImageView click listener


[Link](new [Link]() {
@Override
public void onClick(View v) {
[Link]([Link], "Image Clicked",
Toast.LENGTH_SHORT).show();
}
});
}
}
[Link] an application that draws basic graphical primitives on the screen.

Activity_xml.xml

<!-- res/layout/activity_main.xml -->


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<Button
android:id="@+id/drawButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Shape" />

<[Link]
android:id="@+id/shapeView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="16dp" />
</LinearLayout>

[Link]

// src/com/example/shapedrawer/[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ShapeView extends View {
private Paint paint;
private int shapeType = 0; // 0 = circle, 1 = square, 2 = rectangle, 3 = triangle

public ShapeView(Context context, AttributeSet attrs) {


super(context, attrs);
paint = new Paint();
[Link]([Link]);
[Link]([Link]);
}

public void setShapeType(int shapeType) {


[Link] = shapeType;
invalidate(); // Redraw the view
}

@Override
protected void onDraw(Canvas canvas) {
[Link](canvas);

int width = getWidth();


int height = getHeight();

switch (shapeType) {
case 0:
// Draw a Circle
[Link](width / 2, height / 2, [Link](width, height) / 4, paint);
break;
case 1:
// Draw a Square
[Link](width / 4, height / 4, 3 * width / 4, 3 * height / 4, paint);
break;
case 2:
// Draw a Rectangle
[Link](width / 4, height / 3, 3 * width / 4, 2 * height / 3, paint);
break;
case 3:
// Draw a Triangle
Path path = new Path();
[Link](width / 2, height / 4);
[Link](width / 4, 3 * height / 4);
[Link](3 * width / 4, 3 * height / 4);
[Link]();
[Link](path, paint);
break;
}
}
}

[Link]

// src/com/example/shapedrawer/[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


private ShapeView shapeView;
private int clickCount = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

shapeView = findViewById([Link]);
Button drawButton = findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
clickCount = (clickCount + 1) % 4; // Cycle through shapes 0, 1, 2, 3
[Link](clickCount);
}
});
}
}
[Link] (already there under manifest)

<!-- [Link] -->


<manifest xmlns:android="[Link]
package="[Link]">

<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
[Link] an application that makes use of databases.

Activity_xml.xml

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- Input for name -->


<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name"
android:textSize="18sp"/>

<!-- Add button -->


<Button
android:id="@+id/buttonAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Name"
android:layout_marginTop="8dp" />

<!-- View all button -->


<Button
android:id="@+id/buttonViewAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View All Names"
android:layout_marginTop="8dp" />

<!-- Delete button -->


<Button
android:id="@+id/buttonDelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete Name"
android:layout_marginTop="8dp" />

<!-- Display area -->


<TextView
android:id="@+id/textViewDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:padding="16dp"
android:textSize="16sp"
android:layout_marginTop="16dp"
android:background="#eeeeee" />
</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "[Link]";


private static final String TABLE_NAME = "names_table";
private static final String COL_1 = "ID";
private static final String COL_2 = "NAME";

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
[Link]("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, NAME TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

// Insert data
public boolean insertData(String name) {
SQLiteDatabase db = [Link]();
ContentValues contentValues = new ContentValues();
[Link](COL_2, name);
long result = [Link](TABLE_NAME, null, contentValues);
return result != -1;
}

// Get all data


public Cursor getAllData() {
SQLiteDatabase db = [Link]();
return [Link]("SELECT * FROM " + TABLE_NAME, null);
}

// Delete a specific entry


public Integer deleteData(String id) {
SQLiteDatabase db = [Link]();
return [Link](TABLE_NAME, "ID = ?", new String[]{id});
}
}

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

DatabaseHelper myDb;
EditText editTextName;
TextView textViewDisplay;
Button buttonAdd, buttonViewAll, buttonDelete;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

myDb = new DatabaseHelper(this);

editTextName = findViewById([Link]);
textViewDisplay = findViewById([Link]);
buttonAdd = findViewById([Link]);
buttonViewAll = findViewById([Link]);
buttonDelete = findViewById([Link]);

addData();
viewAllData();
deleteData();
}
// Method to add data
public void addData() {
[Link](new [Link]() {
@Override
public void onClick(View v) {
String name = [Link]().toString();
if ([Link]()) {
[Link]([Link], "Please enter a name",
Toast.LENGTH_SHORT).show();
return;
}
boolean isInserted = [Link](name);
if (isInserted) {
[Link]([Link], "Name Added",
Toast.LENGTH_SHORT).show();
[Link]("");
} else {
[Link]([Link], "Error Adding Name",
Toast.LENGTH_SHORT).show();
}
}
});
}

// Method to view all data


public void viewAllData() {
[Link](new [Link]() {
@Override
public void onClick(View v) {
Cursor res = [Link]();
if ([Link]() == 0) {
[Link]("No data found");
return;
}
StringBuilder buffer = new StringBuilder();
while ([Link]()) {
[Link]("ID:
").append([Link](0)).append("\n");
[Link]("Name:
").append([Link](1)).append("\n\n");
}
[Link]([Link]());
}
});
}

// Method to delete data


public void deleteData() {
[Link](new [Link]() {
@Override
public void onClick(View v) {
String id = [Link]().toString();
if ([Link]()) {
[Link]([Link], "Enter ID to delete",
Toast.LENGTH_SHORT).show();
return;
}
Integer deletedRows = [Link](id);
if (deletedRows > 0) {
[Link]([Link], "Name Deleted",
Toast.LENGTH_SHORT).show();
[Link]("");
} else {
[Link]([Link], "No match found for ID",
Toast.LENGTH_SHORT).show();
}
}
});
}
}

[Link] (already there under manifest)

<manifest xmlns:android="[Link]
package="[Link]">

<application
android:allowBackup="true"
android:label="Simple Database App"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
[Link] a calculator application that uses Layout Managers and event listeners.

Activity_xml.xml

<!-- res/layout/activity_main.xml -->


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<!-- Display Screen -->


<TextView
android:id="@+id/display"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
android:gravity="end"
android:padding="20dp"
android:text="0"
android:textSize="32sp"
android:textColor="#000000" />

<!-- Button Grid Layout -->


<GridLayout
android:id="@+id/buttonGrid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:columnCount="4"
android:rowCount="5">

<!-- Row 1 -->


<Button android:id="@+id/btnClear" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="C" android:layout_columnWeight="1" />
<Button android:id="@+id/btnDivide" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="/" android:layout_columnWeight="1" />
<Button android:id="@+id/btnMultiply" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="*" android:layout_columnWeight="1" />
<Button android:id="@+id/btnDelete" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="DEL" android:layout_columnWeight="1"
/>

<!-- Row 2 -->


<Button android:id="@+id/btn7" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="7" android:layout_columnWeight="1" />
<Button android:id="@+id/btn8" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="8" android:layout_columnWeight="1" />
<Button android:id="@+id/btn9" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="9" android:layout_columnWeight="1" />
<Button android:id="@+id/btnSubtract" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="-" android:layout_columnWeight="1" />

<!-- Row 3 -->


<Button android:id="@+id/btn4" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="4" android:layout_columnWeight="1" />
<Button android:id="@+id/btn5" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="5" android:layout_columnWeight="1" />
<Button android:id="@+id/btn6" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="6" android:layout_columnWeight="1" />
<Button android:id="@+id/btnAdd" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="+" android:layout_columnWeight="1" />

<!-- Row 4 -->


<Button android:id="@+id/btn1" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="1" android:layout_columnWeight="1" />
<Button android:id="@+id/btn2" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="2" android:layout_columnWeight="1" />
<Button android:id="@+id/btn3" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="3" android:layout_columnWeight="1" />
<Button android:id="@+id/btnEquals" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="=" android:layout_columnWeight="1" />

<!-- Row 5 -->


<Button android:id="@+id/btn0" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="0" android:layout_columnWeight="2"
android:layout_columnSpan="2"/>
<Button android:id="@+id/btnDot" android:layout_width="0dp"
android:layout_height="wrap_content" android:text="." android:layout_columnWeight="1" />
</GridLayout>
</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private TextView display;


private String input = "";
private String operator = "";
private double num1 = 0, num2 = 0;
private boolean isNewOperator = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

display = findViewById([Link]);
setupButtonListeners();
}

private void setupButtonListeners() {


int[] numberIds = {[Link].btn0, [Link].btn1, [Link].btn2, [Link].btn3, [Link].btn4, [Link].btn5,
[Link].btn6, [Link].btn7, [Link].btn8, [Link].btn9, [Link]};
int[] operatorIds = {[Link], [Link], [Link], [Link]};

for (int id : numberIds) {


findViewById(id).setOnClickListener(new [Link]() {
@Override
public void onClick(View v) {
handleNumberInput(((Button) v).getText().toString());
}
});
}

for (int id : operatorIds) {


findViewById(id).setOnClickListener(new [Link]() {
@Override
public void onClick(View v) {
handleOperator(((Button) v).getText().toString());
}
});
}

findViewById([Link]).setOnClickListener(v -> handleEquals());


findViewById([Link]).setOnClickListener(v -> handleClear());
findViewById([Link]).setOnClickListener(v -> handleDelete());
}

private void handleNumberInput(String value) {


if (isNewOperator) {
input = "";
isNewOperator = false;
}
input += value;
[Link](input);
}

private void handleOperator(String op) {


if (![Link]()) {
num1 = [Link](input);
operator = op;
isNewOperator = true;
}
}

private void handleEquals() {


if (![Link]() && ![Link]()) {
num2 = [Link](input);
double result = 0;
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "/": result = num2 != 0 ? num1 / num2 : 0; break;
}
[Link]([Link](result));
input = [Link](result);
operator = "";
}
}

private void handleClear() {


input = "";
num1 = 0;
num2 = 0;
operator = "";
[Link]("0");
}

private void handleDelete() {


if (![Link]()) {
input = [Link](0, [Link]() - 1);
[Link]([Link]() ? "0" : input);
}
}
}
[Link] a student database to find the result of a student in the recent examination
results.

Activity_xml.xml

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- Name Input -->


<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Student Name"
android:textSize="18sp" />

<!-- Subject Input -->


<EditText
android:id="@+id/editTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:textSize="18sp"
android:layout_marginTop="8dp" />

<!-- Score Input -->


<EditText
android:id="@+id/editTextScore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Score"
android:inputType="number"
android:textSize="18sp"
android:layout_marginTop="8dp" />

<!-- Add Button -->


<Button
android:id="@+id/buttonAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Result"
android:layout_marginTop="8dp" />

<!-- View Results Button -->


<Button
android:id="@+id/buttonViewAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View All Results"
android:layout_marginTop="8dp" />

<!-- Display Area -->


<TextView
android:id="@+id/textViewResults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:padding="16dp"
android:textSize="16sp"
android:layout_marginTop="16dp"
android:background="#eeeeee" />
</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DatabaseHelper extends SQLiteOpenHelper {

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


private static final String TABLE_NAME = "results";
private static final String COL_1 = "ID";
private static final String COL_2 = "NAME";
private static final String COL_3 = "SUBJECT";
private static final String COL_4 = "SCORE";

public DatabaseHelper(Context context) {


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

@Override
public void onCreate(SQLiteDatabase db) {
[Link]("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, NAME TEXT, SUBJECT TEXT, SCORE INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
[Link]("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

// Insert data
public boolean insertData(String name, String subject, int score) {
SQLiteDatabase db = [Link]();
ContentValues contentValues = new ContentValues();
[Link](COL_2, name);
[Link](COL_3, subject);
[Link](COL_4, score);
long result = [Link](TABLE_NAME, null, contentValues);
return result != -1;
}

// Get all data


public Cursor getAllData() {
SQLiteDatabase db = [Link]();
return [Link]("SELECT * FROM " + TABLE_NAME, null);
}
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

DatabaseHelper myDb;
EditText editTextName, editTextSubject, editTextScore;
TextView textViewResults;
Button buttonAdd, buttonViewAll;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

myDb = new DatabaseHelper(this);

editTextName = findViewById([Link]);
editTextSubject = findViewById([Link]);
editTextScore = findViewById([Link]);
textViewResults = findViewById([Link]);
buttonAdd = findViewById([Link]);
buttonViewAll = findViewById([Link]);

addData();
viewAllData();
}

// Method to add data


public void addData() {
[Link](new [Link]() {
@Override
public void onClick(View v) {
String name = [Link]().toString();
String subject = [Link]().toString();
String scoreStr = [Link]().toString();

if ([Link]() || [Link]() || [Link]())


{
[Link]([Link], "Please fill in all
fields", Toast.LENGTH_SHORT).show();
return;
}

int score = [Link](scoreStr);


boolean isInserted = [Link](name, subject, score);
if (isInserted) {
[Link]([Link], "Result Added",
Toast.LENGTH_SHORT).show();
[Link]("");
[Link]("");
[Link]("");
} else {
[Link]([Link], "Error Adding Result",
Toast.LENGTH_SHORT).show();
}
}
});
}

// Method to view all data


public void viewAllData() {
[Link](new [Link]() {
@Override
public void onClick(View v) {
Cursor res = [Link]();
if ([Link]() == 0) {
[Link]("No results found");
return;
}
StringBuilder buffer = new StringBuilder();
while ([Link]()) {
[Link]("ID:
").append([Link](0)).append("\n");
[Link]("Name:
").append([Link](1)).append("\n");
[Link]("Subject:
").append([Link](2)).append("\n");
[Link]("Score:
").append([Link](3)).append("\n\n");
}
[Link]([Link]());
}
});
}
}

[Link] (already there under manifest)

<!-- [Link] -->


<manifest xmlns:android="[Link]
package="[Link]">

<application
android:allowBackup="true"
android:label="Student Results App"
android:supportsRtl="true"
android:theme="@style/[Link]">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
7. Design an android application using Cordova for a user login screen with
username,password, reset button and a submit button. Also, include header image and a
label.

1. npm install -g cordova


2. cordova create LoginApp [Link] LoginApp
3. cd LoginApp
4. code . ( Alter the code in VS code)
5. cordova platform add android

html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Screen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/[Link]">
</head>
<body>
<div class="login-container">
<img src="img/[Link]" alt="Header Image" class="header-img">
<h2 class="label">Login</h2>

<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

<div class="button-container">
<button type="button" id="resetBtn">Reset</button>
<button type="button" id="submitBtn">Submit</button>
</div>
</form>
</div>
<script src="[Link]"></script>
<script src="js/[Link]"></script>
</body>
</html>

css
body {
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f7f7f7;
}

.login-container {
width: 90%;
max-width: 400px;
padding: 20px;
border-radius: 8px;
background-color: white;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

.header-img {
width: 100%;
height: auto;
margin-bottom: 20px;
}

.label {
text-align: center;
margin-bottom: 20px;
font-size: 24px;
color: #333;
}

input[type="text"], input[type="password"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

.button-container {
display: flex;
justify-content: space-between;
}

button {
width: 45%;
padding: 10px;
font-size: 16px;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
}

#resetBtn {
background-color: #d9534f;
}

#submitBtn {
background-color: #5cb85c;
}

Js
[Link]('deviceready', function() {
// Get form elements
const resetBtn = [Link]("resetBtn");
const submitBtn = [Link]("submitBtn");
const usernameInput = [Link]("username");
const passwordInput = [Link]("password");

// Reset button functionality


[Link]('click', function() {
[Link] = '';
[Link] = '';
});

// Submit button functionality


[Link]('click', function() {
const username = [Link];
const password = [Link];

if (username && password) {


alert("Login Successful");
// Process login logic here
} else {
alert("Please enter both username and password.");
}
});
});

Build and Run the App on Android


1. cordova build android
2. cordova run android
[Link] and develop an android application using Apache Cordova to find and display the
current location of the user.

Step 1: Create a New Cordova Project


cordova create LocationApp [Link] LocationApp
cd LocationApp
cordova platform add android

Step 2: Install the Geolocation Plugin


cordova plugin add cordova-plugin-geolocation

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Current Location</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/[Link]">
</head>
<body>
<div class="location-container">
<h2>Find My Location</h2>
<button id="getLocationBtn">Get Current Location</button>
<div id="locationDisplay">
<p id="latitude">Latitude: </p>
<p id="longitude">Longitude: </p>
</div>
</div>

<script src="[Link]"></script>
<script src="js/[Link]"></script>
</body>
</html>

css/[Link]
body {
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}

.location-container {
width: 90%;
max-width: 400px;
padding: 20px;
border-radius: 8px;
background-color: white;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

h2 {
color: #333;
margin-bottom: 20px;
}

button {
padding: 10px 20px;
font-size: 16px;
border: none;
border-radius: 4px;
background-color: #5cb85c;
color: white;
cursor: pointer;
margin-bottom: 20px;
}

#locationDisplay p {
font-size: 18px;
color: #555;
}
js/[Link]
[Link]("deviceready", function() {
const getLocationBtn = [Link]("getLocationBtn");
const latitudeDisplay = [Link]("latitude");
const longitudeDisplay = [Link]("longitude");

[Link]("click", function() {
[Link](onSuccess, onError, {
enableHighAccuracy: true
});
});
function onSuccess(position) {
const latitude = [Link];
const longitude = [Link];

[Link] = `Latitude: ${latitude}`;


[Link] = `Longitude: ${longitude}`;
}
function onError(error) {
alert(`Error: ${[Link]}`);
}
});

Step 4: Configure Android Permissions


[Link]:
<widget id="[Link]" version="1.0.0" xmlns="[Link]
xmlns:cdv="[Link]
<platform name="android">
<edit-config file="app/src/main/[Link]" mode="merge" target="/manifest">
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION" />
<uses-permission android:name="[Link].ACCESS_COARSE_LOCATION"
/>
</edit-config>
</platform>
</widget>

Step 5: Build and Run the App on Android


cordova build android
cordova run android
[Link] an android application to send email to friends.

Activity_xml.xml

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/editTextRecipient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Recipient Email"
android:inputType="textEmailAddress" />

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

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message"
android:inputType="textMultiLine"
android:minLines="4" />

<Button
android:id="@+id/buttonSendEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Email" />

</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

private EditText editTextRecipient, editTextSubject, editTextMessage;


private Button buttonSendEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

// Initialize the UI elements


editTextRecipient = findViewById([Link]);
editTextSubject = findViewById([Link]);
editTextMessage = findViewById([Link]);
buttonSendEmail = findViewById([Link]);

// Set click listener on the Send Email button


[Link](v -> sendEmail());
}

private void sendEmail() {


// Get user input from the EditText fields
String recipient = [Link]().toString().trim();
String subject = [Link]().toString().trim();
String message = [Link]().toString().trim();

// Check if the recipient email is entered


if ([Link]()) {
[Link](this, "Please enter recipient email",
Toast.LENGTH_SHORT).show();
return;
}

// Set up the email Intent


Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
[Link]([Link]("[Link] // Only email apps should
handle this
[Link](Intent.EXTRA_EMAIL, new String[]{recipient});
[Link](Intent.EXTRA_SUBJECT, subject);
[Link](Intent.EXTRA_TEXT, message);

try {
// Start the email client
startActivity([Link](emailIntent, "Choose an email
client"));
} catch (Exception e) {
[Link](this, "No email client found on device.",
Toast.LENGTH_SHORT).show();
}
}
}
[Link] an android application to generate notifications on receiving mails or messages.

Acitivity_main.xml

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


<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="shownofn"/>
</LinearLayout>

[Link]

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
public void shownvofn(View view) {
//this code is for before Oreo
// 1. create a Intent
// 2. create a PendingIntent
// 3. design Notification
// 4. initialise NotifivstionManager

Intent intent = new Intent([Link], [Link]);

PendingIntent pendingIntent = [Link]([Link], 0, intent, 0);

Notification notification = new


[Link]([Link]).setSmallIcon([Link].ic_media_play)
.setContentTitle("New message received")
.setContentIntent(pendingIntent)
.setContentText("message from Ragu")
.build();

NotificationManager notificationManager = (NotificationManager)


getSystemService(NOTIFICATION_SERVICE);

[Link](0, notification);

public void shownofn(View view) {


NotificationManager notificationManager = (NotificationManager)
[Link](Context.NOTIFICATION_SERVICE);

int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;

if ([Link].SDK_INT >= [Link].VERSION_CODES.O) {


NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
[Link](mChannel);
}

[Link] mBuilder = new [Link]([Link],


channelId)
.setLargeIcon([Link]([Link](),
[Link].ic_media_play))
.setSmallIcon([Link].ic_media_play).setContentTitle("You can also
'Learn Android'")
.setContentText("Contact AndroidManifester today!!");

Intent intent = new Intent([Link], [Link]);


PendingIntent pendingIntent = [Link]([Link], 0, intent, 0);
[Link](pendingIntent);

[Link](notificationId, [Link]());
}

}
[Link] calculator in Android and Cordova

Step 1: Create a New Cordova Project


cordova create BMICalculator [Link] BMICalculator
cd BMICalculator
cordova platform add android

Step 2: Design the HTML Layout for the BMI Calculator


[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>BMI Calculator</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/[Link]">
</head>
<body>
<div class="bmi-container">
<h2>BMI Calculator</h2>

<form id="bmiForm">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" name="weight" required>

<label for="height">Height (cm):</label>


<input type="number" id="height" name="height" required>

<button type="button" id="calculateBtn">Calculate BMI</button>


</form>

<div id="result" class="result">


<p>BMI: <span id="bmiValue"></span></p>
<p>Category: <span id="bmiCategory"></span></p>
</div>
</div>

<script src="[Link]"></script>
<script src="js/[Link]"></script>
</body>
</html>

css/[Link]
body {
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}

.bmi-container {
width: 90%;
max-width: 400px;
padding: 20px;
border-radius: 8px;
background-color: white;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}

h2 {
color: #333;
margin-bottom: 20px;
}

label {
font-size: 16px;
color: #555;
}

input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

button {
width: 100%;
padding: 10px;
font-size: 16px;
border: none;
border-radius: 4px;
background-color: #5cb85c;
color: white;
cursor: pointer;
margin-top: 10px;
}

.result p {
font-size: 18px;
color: #333;
}

js/[Link]

[Link]("deviceready", function() {
const calculateBtn = [Link]("calculateBtn");
const weightInput = [Link]("weight");
const heightInput = [Link]("height");
const bmiValueDisplay = [Link]("bmiValue");
const bmiCategoryDisplay = [Link]("bmiCategory");

[Link]("click", function() {
const weight = parseFloat([Link]);
const height = parseFloat([Link]) / 100; // Convert height from cm to meters

if (weight > 0 && height > 0) {


const bmi = (weight / (height * height)).toFixed(2);

[Link] = bmi;
[Link] = getBMICategory(bmi);
} else {
alert("Please enter valid values for weight and height.");
}
});

function getBMICategory(bmi) {
if (bmi < 18.5) return "Underweight";
if (bmi >= 18.5 && bmi < 24.9) return "Normal weight";
if (bmi >= 25 && bmi < 29.9) return "Overweight";
return "Obesity";
}
});

Step 4: Build and Run the App on Android


cordova build android
cordova run android
[Link] programs using Java to create Android application having Databases
● For a simple library application.
● For displaying books available, books lend, book reservation. Assume that student
information is available in a database which has been stored in a database server.

Activity_xml.xml

<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView android:text="Available Books" android:textSize="20sp"


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

<ListView android:id="@+id/listViewBooks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />

<EditText android:id="@+id/editTextBookName"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="Enter Book Name" />

<Button android:id="@+id/buttonBorrow" android:layout_width="match_parent"


android:layout_height="wrap_content" android:text="Borrow Book" />

<Button android:id="@+id/buttonReserve"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Reserve Book" />
</LinearLayout>

[Link]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


private ArrayList<Book> books;
private ListView listViewBooks;
private EditText editTextBookName;
private Button buttonBorrow, buttonReserve;

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

listViewBooks = findViewById([Link]);
editTextBookName = findViewById([Link]);
buttonBorrow = findViewById([Link]);
buttonReserve = findViewById([Link]);

initializeBooks(); // Initialize the book list with sample data


displayAvailableBooks();

[Link](v -> handleBookAction("borrow"));


[Link](v -> handleBookAction("reserve"));
}

// Initializes sample books data


private void initializeBooks() {
books = new ArrayList<>();
[Link](new Book("Book A", "Author A", true));
[Link](new Book("Book B", "Author B", true));
[Link](new Book("Book C", "Author C", true));
// Add more sample books as needed
}

// Display available books


private void displayAvailableBooks() {
ArrayList<String> availableBooks = new ArrayList<>();
for (Book book : books) {
if ([Link]()) {
[Link]([Link]() + " by " +
[Link]());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
[Link].simple_list_item_1, availableBooks);
[Link](adapter);
}

// Handles borrow or reserve actions based on button clicked


private void handleBookAction(String action) {
String bookName = [Link]().toString().trim();
for (Book book : books) {
if ([Link]().equalsIgnoreCase(bookName)) {
if ([Link]()) {
[Link](false);
String message = "Book " + action + "ed successfully!";
[Link](this, message, Toast.LENGTH_SHORT).show();
displayAvailableBooks();
return;
} else {
[Link](this, "Book is already lent out.",
Toast.LENGTH_SHORT).show();
return;
}
}
}
[Link](this, "Book not found.", Toast.LENGTH_SHORT).show();
}
}

[Link]

package [Link];

public class Book {


private String name;
private String author;
private boolean isAvailable;

public Book(String name, String author, boolean isAvailable) {


[Link] = name;
[Link] = author;
[Link] = isAvailable;
}

public String getName() {


return name;
}

public String getAuthor() {


return author;
}

public boolean isAvailable() {


return isAvailable;
}

public void setAvailable(boolean available) {


isAvailable = available;
}}

You might also like