0% found this document useful (0 votes)
29 views70 pages

Mobile

A mobile device is a portable computing device like smartphones and tablets that can run applications. Popular programming languages for mobile app development include Java, Kotlin, Swift, and JavaScript with frameworks like React Native. Android architecture consists of layers including the Linux kernel, native libraries, Android runtime, application framework, and applications, while UI controls in iOS include buttons, labels, and text fields.

Uploaded by

Suresh Pant
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)
29 views70 pages

Mobile

A mobile device is a portable computing device like smartphones and tablets that can run applications. Popular programming languages for mobile app development include Java, Kotlin, Swift, and JavaScript with frameworks like React Native. Android architecture consists of layers including the Linux kernel, native libraries, Android runtime, application framework, and applications, while UI controls in iOS include buttons, labels, and text fields.

Uploaded by

Suresh Pant
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
You are on page 1/ 70

11. What do you mean by mobile device?

List and explain any four popular programming languages used for
developing mobile applications.

A mobile device is a small, handheld computing device, typically with a display screen and a touch interface or
miniature keyboard, designed for portability and often equipped with internet connectivity and the ability to run
applications. Examples include smartphones, tablets, and smartwatches.

Four popular programming languages for mobile application development are:

Java: Primarily used for native Android app development. It's a robust, object-oriented language that benefits from
a large developer community and extensive libraries.

• Kotlin: A modern, statically typed programming language that runs on the Java Virtual Machine (JVM). It's
officially recommended by Google for Android development and offers conciseness, null safety, and
interoperability with existing Java code.

• Swift: Apple's powerful and intuitive programming language for building apps across all Apple platforms
(iOS, iPadOS, macOS, watchOS, tvOS). It's known for its safety, performance, and modern syntax.

• JavaScript (with frameworks like React Native or Ionic): While JavaScript itself isn't a native mobile
language, frameworks like React Native and Ionic allow developers to write mobile applications using
JavaScript, which can then be compiled into native apps for both iOS and Android. This offers cross-
platform development capabilities.

12. What is an event? How many ways to handle events in android programming?

In Android programming, an event is an action or occurrence that happens within an application, often triggered by
user interaction (like a button click, a screen touch, or a text input) or by the system (like a device rotation or a low
battery warning). These events signal that something has happened and the application might need to respond.

There are several common ways to handle events in Android programming:

• Using an OnClickListener (Anonymous Inner Class): This is a very common approach, especially for simple
interactions like button clicks.

Java

Button myButton = findViewById(R.id.my_button);

myButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Code to execute when the button is clicked

Toast.makeText(MainActivity.this, "Button Clicked!", Toast.LENGTH_SHORT).show();

}});

1
• Implementing an Interface: The activity or fragment can implement the appropriate listener interface
(e.g., View.OnClickListener), and then override the required method.

Java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button myButton = findViewById(R.id.my_button);

myButton.setOnClickListener(this); // 'this' refers to the activity itself }

@Override

public void onClick(View v) {

if (v.getId() == R.id.my_button) {

Toast.makeText(this, "Button Clicked (via Interface)!", Toast.LENGTH_SHORT).show(); } }}

• XML android:onClick attribute: For simple click events, you can specify the method name directly in your
layout XML. The method must be public, have a View parameter, and reside in the associated Activity or
Fragment.

XML

<Button

android:id="@+id/my_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:onClick="onMyButtonClick" />

Java

public void onMyButtonClick(View view) {

Toast.makeText(this, "Button Clicked (from XML)!", Toast.LENGTH_SHORT).show();}

• Lambda Expressions (Java 8+): For more concise code, especially with functional interfaces.

Java

Button myButton = findViewById(R.id.my_button);

myButton.setOnClickListener(v -> Toast.makeText(MainActivity.this, "Button Clicked (Lambda)!",


Toast.LENGTH_SHORT).show());

2
13. Explain android architecture briefly with a suitable diagram.

The Android architecture is a layered software stack designed for mobile devices. It's built upon the Linux kernel
and comprises several key components, each playing a crucial role in the system's functionality.

Brief Explanation of Layers:

1. Linux Kernel: The foundation of the Android platform. It handles low-level system services like memory
management, process management, networking, and hardware drivers (e.g., camera, Wi-Fi, audio). This
provides an abstraction layer between the hardware and the rest of the software stack.

2. Native Libraries: These are C/C++ libraries that provide core functionality for Android. Examples include:

o Surface Manager: For managing display access.

o Media Framework: For audio and video playback and recording.

o SQLite: A lightweight relational database for data storage.

o WebKit: The browser engine used for displaying web content.

o OpenGL ES: For 2D and 3D graphics rendering. These libraries are exposed to the Android
framework through Java interfaces.

3. Android Runtime (ART/Dalvik): This layer provides the environment for executing Android applications.

o ART (Android Runtime) is the current runtime, replacing Dalvik. It compiles app code into
machine code when the app is installed, leading to faster execution and improved performance.

o It also includes the Core Libraries, which provide the Java language features (like data structures,
utilities, I/O) that Android developers use.

4. Application Framework: This is a crucial layer that provides high-level building blocks and services that
developers use to create Android applications. It's essentially a set of Java APIs that simplify complex tasks.
Key components include:

o Activity Manager: Manages the lifecycle of applications and activities.

o Window Manager: Manages windows and their display on the screen.

o Package Manager: Manages installed applications and their packages.

o Resource Manager: Provides access to non-code resources like strings, layouts, and images.

o Content Providers: Enables data sharing between applications.

o View System: Manages the UI components (buttons, text views, etc.).

5. Applications: This is the top layer, comprising all the pre-installed system applications (like Home,
Contacts, Phone, Browser, Camera) and all the third-party applications that users download from the Play
Store or install manually. These applications are built using the components and APIs provided by the
Application Framework.

3
14. Why is fragment needed in android application? How can a fragment be added to an activity?

A Fragment in Android is a modular section of an Activity's user interface, offering a way to create more
flexible and reusable UI components. Fragments are needed for several key reasons:

• Modularity and Reusability:

• Support for Different Screen Sizes/Orientations:

• Improved User Experience (Especially on Tablets):

• Better Activity Lifecycle ManagementHow to add a Fragment to an Activity:

Fragments can be added to an activity programmatically (dynamically) or declared in the activity's layout
XML (statically).

1. Adding Programmatically (Dynamically): This is the more flexible and common approach, allowing you
to add, remove, replace, and manage fragments at runtime.

Java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.fragment.app.FragmentManager;

import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

FragmentManager fragmentManager = getSupportFragmentManager

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

MyFragment myFragment = new MyFragment();

fragmentTransaction.add(R.id.fragment_container, myFragment);

fragmentTransaction.commit(); }}

2. Adding Statically (in XML Layout): This is simpler for fragments that are always present in a specific part
of the UI.

In your activity_main.xml:

XML

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

android:layout_width="match_parent"

android:layout_height="match_parent"

4
android:orientation="vertical">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="This is the Activity" />

<fragment

android:id="@+id/my_static_fragment"

android:name="com.example.yourapp.MyFragment" // Fully qualified class name of your fragment

android:layout_width="match_parent"

android:layout_height="match_parent" />

</LinearLayout>

15. What are different types of UI controls used in iOS programming? Write a swift program to find the sum of all
elements of a 1-D array.

In iOS programming, UI controls (also known as UIKit controls) are standard, interactive user interface elements
that allow users to interact with an app. Some different types include:

• Buttons (UIButton): To initiate an action when tapped.

• Labels (UILabel): To display static text.

• Text Fields (UITextField): To allow users to input single lines of text.

• Text Views (UITextView): To allow users to input or display multiple lines of text.

• Sliders (UISlider): To select a value from a continuous range.

• Switches (UISwitch): To toggle a setting on or off.

• Segmented Controls (UISegmentedControl): To select from a small set of mutually exclusive options.

• Steppers (UIStepper): To incrementally increase or decrease a value.

• Image Views (UIImageView): To display images.

• Progress Views (UIProgressView): To indicate the progress of a task.

• Activity Indicators (UIActivityIndicatorView): To show that a task is in progress.

• Table Views (UITableView): To display lists of data in a single column.

• Collection Views (UICollectionView): To display collections of data in customizable layouts.

• Pickers (UIPickerView): To select one or more items from a list of values.

• Date Pickers (UIDatePicker): To select a date and/or time.

• Web Views (WKWebView): To display web content.

5
Swift program to find the sum of all elements of a 1-D array:

Swift

let numbers = [10, 20, 5, 15, 30]

var sumOfNumbersTraditional = 0

for number in numbers {

sumOfNumbersTraditional += number

print("Sum (Traditional Loop): \(sumOfNumbersTraditional)")

Output:

Sum (Traditional Loop): 80

Sum (Using reduce): 80

Sum (Using reduce with closure): 80

Sum of empty array: 0

16. How is List View differ from Recycler View? Explain with an example.

Both ListView and RecyclerView are Android UI components used to display scrollable lists of items. However,
RecyclerView is a more modern, flexible, and efficient successor to ListView.

Here's a breakdown of their differences:

Feature ListView RecyclerView

Less efficient, especially for long lists.


Highly efficient. Explicitly enforces view recycling
Efficiency Relies on convertView but sometimes re-
(ViewHolder pattern).
inflates views.

Can suffer from performance issues (jank,


Excellent performance due to intelligent view recycling
Performance stuttering) with complex items or large
and layout management.
datasets.

Limited flexibility. Primarily supports Highly flexible. Supports various layout managers (linear,
Flexibility
vertical scrolling and basic item layouts. grid, staggered grid) and animations.

Manual implementation required for Built-in and enforced through the


ViewHolder good performance (often forgotten or RecyclerView.ViewHolder class, promoting proper
done incorrectly). recycling.

Requires an explicit LayoutManager (e.g.,


Layout No explicit layout manager. Layout is
LinearLayoutManager, GridLayoutManager) to define
Manager handled internally.
how items are arranged.

6
Using ListView (Conceptual - requires BaseAdapter or ArrayAdapter):

Java

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

String[] names = {"Alice", "Bob", "Charlie", "David", "Eve"};

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

listView.setAdapter(adapter);

// In your activity_main.xml

<ListView

android:id="@+id/my_list_view"

android:layout_width="match_parent"

android:layout_height="match_parent" />

Using RecyclerView (Conceptual - requires RecyclerView.Adapter, ViewHolder, and LayoutManager):

Java

RecyclerView recyclerView = findViewById(R.id.my_recycler_view);

recyclerView.setLayoutManager(new LinearLayoutManager(this));

String[] names = {"Alice", "Bob", "Charlie", "David", "Eve"};

MyAdapter adapter = new MyAdapter(names);

recyclerView.setAdapter(adapter);

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/my_recycler_view"

android:layout_width="match_parent"

android:layout_height="match_parent" />

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

private String[] mNames;

public MyAdapter(String[] names) {

mNames = names; }

@NonNull

@Override

public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

View itemView = LayoutInflater.from(parent.getContext())

.inflate(android.R.layout.simple_list_item_1, parent, false);

7
return new MyViewHolder(itemView);

@Override

public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

holder.nameTextView.setText(mNames[position]);

@Override

public int getItemCount() {

return mNames.length;

public static class MyViewHolder extends RecyclerView.ViewHolder {

public TextView nameTextView;

public MyViewHolder(View view) {

super(view);

nameTextView = view.findViewById(android.R.id.text1); // Simple text view

17. How do you find a view element in your program? Which dialog boxes can you use in your android
application?

Finding a View Element in your Program:

In Android, you typically find a view element (like a Button, TextView, EditText, etc.) in your Java or Kotlin code
using its assigned ID. This is done after your activity's or fragment's layout XML has been inflated. The most
common method is findViewById().

Example:

Suppose you have this in your activity_main.xml:

XML

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

android:layout_width="match_parent"

8
android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:id="@+id/myTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, Android!" />

<Button

android:id="@+id/myButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me" />

</LinearLayout>

In your MainActivity.java (or Fragment):

Java

import androidx.appcompat.app.AppCompatActivity;

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

import android.view.View;import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private TextView myTextView; private Button myButton

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

myTextView = findViewById(R.id.myTextView);

myTextView.setText("Text changed programmatically!");

myButton = findViewById(R.id.myButton);

myButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this, "Button was clicked!", Toast.LENGTH_SHORT).show();

} }); }}

9
Which dialog boxes can you use in your Android application?

Android provides several types of dialog boxes (or dialogs) to display important information, ask for user input, or
confirm actions without taking the user away from the current activity. The most common ones include:

1. AlertDialog:

o Purpose: The most common and versatile dialog. It can display a title, a message, up to three
buttons (positive, negative, neutral), and a list of items (single-choice, multi-choice) or even a
custom layout.

o When to use: For alerts, confirmations, warnings, or simple choices.

o Example: "Are you sure you want to delete this item?", "Choose an option from the list."

Java

new AlertDialog.Builder(this)

.setTitle("Delete Item")

.setMessage("Are you sure you want to delete this item?")

.setPositiveButton("Delete", (dialog, which) -> {

Toast.makeText(this, "Item Deleted", Toast.LENGTH_SHORT).show();

})

.setNegativeButton("Cancel", null) // No action on cancel

.show();

2. DatePickerDialog:

o Purpose: Allows users to select a date.

o When to use: For picking birthdates, event dates, etc.

o Example: Selecting a reservation date.

Java

int year = 2025;

int month = 6; // July (0-indexed)

int day = 2;

new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDayOfMonth) -> {

String date = selectedDayOfMonth + "/" + (selectedMonth + 1) + "/" + selectedYear;

Toast.makeText(this, "Selected Date: " + date, Toast.LENGTH_SHORT).show();

}, year, month, day).show();

10
3. TimePickerDialog:

o Purpose: Allows users to select a time.

o When to use: For picking appointment times, alarm times, etc.

o Example: Setting a reminder time.

int hour = 12;

int minute = 45;

boolean is24HourFormat = true;

new TimePickerDialog(this, (view, selectedHour, selectedMinute) -> {

String time = String.format("%02d:%02d", selectedHour, selectedMinute);

Toast.makeText(this, "Selected Time: " + time, Toast.LENGTH_SHORT).show();

}, hour, minute, is24HourFormat).show();

4. ProgressDialog (Deprecated - Use ProgressBar or custom dialogs instead):

o Purpose (historical): To show indefinite or definite progress of an operation.

o When to use (Modern Android): It's deprecated. For modern applications, use a ProgressBar
directly within your layout or a custom DialogFragment that contains a ProgressBar. This avoids
blocking the UI thread.

5. DialogFragment (Recommended for custom dialogs):

o Purpose: The recommended way to display a modal UI in Android. It acts as a wrapper for
creating custom dialogs or presenting existing dialog types (like AlertDialog, DatePickerDialog)
within a fragment's lifecycle. This offers better lifecycle management and integration with
navigation components.

o When to use: For almost any dialog need, especially custom layouts, complex interactions, or
when integrating with FragmentManager.

11
18. Provided that a SQLite database named "College" with a table named Student with the following columns
(Roll as Integer, Name as Text and Address as Text). Develop an android application to connect to the database
and insert five student records and display the student information.

CollegeDbHelper.java (Database Helper):

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class CollegeDbHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "College.db";

public static final int DATABASE_VERSION = 1;

public static final String TABLE_STUDENT = "Student";

public static final String COLUMN_ROLL = "Roll";

public static final String COLUMN_NAME = "Name";

public static final String COLUMN_ADDRESS = "Address";

private static final String SQL_CREATE_STUDENT_TABLE =

"CREATE TABLE " + TABLE_STUDENT + " (" +

COLUMN_ROLL + " INTEGER PRIMARY KEY," +

COLUMN_NAME + " TEXT," +

COLUMN_ADDRESS + " TEXT)";

private static final String SQL_DELETE_STUDENT_TABLE =

"DROP TABLE IF EXISTS " + TABLE_STUDENT;

public CollegeDbHelper(Context context) {

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

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(SQL_CREATE_STUDENT_TABLE); }

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL(SQL_DELETE_STUDENT_TABLE);

onCreate(db); }}

12
MainActivity.java (Database Operations & Display):

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues; import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase; import android.os.Bundle;

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

import android.widget.TextView; import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private CollegeDbHelper dbHelper; private TextView displayTextView;

private Button operateButton; @Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

dbHelper = new CollegeDbHelper(this);

displayTextView = findViewById(R.id.displayTextView);

operateButton = findViewById(R.id.operateButton);

operateButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

insertFiveStudents(); displayStudentInformation(); } }); }

private void insertFiveStudents() {

SQLiteDatabase db = dbHelper.getWritableDatabase();

db.execSQL("DELETE FROM " + CollegeDbHelper.TABLE_STUDENT);

ContentValues values1 = new ContentValues();

values1.put(CollegeDbHelper.COLUMN_ROLL, 101);

values1.put(CollegeDbHelper.COLUMN_NAME, "Alice Johnson");

values1.put(CollegeDbHelper.COLUMN_ADDRESS, "123 Main St");

db.insert(CollegeDbHelper.TABLE_STUDENT, null, values1);

ContentValues values2 = new ContentValues();

values2.put(CollegeDbHelper.COLUMN_ROLL, 102);

13
values2.put(CollegeDbHelper.COLUMN_NAME, "Bob Williams");

values2.put(CollegeDbHelper.COLUMN_ADDRESS, "456 Oak Ave");

db.insert(CollegeDbHelper.TABLE_STUDENT, null, values2);

db.close();

Toast.makeText(this, "2 student records inserted.", Toast.LENGTH_SHORT).show(); }

private void displayStudentInformation() {

SQLiteDatabase db = dbHelper.getReadableDatabase(); // Get a readable database instance

String[] projection = {

CollegeDbHelper.COLUMN_ROLL,

CollegeDbHelper.COLUMN_NAME,

CollegeDbHelper.COLUMN_ADDRESS };

Cursor cursor = db.query(

CollegeDbHelper.TABLE_STUDENT,

projection, null, // selection (WHERE clause) null, // selectionArgs

null, // groupBy null, // having null // orderBy );

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("Student Records:\n\n");

while (cursor.moveToNext()) {

int roll = cursor.getInt(cursor.getColumnIndexOrThrow(CollegeDbHelper.COLUMN_ROLL));

String name = cursor.getString(cursor.getColumnIndexOrThrow(CollegeDbHelper.COLUMN_NAME));

String address = cursor.getString(cursor.getColumnIndexOrThrow(CollegeDbHelper.COLUMN_ADDRESS));

stringBuilder.append("Roll: ").append(roll)

.append(", Name: ").append(name) .append(", Address: ").append(address)

.append("\n"); }

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

displayTextView.setText(stringBuilder.toString());

}}

14
activity_main.xml:

XML

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

<LinearLayout 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:orientation="vertical"

android:padding="16dp"

tools:context=".MainActivity">

<Button

android:id="@+id/operateButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Insert &amp; Display Students"

android:layout_gravity="center_horizontal"

android:layout_marginBottom="16dp"/>

<ScrollView

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/displayTextView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Student information will appear here."

android:textSize="16sp"/>

</ScrollView>

</LinearLayout>

15
19. Develop an android application to calculate simple interest using a customize dialog box.

activity_main.xml:

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

<LinearLayout 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:orientation="vertical"

android:gravity="center"

android:padding="16dp"

tools:context=".MainActivity">

<TextView

android:id="@+id/resultTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Simple Interest: N/A"

android:textSize="20sp"

android:layout_marginBottom="30dp"/>

<Button

android:id="@+id/openDialogButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Calculate Simple Interest" /></LinearLayout>

16
dialog_simple_interest.xml:

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

<LinearLayout android:id="@+id/rateEditText"
xmlns:android="http://schemas.android.com/apk/re
android:layout_width="match_parent"
s/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Interest Rate (R) %"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:orientation="vertical"
android:padding="10dp"
android:padding="20dp">
android:layout_marginBottom="10dp"/>
<TextView
<EditText
android:layout_width="wrap_content"
android:id="@+id/timeEditText"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Calculate Simple Interest"
android:layout_height="wrap_content"
android:textSize="22sp"
android:hint="Time (T) in Years"
android:textStyle="bold"
android:inputType="numberDecimal"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:layout_marginBottom="20dp"/>
android:layout_marginBottom="20dp"/>
<EditText
<Button
android:id="@+id/principalEditText"
android:id="@+id/calculateButton"
android:layout_width="match_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:hint="Principal Amount (P)"
android:text="Calculate"
android:inputType="numberDecimal"
android:layout_gravity="center_horizontal" />
android:padding="10dp"
</LinearLayout>
android:layout_marginBottom="10dp"/>

17
SimpleInterestDialogFragment.java:

import android.app.AlertDialog; import android.app.Dialog;import android.os.Bundle;

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

import android.widget.EditText;import android.widget.Toast;import androidx.annotation.NonNull;

import androidx.annotation.Nullable;import androidx.fragment.app.DialogFragment;

public class SimpleInterestDialogFragment extends DialogFragment {

public interface SimpleInterestDialogListener {

void onInterestCalculated(double interest); }

private SimpleInterestDialogListener listener;

@Override

public void onAttach(@NonNull Context context) {

super.onAttach(context);

try {

listener = (SimpleInterestDialogListener) context;

} catch (ClassCastException e) {

throw new ClassCastException(context.toString() + " must implement SimpleInterestDialogListener"); } }

@NonNull

@Override

public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

LayoutInflater inflater = requireActivity().getLayoutInflater();

View view = inflater.inflate(R.layout.dialog_simple_interest, null);

EditText principalEditText = view.findViewById(R.id.principalEditText);

EditText rateEditText = view.findViewById(R.id.rateEditText);

EditText timeEditText = view.findViewById(R.id.timeEditText);

Button calculateButton = view.findViewById(R.id.calculateButton);

calculateButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

18
try {

double principal = Double.parseDouble(principalEditText.getText().toString());

double rate = Double.parseDouble(rateEditText.getText().toString());

double time = Double.parseDouble(timeEditText.getText().toString());

double simpleInterest = (principal * rate * time) / 100;

if (listener != null) {

listener.onInterestCalculated(simpleInterest); // Send result back to activity }

dismiss(); // Close the dialog

} catch (NumberFormatException e) {

Toast.makeText(getActivity(), "Please enter valid numbers.", Toast.LENGTH_SHORT).show();

} catch (Exception e) {

Toast.makeText(getActivity(), "An error occurred: " + e.getMessage(), Toast.LENGTH_SHORT).show();


} } }); builder.setView(view); return builder.create(); }}

MainActivity.java:

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

import android.widget.Button; import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements


SimpleInterestDialogFragment.SimpleInterestDialogListener {

private TextView resultTextView; @Override

protected void onCreate(Bundle savedInstanceState) {

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

resultTextView = findViewById(R.id.resultTextView); Button openDialogButton =


findViewById(R.id.openDialogButton);

openDialogButton.setOnClickListener(new View.OnClickListener() { @Override

public void onClick(View v) {

SimpleInterestDialogFragment dialog = new SimpleInterestDialogFragment();

dialog.show(getSupportFragmentManager(), "simpleInterestDialog"); } }); }

@Override

public void onInterestCalculated(double interest) {

resultTextView.setText(String.format("Simple Interest: %.2f", interest)); } }

19
20. Develop an android application to input your Name, Age, gender and other personal information. Pass and
display this information in another activity.

activity_main.xml (For input):

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

<LinearLayout 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:orientation="vertical"

android:padding="20dp"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Enter Your Personal Information"

android:textSize="24sp"

android:textStyle="bold"

android:layout_gravity="center_horizontal"

android:layout_marginBottom="30dp"/>

<EditText

android:id="@+id/nameEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Name"

android:inputType="textPersonName"

android:padding="12dp"

android:layout_marginBottom="15dp"/>

<EditText

android:id="@+id/ageEditText"

android:layout_width="match_parent"

20
android:layout_height="wrap_content"

android:hint="Age"

android:inputType="number"

android:padding="12dp"

android:layout_marginBottom="15dp"/>

<EditText

android:id="@+id/genderEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Gender (e.g., Male/Female/Other)"

android:inputType="textCapWords"

android:padding="12dp"

android:layout_marginBottom="15dp"/>

<EditText

android:id="@+id/otherInfoEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Other Information (e.g., Hobby)"

android:inputType="textMultiLine"

android:lines="3" android:gravity="top"

android:padding="12dp"

android:layout_marginBottom="30dp"/>

<Button

android:id="@+id/submitButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Information"

android:layout_gravity="center_horizontal"/>

</LinearLayout>

21
MainActivity.java (For input and sending data):

import androidx.appcompat.app.AppCompatActivity; otherInfoEditText =


findViewById(R.id.otherInfoEditText);
import android.content.Intent;
submitButton =
import android.os.Bundle;
findViewById(R.id.submitButton);
import android.view.View;
submitButton.setOnClickListener(new
import android.widget.Button; View.OnClickListener() {

import android.widget.EditText; @Override

import android.widget.Toast; public void onClick(View v) {

public class MainActivity extends AppCompatActivity String name =


{ nameEditText.getText().toString().trim();

private EditText nameEditText, ageEditText, String age =


genderEditText, otherInfoEditText; ageEditText.getText().toString().trim();

private Button submitButton; String gender =


genderEditText.getText().toString().trim();
public static final String EXTRA_NAME =
"com.example.yourapp.NAME"; String otherInfo =
otherInfoEditText.getText().toString().trim();
public static final String EXTRA_AGE =
"com.example.yourapp.AGE"; if (name.isEmpty() || age.isEmpty() ||
gender.isEmpty()) {
public static final String EXTRA_GENDER =
"com.example.yourapp.GENDER"; Toast.makeText(MainActivity.this, "Please
fill in Name, Age, and Gender.",
public static final String EXTRA_OTHER_INFO = Toast.LENGTH_SHORT).show();
"com.example.yourapp.OTHER_INFO";
return; }
@Override
Intent intent = new Intent(MainActivity.this,
protected void onCreate(Bundle DisplayInfoActivity.class);
savedInstanceState) {
intent.putExtra(EXTRA_NAME, name);
super.onCreate(savedInstanceState);
intent.putExtra(EXTRA_AGE, age);
setContentView(R.layout.activity_main);
intent.putExtra(EXTRA_GENDER, gender);
nameEditText =
findViewById(R.id.nameEditText); intent.putExtra(EXTRA_OTHER_INFO,
otherInfo); // Other info might be empty, that's fine
ageEditText = findViewById(R.id.ageEditText);
startActivity(intent); } }); } }
genderEditText =
findViewById(R.id.genderEditText);

22
activity_display_info.xml (For displaying data):

<?xml version="1.0" encoding="utf-8"?> android:layout_width="wrap_content"

<LinearLayout android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
android:textSize="18sp"
s/android"
android:layout_marginBottom="10dp"
xmlns:tools="http://schemas.android.com/tools"
android:text="Age: "/>
android:layout_width="match_parent"
<TextView
android:layout_height="match_parent"
android:id="@+id/displayGenderTextView"
android:orientation="vertical"
android:layout_width="wrap_content"
android:padding="20dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="18sp"
tools:context=".DisplayInfoActivity">
android:layout_marginBottom="10dp"
<TextView
android:text="Gender: "/>
android:layout_width="wrap_content"
<TextView
android:layout_height="wrap_content"
android:id="@+id/displayOtherInfoTextView"
android:text="Your Submitted Information"
android:layout_width="wrap_content"
android:textSize="24sp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="18sp"
android:layout_marginBottom="30dp"/>
android:layout_marginBottom="20dp"
<TextView
android:text="Other Info: "/>
android:id="@+id/displayNameTextView"
<Button
android:layout_width="wrap_content"
android:id="@+id/goBackButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="18sp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Go Back"/>
android:text="Name: "/>
</LinearLayout>
<TextView

android:id="@+id/displayAgeTextView"

23
DisplayInfoActivity.java (For receiving and displaying data):

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.Button;

import android.widget.TextView;

public class DisplayInfoActivity extends AppCompatActivity {

private TextView displayNameTextView, displayAgeTextView, displayGenderTextView, displayOtherInfoTextView;

private Button goBackButton; @Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_display_info);

displayNameTextView = findViewById(R.id.displayNameTextView);

displayAgeTextView = findViewById(R.id.displayAgeTextView);

displayGenderTextView = findViewById(R.id.displayGenderTextView);

displayOtherInfoTextView = findViewById(R.id.displayOtherInfoTextView);

goBackButton = findViewById(R.id.goBackButton);

Intent intent = getIntent();

String name = intent.getStringExtra(MainActivity.EXTRA_NAME);

String age = intent.getStringExtra(MainActivity.EXTRA_AGE);

String gender = intent.getStringExtra(MainActivity.EXTRA_GENDER);

String otherInfo = intent.getStringExtra(MainActivity.EXTRA_OTHER_INFO);

// Display the received data

displayNameTextView.setText("Name: " + (name != null ? name : "N/A"));

displayAgeTextView.setText("Age: " + (age != null ? age : "N/A"));

displayGenderTextView.setText("Gender: " + (gender != null ? gender : "N/A"));

displayOtherInfoTextView.setText("Other Info: " + (otherInfo != null && !otherInfo.isEmpty() ? otherInfo : "Not


provided"));

goBackButton.setOnClickListener(v -> finish()); // Go back to the previous activity } }

24
AndroidManifest.xml:

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

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

package="com.example.yourapp"> <application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/Theme.YourApp">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity android:name=".DisplayInfoActivity"

android:exported="false"> </activity>

</application>

</manifest>

25
12. What is a surface manager library? How DVM is different from ART?

A Surface Manager library in Android is a critical component within the Native Libraries layer of the Android
architecture. It's responsible for managing the display surface of the device. When applications draw content (text,
images, UI elements), they draw onto "surfaces." The Surface Manager then composites (combines) these various
surfaces from different applications (e.g., your app, the system status bar, the navigation bar) into a single buffer
that is then sent to the device's display hardware. It ensures that applications can draw efficiently without
interfering with each other and handles aspects like screen rotation and scaling.

Difference between DVM (Dalvik Virtual Machine) and ART (Android Runtime):

Feature DVM (Dalvik Virtual Machine) ART (Android Runtime)

JIT (Just-In-Time) Compilation: Compiles code AOT (Ahead-Of-Time) Compilation: Compiles code
Compilation
at runtime, each time the app is launched. into native machine code during app installation.

Execution Slower startup times and potentially slower Faster app startup and smoother execution once
Speed execution during runtime due to JIT overhead. installed, as compilation is done beforehand.

Can consume more battery due to continuous Generally better battery life as compilation is a
Battery Life
JIT compilation. one-time event during installation.

Installation Faster app installation as less compilation Slower app installation because the entire app
Time occurs initially. code is compiled to native code.

Occupies less storage space after installation Occupies more storage space on the device due to
Storage Space
as compiled code is generated dynamically. storing pre-compiled native code.

Memory Can have a higher memory footprint during Generally has a lower memory footprint during
Footprint runtime. runtime.

13. What are important attributes used in Absolute Layout? Develop a simple calculator application with two
input fields for inputting numbers and two buttons for performing multiplication and division and display the
result in TextView using Absolute Layout.

Note: AbsoluteLayout is deprecated in Android API level 3 and is highly discouraged for modern Android
development. It offers very little flexibility and makes it incredibly difficult to create layouts that adapt to different
screen sizes and orientations. Developers should use ConstraintLayout, LinearLayout, RelativeLayout, or
FrameLayout instead.

However, to answer the question as asked, important attributes used in AbsoluteLayout are:

• android:layout_x: Specifies the X-coordinate (horizontal position) of the view within the AbsoluteLayout.
The value is typically in density-independent pixels (dp).

• android:layout_y: Specifies the Y-coordinate (vertical position) of the view within the AbsoluteLayout. The
value is typically in density-independent pixels (dp).

These attributes position children elements precisely based on pixel coordinates relative to the top-left corner of
the AbsoluteLayout.

26
Simple Calculator Application using Deprecated AbsoluteLayout (Conceptual Code):

activity_main.xml:

XML <Button

<?xml version="1.0" encoding="utf-8"?> android:id="@+id/multiplyButton"

<AbsoluteLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
android:layout_height="wrap_content"
s/android"
android:layout_x="50dp"
xmlns:tools="http://schemas.android.com/tools"
android:layout_y="200dp"
android:layout_width="match_parent"
android:text="Multiply" />
android:layout_height="match_parent"
<Button
tools:context=".MainActivity">
android:id="@+id/divideButton"
<EditText
android:layout_width="wrap_content"
android:id="@+id/num1EditText"
android:layout_height="wrap_content"
android:layout_width="200dp"
android:layout_x="180dp"
android:layout_height="wrap_content"
android:layout_y="200dp"
android:layout_x="50dp"
android:text="Divide" />
android:layout_y="50dp"
<TextView
android:hint="Number 1"
android:id="@+id/resultTextView"
android:inputType="numberDecimal" />
android:layout_width="wrap_content"
<EditText
android:layout_height="wrap_content"
android:id="@+id/num2EditText"
android:layout_x="50dp"
android:layout_width="200dp"
android:layout_y="280dp"
android:layout_height="wrap_content"
android:text="Result: "
android:layout_x="50dp"
android:textSize="20sp"
android:layout_y="120dp"
android:textStyle="bold" />
android:hint="Number 2"
</AbsoluteLayout>
android:inputType="numberDecimal" />

27
MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; divideButton.setOnClickListener(new


View.OnClickListener() { @Override
import android.os.Bundle;
public void onClick(View v) {
import android.view.View;
calculateResult("/"); } }); }
import android.widget.Button;
private void calculateResult(String operation) {
import android.widget.EditText;
String num1Str =
import android.widget.TextView;
num1EditText.getText().toString();
import android.widget.Toast;
String num2Str =
public class MainActivity extends AppCompatActivity num2EditText.getText().toString();
{
if (num1Str.isEmpty() || num2Str.isEmpty()) {
private EditText num1EditText, num2EditText;
Toast.makeText(this, "Please enter both
private Button multiplyButton, divideButton; numbers.", Toast.LENGTH_SHORT).show();

private TextView resultTextView; @Override return; } try {

protected void onCreate(Bundle double num1 =


savedInstanceState) { Double.parseDouble(num1Str);

super.onCreate(savedInstanceState); double num2 =


Double.parseDouble(num2Str);
setContentView(R.layout.activity_main);
double result = 0;
num1EditText =
findViewById(R.id.num1EditText); if (operation.equals("*")) {

num2EditText = result = num1 * num2;


findViewById(R.id.num2EditText);
} else if (operation.equals("/")) {
multiplyButton =
if (num2 == 0) {
findViewById(R.id.multiplyButton);
Toast.makeText(this, "Cannot divide by
divideButton = findViewById(R.id.divideButton);
zero.", Toast.LENGTH_SHORT).show();
resultTextView =
return; }
findViewById(R.id.resultTextView);
result = num1 / num2; }
multiplyButton.setOnClickListener(new
View.OnClickListener() { @Override resultTextView.setText("Result: " +
String.format("%.2f", result));
public void onClick(View v) {
} catch (NumberFormatException e) {
calculateResult("*"); } });
Toast.makeText(this, "Invalid number format.",
Toast.LENGTH_SHORT).show(); } }}

28
14. Android Application for Volume Calculation using Two Fragments:

activity_main.xml (Main Activity Layout):

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

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

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

android:id="@+id/fragment_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"> </FrameLayout>

29
fragment_input.xml (Input Fragment Layout):

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

<LinearLayout android:id="@+id/widthEditText"
xmlns:android="http://schemas.android.com/apk/re
android:layout_width="match_parent"
s/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Width"
android:layout_height="match_parent"
android:inputType="numberDecimal"
android:orientation="vertical"
android:padding="12dp"
android:padding="20dp"
android:layout_marginBottom="15dp"/>
android:gravity="center_horizontal"
<EditText
android:background="#E0F7FA"> <TextView
android:id="@+id/heightEditText"
android:layout_width="wrap_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Box Dimensions"
android:hint="Height"
android:textSize="24sp"
android:inputType="numberDecimal"
android:textStyle="bold"
android:padding="12dp"
android:layout_marginBottom="30dp"/>
android:layout_marginBottom="30dp"/>
<EditText
<Button
android:id="@+id/lengthEditText"
android:id="@+id/calculateVolumeButton"
android:layout_width="match_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:hint="Length"
android:text="Calculate Volume" />
android:inputType="numberDecimal"
</LinearLayout>
android:padding="12dp"

android:layout_marginBottom="15dp"/>

30
fragment_result.xml (Result Fragment Layout):

<?xml version="1.0" encoding="utf-8"?> android:id="@+id/volumeResultTextView"

<LinearLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
android:layout_height="wrap_content"
s/android"
android:text="Volume: "
android:layout_width="match_parent"
android:textSize="22sp"
android:layout_height="match_parent"
android:textStyle="bold"
android:orientation="vertical"
android:textColor="@android:color/black"/>
android:padding="20dp"
<Button
android:gravity="center"
android:id="@+id/backToInputButton"
android:background="#C8E6C9"> <TextView
android:layout_width="wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Go Back"
android:text="Calculated Volume"
android:layout_marginTop="50dp"/>
android:textSize="24sp"

android:textStyle="bold"
</LinearLayout>
android:layout_marginBottom="30dp"/>

<TextView

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.fragment.app.FragmentManager;

import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements InputFragment.OnVolumeCalculatedListener {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()

31
.add(R.id.fragment_container, new InputFragment())

.commit(); } }

@Override

public void onVolumeCalculated(double length, double width, double height) {

ResultFragment resultFragment = new ResultFragment();

Bundle args = new Bundle();

args.putDouble(ResultFragment.ARG_LENGTH, length);

args.putDouble(ResultFragment.ARG_WIDTH, width);

args.putDouble(ResultFragment.ARG_HEIGHT, height);

resultFragment.setArguments(args);

getSupportFragmentManager().beginTransaction()

.replace(R.id.fragment_container, resultFragment)

.addToBackStack(null)

.commit(); }

public void goBackToInput() {

getSupportFragmentManager().popBackStack(); }}

InputFragment.java:

import android.content.Context; import android.view.View;

import android.os.Bundle; import android.view.ViewGroup;

import androidx.annotation.NonNull; import android.widget.Button;

import androidx.annotation.Nullable; import android.widget.EditText;

import androidx.fragment.app.Fragment; import android.widget.Toast;

import android.view.LayoutInflater;

public class InputFragment extends Fragment {

private EditText lengthEditText, widthEditText, heightEditText;

private Button calculateVolumeButton;

public interface OnVolumeCalculatedListener {

void onVolumeCalculated(double length, double width, double height); }

32
private OnVolumeCalculatedListener listener;

@Override

public void onAttach(@NonNull Context context) {

super.onAttach(context);

if (context instanceof OnVolumeCalculatedListener) {

listener = (OnVolumeCalculatedListener) context; } else {

throw new RuntimeException(context.toString()

+ " must implement OnVolumeCalculatedListener"); } }

@Override

public void onDetach() { super.onDetach(); listener = null; }

@Nullable @Override

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_input, container, false);

lengthEditText = view.findViewById(R.id.lengthEditText);

widthEditText = view.findViewById(R.id.widthEditText);

heightEditText = view.findViewById(R.id.heightEditText);

calculateVolumeButton = view.findViewById(R.id.calculateVolumeButton);

calculateVolumeButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String lengthStr = lengthEditText.getText().toString();

String widthStr = widthEditText.getText().toString();

String heightStr = heightEditText.getText().toString();

if (lengthStr.isEmpty() || widthStr.isEmpty() || heightStr.isEmpty()) {

Toast.makeText(getActivity(), "Please enter all dimensions.", Toast.LENGTH_SHORT).show();

return; } try {

double length = Double.parseDouble(lengthStr);

double width = Double.parseDouble(widthStr);

33
double height = Double.parseDouble(heightStr);

if (listener != null) {

listener.onVolumeCalculated(length, width, height); // Send data to Activity }

} catch (NumberFormatException e) {

Toast.makeText(getActivity(), "Invalid number format.", Toast.LENGTH_SHORT).show();

} } });

return view; }}

ResultFragment.java:

import android.os.Bundle; public class ResultFragment extends Fragment {

import androidx.annotation.NonNull;

import androidx.annotation.Nullable; public static final String ARG_LENGTH = "length";

import androidx.fragment.app.Fragment; public static final String ARG_WIDTH = "width";

import android.view.LayoutInflater; public static final String ARG_HEIGHT = "height";

import android.view.View;

import android.view.ViewGroup; private TextView volumeResultTextView;

import android.widget.Button; private Button backToInputButton

import android.widget.TextView; @Nullable @Override

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_result, container, false);

volumeResultTextView = view.findViewById(R.id.volumeResultTextView);

backToInputButton = view.findViewById(R.id.backToInputButton);

Bundle args = getArguments();

if (args != null) {

double length = args.getDouble(ARG_LENGTH, 0.0); double height = args.getDouble(ARG_HEIGHT,


0.0);
double width = args.getDouble(ARG_WIDTH,
0.0); double volume = length * width * height;

volumeResultTextView.setText(String.format("Volume: %.2f", volume));

} else {

34
volumeResultTextView.setText("Volume: Error (No data)"); }

backToInputButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (getActivity() instanceof MainActivity) {

((MainActivity) getActivity()).goBackToInput(); } } });

return view; }}

15. What is Toast? Develop an android application to create an alert dialog to input any number and then
calculate the factorial of the number and display the result in Toast.

A Toast is a small, transient, non-interactive pop-up message that appears briefly on the screen, typically at the
bottom, to provide feedback about an operation. It's designed to be unobtrusive and automatically disappears after
a short period. It's commonly used for simple notifications like "Email sent," "Settings saved," or "Invalid input."

Key Characteristics of Toast:

• Non-blocking: It does not prevent user interaction with the current activity.

• Ephemeral: It appears for a short duration and then fades away.

• Informative: Provides quick feedback without requiring user action.Non-focusable: Users cannot tap on it.

Android Application: Factorial with AlertDialog and Toast:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> android:layout_height="wrap_content"

<LinearLayout android:text="Factorial Calculator"


xmlns:android="http://schemas.android.com/apk/re
android:textSize="24sp"
s/android"
android:textStyle="bold"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginBottom="30dp"/>
android:layout_width="match_parent"
<Button
android:layout_height="match_parent"
android:id="@+id/openFactorialDialogButton"
android:orientation="vertical"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Calculate Factorial" />
tools:context=".MainActivity">
</LinearLayout>
<TextView

android:layout_width="wrap_content"

35
MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; import android.view.View;

import android.app.AlertDialog; import android.widget.Button;

import android.os.Bundle; import android.widget.EditText;

import android.text.InputType; import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Button openFactorialDialogButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

openFactorialDialogButton = findViewById(R.id.openFactorialDialogButton);

openFactorialDialogButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

showFactorialInputDialog(); } }); }

private void showFactorialInputDialog() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Enter a Number for Factorial");

final EditText input = new EditText(this);

input.setInputType(InputType.TYPE_CLASS_NUMBER);

builder.setView(input);

builder.setPositiveButton("Calculate", (dialog, which) -> {

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

if (numStr.isEmpty()) {

Toast.makeText(MainActivity.this, "Please enter a number.", Toast.LENGTH_SHORT).show();

return; }try {

int number = Integer.parseInt(numStr);

if (number < 0) {

36
Toast.makeText(MainActivity.this, "Factorial is not defined for negative numbers.",
Toast.LENGTH_LONG).show();

} else if (number > 20) { // Factorial grows very fast, avoid overflow

Toast.makeText(MainActivity.this, "Number too large for accurate calculation.",


Toast.LENGTH_LONG).show();

} else {

long factorial = calculateFactorial(number);

Toast.makeText(MainActivity.this, "Factorial of " + number + " is: " + factorial,


Toast.LENGTH_LONG).show(); }

} catch (NumberFormatException e) {

Toast.makeText(MainActivity.this, "Invalid number entered.", Toast.LENGTH_SHORT).show();

} });

builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());

builder.show(); }

private long calculateFactorial(int n) {

if (n == 0 || n == 1) {

return 1; }

long result = 1;

for (int i = 2; i <= n; i++) {

result *= i; }

return result; }}

16. What are different data types supported by SQLite? How to decode JSON data in an android application?
Explain with a suitable example.

SQLite uses a more flexible, dynamic type system compared to traditional relational databases. Instead of strict
data types for columns, it uses a "typeless" model where the data type of a value is associated with the value itself,
not necessarily its container column. However, it does define storage classes for values and type affinities for
columns which guide how data is stored and interpreted.

SQLite Storage Classes (the actual types of values stored):

1. NULL: The value is a NULL value.

2. INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of
the value.

3. REAL: The value is a floating point value, stored as an 8-byte IEEE floating point number.

37
4. TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).

5. BLOB: The value is a blob of data, stored exactly as it was input.

Column Type Affinities (suggested types for columns, influencing data conversion):

When you declare a column with a type, SQLite assigns it a "type affinity." This affinity suggests the preferred
storage class for values in that column.

• TEXT Affinity: Columns with TEXT affinity store TEXT data. If you insert a numeric value, it's converted to
text.

o Examples: TEXT, CLOB, VARCHAR, NCHAR, VARYING CHARACTER

• NUMERIC Affinity: Columns with NUMERIC affinity can store INTEGER, REAL, or BLOB data. Dates and
booleans are often stored as NUMERIC.

o Examples: NUMERIC, BOOLEAN, DATE, DATETIME

• INTEGER Affinity: Similar to NUMERIC but prioritizes INTEGER storage. If you declare a column with
INTEGER PRIMARY KEY, it gains INTEGER affinity.

o Examples: INT, INTEGER, TINYINT, SMALLINT, MEDIUMINT, BIGINT, UNSIGNED BIG INT

• REAL Affinity: Prioritizes REAL storage.

o Examples: REAL, DOUBLE, DOUBLE PRECISION, FLOAT

• BLOB Affinity: No type conversion occurs. Data is stored exactly as is.

o Example: BLOB

How to decode JSON data in an Android application?

In Android, JSON (JavaScript Object Notation) data is typically decoded (parsed) using the org.json package (built-
in) or external libraries like Gson (Google) or Jackson. Gson is widely preferred for its simplicity and efficiency,
especially for converting JSON to Java objects and vice-versa.

Example: Decoding JSON using Gson Library

Let's say you receive the following JSON string from a web API:

JSON

{ "midterm": 85,

"studentId": 101, "final": 92

"name": "Alice Johnson", },

"course": "Mobile Programming", "subjects": ["Android", "iOS", "DBMS"]

"grades": { }

38
17. What do you mean by View hierarchy in iOS programming? Write a swift program to find the sum of all
elements of a 1-D array.

in a previous response (Question 15 from the first set

View Hierarchy in iOS Programming:

In iOS programming, a view hierarchy refers to the tree-like structure of UIView objects (and their subclasses) that
make up an application's user interface. At its core, the UI is composed of individual views, and these views are
organized in a parent-child relationship.

• UIView: The fundamental building block for UI in iOS. It defines a rectangular area on the screen and is
responsible for drawing content, handling events, and managing subviews.

• Parent-Child Relationship: A view can contain multiple "subviews" (its children). The subviews are
positioned and sized relative to their parent's coordinate system. The parent view is responsible for
managing its subviews.

• Root View: Every screen (or UIViewController's view) has a single root view, which is the top-level view in
its hierarchy. All other UI elements are subviews, directly or indirectly, of this root view.

• Drawing Order: Views are drawn from back to front. The first subview added is drawn first (at the back),
and subsequent subviews are drawn on top of it.

• Event Handling: User interactions (touches, gestures) are typically handled starting from the outermost
view and are passed down the hierarchy until a view can handle them (or passed up the hierarchy if not
handled by a subview).

Example of a Simple View Hierarchy:

Imagine a screen in an iOS app:

UIWindow (Top-level container for all views)

UIViewController's View (The root view of the screen)

/ \

UILabel UIButton

/ \

UIImageView TextField

Why is it important?

• Layout and Positioning: Views are laid out relative to their parent, making it easier to arrange complex
UIs.

• Event Delivery: Rendering Efficiency.Modularity: You can encapsulate UI components (e.g., a custom
login form) as separate view hierarchies that can be added or removed dynamically.

39
18. What is the difference between ArrayAdapter and CursorAdapter? Develop an android application to display
the application name with logo (i.e., YouTube, Facebook, Twitter, Tiktok, Snapchat, Telegram etc.) in Grid View
and display their site in another activity when a Grid View item is clicked.

Feature ArrayAdapter CursorAdapter

Works directly with data retrieved from a Cursor


Data Works with arrays or ArrayLists of objects (e.g.,
(typically from a SQLite database or
Source String[], List<MyObject>).
ContentProvider).

Lazily loads data from the Cursor as items scroll into


Data Loads all data into memory at once (or as
view, making it efficient for large datasets from
Loading needed for a List).
databases.

Data Requires you to define how each object in the Automatically maps columns from the Cursor to
Mapping array maps to the views in the list item layout. views in the list item layout (via bindView).

Automatically updates when the underlying Cursor


Data To update the UI, you modify the array/list and
changes (e.g., via ContentObserver). You might call
Updates call notifyDataSetChanged().
changeCursor() to swap to a new cursor.

Less efficient for very large datasets from


More efficient for database-backed lists as it avoids
Efficiency databases as it might involve converting Cursor
explicit data mapping and conversion.
data to objects first.

Common Simple lists, static data, small dynamic lists, data Displaying data from SQLite databases or
Use not from databases. ContentProviders.

Android Application: GridView with App Names and Logos, Click to View Site:

AppInfo.java (Data Model):

public class AppInfo { this.url = url; }

private String name; public String getName() {

private int logoResId; return name; }

private String url;

public AppInfo(String name, int logoResId, String public int getLogoResId() {


url) {
return logoResId; }
this.name = name;
public String getUrl() {
this.logoResId = logoResId;
return url; }}

40
AppGridAdapter.java (Custom Adapter):

import android.content.Context; this.appList = appList;

import android.view.LayoutInflater; this.inflater = LayoutInflater.from(context); }

import android.view.View; @Override

import android.view.ViewGroup; public int getCount() {

import android.widget.BaseAdapter; return appList.size(); }

import android.widget.ImageView; @Override

import android.widget.TextView; public Object getItem(int position) {

import java.util.List; return appList.get(position); }

public class AppGridAdapter extends BaseAdapter { @Override

private Context context; public long getItemId(int position) {

private List<AppInfo> appList; return position; }

private LayoutInflater inflater; @Override

public AppGridAdapter(Context context, public View getView(int position, View


List<AppInfo> appList) { convertView, ViewGroup parent) {

this.context = context; ViewHolder holder;

if (convertView == null) {

convertView = inflater.inflate(R.layout.grid_item_app, parent, false);

holder = new ViewHolder();

holder.appLogoImageView = convertView.findViewById(R.id.appLogoImageView);

holder.appNameTextView = convertView.findViewById(R.id.appNameTextView);

convertView.setTag(holder);

} else { holder = (ViewHolder) convertView.getTag(); }

AppInfo app = appList.get(position);

holder.appLogoImageView.setImageResource(app.getLogoResId());

holder.appNameTextView.setText(app.getName());

return convertView; }

static class ViewHolder {

ImageView appLogoImageView;

TextView appNameTextView; }}

41
grid_item_app.xml (Layout for each GridView item):

<?xml version="1.0" encoding="utf-8"?> android:layout_width="60dp"

<LinearLayout android:layout_height="60dp"
xmlns:android="http://schemas.android.com/apk/re
android:scaleType="fitCenter"
s/android"
android:layout_marginBottom="4dp"
android:layout_width="wrap_content"
android:src="@mipmap/ic_launcher"/>
android:layout_height="wrap_content"
<TextView
android:orientation="vertical"
android:id="@+id/appNameTextView"
android:padding="8dp"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"

android:text="App Name"
android:background="@drawable/grid_item_backgr
ound" android:textSize="14sp"

android:layout_margin="4dp"> android:textStyle="bold"

<ImageView android:textColor="@android:color/black"/>

android:id="@+id/appLogoImageView" </LinearLayout>

drawable/grid_item_background.xml (Optional, for visual feedback):

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

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

<item android:state_pressed="true"> <corners android:radius="8dp"/>

<shape android:shape="rectangle">

<solid android:color="#E0E0E0"/> <stroke android:width="1dp" android:color="#BBBBBB"/>

</shape> </item>

<item>

<shape android:shape="rectangle">

<corners android:radius="8dp"/>

<solid android:color="#FFFFFF"/> <stroke android:width="1dp" android:color="#DDDDDD"/>

</shape> </item>

</selector>

42
activity_main.xml (Main Activity Layout):

<?xml version="1.0" encoding="utf-8"?> android:textStyle="bold"

<LinearLayout android:layout_gravity="center_horizontal"
xmlns:android="http://schemas.android.com/apk/re
android:layout_marginBottom="20dp"/>
s/android"
<GridView
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/appGridView"
android:layout_width="match_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:numColumns="auto_fit"
android:padding="16dp"
android:columnWidth="100dp"
tools:context=".MainActivity">
android:verticalSpacing="8dp"
<TextView
android:horizontalSpacing="8dp"
android:layout_width="wrap_content"
android:stretchMode="columnWidth"
android:layout_height="wrap_content"
android:gravity="center" />
android:text="Popular Applications"
</LinearLayout>
android:textSize="24sp"

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; import java.util.List;

import android.content.Intent; public class MainActivity extends AppCompatActivity


{
import android.os.Bundle;
private GridView appGridView;
import android.view.View;
private List<AppInfo> appList;
import android.widget.AdapterView;
public static final String EXTRA_URL =
import android.widget.GridView;
"com.example.yourapp.URL";
import java.util.ArrayList;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

appGridView = findViewById(R.id.appGridView);

populateAppList();

43
AppGridAdapter adapter = new AppGridAdapter(this, appList);

appGridView.setAdapter(adapter);

appGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

AppInfo clickedApp = appList.get(position);

Intent intent = new Intent(MainActivity.this, WebViewActivity.class);

intent.putExtra(EXTRA_URL, clickedApp.getUrl());

startActivity(intent); } }); }

private void populateAppList() {

appList = new ArrayList<>();

appList.add(new AppInfo("YouTube", R.drawable.youtube_logo, "https://www.youtube.com"));

appList.add(new AppInfo("Facebook", R.drawable.facebook_logo, "https://www.facebook.com"));

appList.add(new AppInfo("Twitter", R.drawable.twitter_logo, "https://twitter.com"));

appList.add(new AppInfo("TikTok", R.drawable.tiktok_logo, "https://www.tiktok.com"));

appList.add(new AppInfo("Snapchat", R.drawable.snapchat_logo, "https://www.snapchat.com"));

appList.add(new AppInfo("Telegram", R.drawable.telegram_logo, "https://telegram.org")); }}

19. Why we use API in Android? Provided that a SQLite database named "Hospital" with table named Doctor
with the following columns (Did as Integer, Dname as Text, and Specialization as Text and Experience as Real).
Develop an Android application to connect to the database and insert records of Doctor and display the Doctor
information whose experience is less than 5.5 years.

Why we use API in Android?

In Android development, "API" (Application Programming Interface) has a few contexts:

1. Android Framework APIs: This is the most common meaning. The Android platform itself provides a vast
set of APIs that developers use to build applications. These APIs are the "building blocks" that allow your
app to interact with the device's hardware, operating system services, and other applications.

Purpose:

▪ Abstraction: They hide the complex low-level details of how Android works, allowing
developers to focus on application logic. For example, you don't need to know how the
camera hardware works internally; you just use the Camera API.

44
▪ Standardization: They provide a consistent way for developers to interact with system
features, ensuring apps behave predictably across different devices and Android
versions.

▪ Functionality Access: They grant access to essential device functionalities like GPS,
camera, networking, storage, UI elements (Activities, Fragments, Views), notifications,
etc.

▪ Reusability: Developers reuse pre-built components and functionalities provided by the


API, saving time and effort.

▪ Interoperability: They enable different components of an app, or even different apps, to


communicate and share data effectively (e.g., Content Providers API).

2. Web/Third-Party APIs: These are interfaces provided by external services (like Google Maps API, Twitter
API, weather APIs, custom backend APIs) that allow your Android application to communicate with these
services over the internet.

o Purpose: To integrate external data and functionalities into your app (e.g., fetching weather data,
displaying maps, logging in with social accounts).

Android Application: Hospital Database (Doctor Records)

HospitalDbHelper.java (Database Helper):

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class HospitalDbHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Hospital.db";

public static final int DATABASE_VERSION = 1;

public static final String TABLE_DOCTOR = "Doctor";

public static final String COLUMN_DID = "Did"; // Doctor ID

public static final String COLUMN_DNAME = "Dname"; // Doctor Name

public static final String COLUMN_SPECIALIZATION = "Specialization";

public static final String COLUMN_EXPERIENCE = "Experience"; // In years (Real type)

private static final String SQL_CREATE_DOCTOR_TABLE =

"CREATE TABLE " + TABLE_DOCTOR + " (" +

COLUMN_DID + " INTEGER PRIMARY KEY," +

45
COLUMN_DNAME + " TEXT," +

COLUMN_SPECIALIZATION + " TEXT," +

COLUMN_EXPERIENCE + " REAL)";

private static final String SQL_DELETE_DOCTOR_TABLE =

"DROP TABLE IF EXISTS " + TABLE_DOCTOR;

public HospitalDbHelper(Context context) {

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

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(SQL_CREATE_DOCTOR_TABLE); }

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL(SQL_DELETE_DOCTOR_TABLE);

onCreate(db); }}

MainActivity.java (Database Operations & Display):

import androidx.appcompat.app.AppCompatActivity; protected void onCreate(Bundle


savedInstanceState) {
import android.content.ContentValues;
super.onCreate(savedInstanceState);
import android.database.Cursor;
setContentView(R.layout.activity_main);
import android.database.sqlite.SQLiteDatabase;
dbHelper = new HospitalDbHelper(this);
import android.os.Bundle;
displayTextView =
import android.view.View;
findViewById(R.id.displayTextView);
import android.widget.Button;
operateButton =
import android.widget.TextView; findViewById(R.id.operateButton);

import android.widget.Toast;

public class MainActivity extends AppCompatActivity operateButton.setOnClickListener(new


{ View.OnClickListener() {

private HospitalDbHelper dbHelper; @Override

private TextView displayTextView; public void onClick(View v) {

private Button operateButton; insertDoctorRecords();

@Override displayDoctorsWithLessExperience(); } });

46
private void insertDoctorRecords() {

SQLiteDatabase db = dbHelper.getWritableDatabase();

db.execSQL("DELETE FROM " + HospitalDbHelper.TABLE_DOCTOR);

ContentValues values1 = new ContentValues();

values1.put(HospitalDbHelper.COLUMN_DID, 1);

values1.put(HospitalDbHelper.COLUMN_DNAME, "Dr. Alice Smith");

values1.put(HospitalDbHelper.COLUMN_SPECIALIZATION, "Cardiology");

values1.put(HospitalDbHelper.COLUMN_EXPERIENCE, 3.0); // Less than 5.5

db.insert(HospitalDbHelper.TABLE_DOCTOR, null, values1);

ContentValues values2 = new ContentValues();

values2.put(HospitalDbHelper.COLUMN_DID, 2);

values2.put(HospitalDbHelper.COLUMN_DNAME, "Dr. Bob Johnson");

values2.put(HospitalDbHelper.COLUMN_SPECIALIZATION, "Pediatrics");

values2.put(HospitalDbHelper.COLUMN_EXPERIENCE, 6.0);

db.insert(HospitalDbHelper.TABLE_DOCTOR, null, values2); db.close();

Toast.makeText(this, "Doctor records inserted.", Toast.LENGTH_SHORT).show(); }

private void displayDoctorsWithLessExperience() {

SQLiteDatabase db = dbHelper.getReadableDatabase();

String[] projection = {

HospitalDbHelper.COLUMN_DID,

HospitalDbHelper.COLUMN_DNAME,

HospitalDbHelper.COLUMN_SPECIALIZATION,

HospitalDbHelper.COLUMN_EXPERIENCE };

String selection = HospitalDbHelper.COLUMN_EXPERIENCE + " < ?";

String[] selectionArgs = {"5.5"};

Cursor cursor = db.query(

HospitalDbHelper.TABLE_DOCTOR,

projection, selection, selectionArgs, null, null, null );

47
StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("Doctors with less than 5.5 years experience:\n\n");

if (cursor.getCount() == 0) {

stringBuilder.append("No doctors found with less than 5.5 years experience.");

} else {

while (cursor.moveToNext()) {

int did = cursor.getInt(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_DID));

String dname = cursor.getString(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_DNAME));

String specialization =
cursor.getString(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_SPECIALIZATION));

double experience =
cursor.getDouble(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_EXPERIENCE));

stringBuilder.append("ID: ").append(did) .append(", Exp: ").append(experience)

.append(", Name: ").append(dname) .append(" years\n");

.append(", Spec:
").append(specialization)

} }

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

displayTextView.setText(stringBuilder.toString()); }}

activity_main.xml

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

<LinearLayout <Button
xmlns:android="http://schemas.android.com/apk/re
android:id="@+id/operateButton"
s/android"
android:layout_width="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Insert &amp; Display Doctors"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
android:layout_marginBottom="16dp"/>
android:padding="16dp"

tools:context=".MainActivity">

48
<ScrollView android:layout_height="wrap_content"

android:layout_width="match_parent" android:text="Doctor information will appear


here."
android:layout_height="match_parent">
android:textSize="16sp"/>

</ScrollView>
<TextView

android:id="@+id/displayTextView"
</LinearLayout>
android:layout_width="match_parent"

20. What does Android APK file contain? Develop an Android application with a context menu having menu
items "Red", "Yellow", "Green", "Black" and "Blue" etc. and change the background color of the layout when the
user selects a menu item accordingly.

What does an Android APK file contain?

An APK (Android Package Kit) file is the package file format used by the Android operating system for distribution
and installation of mobile applications. It's essentially a compressed archive (similar to a .zip file) that contains all
the elements an Android device needs to install and run an application.

Android Application with Context Menu for Background Color Change:

activity_main.xml: tools:context=".MainActivity">

XML <TextView

<?xml version="1.0" encoding="utf-8"?> android:layout_width="wrap_content"

<LinearLayout android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
android:text="Long press this screen to change
s/android"
background color"
xmlns:tools="http://schemas.android.com/tools"
android:textSize="18sp"
android:id="@+id/mainLayout"
android:textStyle="italic"
android:layout_width="match_parent"
android:textColor="@android:color/black"
android:layout_height="match_parent"
android:padding="20dp"
android:orientation="vertical"
android:gravity="center"/>
android:gravity="center"
</LinearLayout>
android:background="@android:color/white"

49
MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; private static final int MENU_YELLOW = 2;

import android.os.Bundle; private static final int MENU_GREEN = 3;

import android.view.ContextMenu; private static final int MENU_BLACK = 4;

import android.view.MenuItem; private static final int MENU_BLUE = 5;

import android.view.View; private static final int MENU_DEFAULT = 6;

import android.widget.LinearLayout; @Override

import android.widget.Toast; protected void onCreate(Bundle


savedInstanceState) {
import android.graphics.Color;
super.onCreate(savedInstanceState);
public class MainActivity extends AppCompatActivity
{ setContentView(R.layout.activity_main);

private LinearLayout mainLayout; mainLayout = findViewById(R.id.mainLayout);

private static final int MENU_RED = 1; registerForContextMenu(mainLayout);

Toast.makeText(this, "Long press anywhere to open menu", Toast.LENGTH_SHORT).show();

} @Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo); @Override

menu.setHeaderTitle("Choose Background public boolean onContextItemSelected(MenuItem


Color"); item) {

menu.add(0, MENU_RED, 0, "Red"); switch (item.getItemId()) { case


MENU_RED:
menu.add(0, MENU_YELLOW, 0, "Yellow");

menu.add(0, MENU_GREEN, 0, "Green");


mainLayout.setBackgroundColor(Color.RED);
menu.add(0, MENU_BLACK, 0, "Black");
Toast.makeText(this, "Background set to
menu.add(0, MENU_BLUE, 0, "Blue"); Red", Toast.LENGTH_SHORT).show();

menu.add(0, MENU_DEFAULT, 0, "Default return true;


(White)"); }

50
case MENU_YELLOW:

mainLayout.setBackgroundColor(Color.YELLOW);

Toast.makeText(this, "Background set to Yellow", Toast.LENGTH_SHORT).show();

return true;

case MENU_GREEN:

mainLayout.setBackgroundColor(Color.GREEN);

Toast.makeText(this, "Background set to Green", Toast.LENGTH_SHORT).show();

return true;

case MENU_BLACK:

mainLayout.setBackgroundColor(Color.BLACK);

Toast.makeText(this, "Background set to Black", Toast.LENGTH_SHORT).show();

return true;

case MENU_BLUE:

mainLayout.setBackgroundColor(Color.BLUE);

Toast.makeText(this, "Background set to Blue", Toast.LENGTH_SHORT).show();

return true;

case MENU_DEFAULT:

mainLayout.setBackgroundColor(Color.WHITE);

Toast.makeText(this, "Background set to White", Toast.LENGTH_SHORT).show();

return true;

default:

return super.onContextItemSelected(item); }

51
11. What are different mobile application development approaches? Explain in detail.

Mobile application development can be broadly categorized into three main approaches:

• Native App Development:

o Description: Native apps are built specifically for a single mobile operating system (OS), like iOS or
Android, using their respective SDKs (Software Development Kits), programming languages, and
tools. For iOS, this means Swift/Objective-C with Xcode. For Android, it's Java/Kotlin with Android
Studio.

o Pros:

▪ Optimal Performance and User Experience (UX): Full Access to Device Features:

▪ Offline Capabilities: Security:

• Hybrid App Development:

o Description: Hybrid apps are essentially web applications (built using HTML, CSS, JavaScript)
wrapped inside a native container. Frameworks like React Native, Flutter, and Xamarin are
popular for this approach. These frameworks allow developers to write a single codebase that
can be compiled to run on multiple platforms (iOS and Android).

o Pros:

▪ Cross-Platform Compatibility: Faster DevelopmentWeb Technologies:

• Web App Development (Progressive Web Apps - PWAs):

o Description: Web apps are not installed on the device but are accessed via a web browser. PWAs
are advanced web applications that combine the best features of web and native apps. They are
built with web technologies (HTML, CSS, JavaScript) but can offer offline capabilities, push
notifications, and can be "added to home screen" to appear like native apps without needing an
app store.

o Pros:

▪ No Installation Required: Single Codebase: Instant Updates: SEO Discoverability:

52
12. Draw the hierarchical directory structure of an Android application. How can you use string and string array
in android? Explain.

Hierarchical Directory Structure of an Android Application:

A typical Android Studio project has a well-defined hierarchical directory structure to organize different types of
files. Here's a simplified representation:

YourProject/ │ │ │ ├── mipmap/

├── app/ │ │ │ ├── values/

│ ├── build/ │ │ │ │ ├── colors.xml

│ ├── libs/ │ │ │ │ ├── strings.xml

│ └── src/ │ │ │ │ └── styles.xml

│ ├── androidTest/ │ │ │ ├── xml/

│ │ └── java/ │ │ │ └── raw/

│ │ └── com/your_package/your_app/ │ │ └── AndroidManifest.xml

│ │ └── ExampleInstrumentedTest.java │ └── test/

│ ├── main/ │ └── java/

│ │ ├── java/ │ └── com/your_package/your_app/

│ │ │ └── com/your_package/your_app/ │ └── ExampleUnitTest.java

│ │ │ ├── MainActivity.java ├── gradle/

│ │ │ └── ... (other Java/Kotlin files) ├── .gitignore

│ │ ├── res/ ├── build.gradle

│ │ │ ├── drawable/ ├── settings.gradle

│ │ │ ├── layout/ └── local.properties

How to use String and String Array in Android and Examples:

In Android, strings and string arrays should always be defined in XML resource files, specifically
res/values/strings.xml. This practice is crucial for:

• Internationalization (Localization): It allows you to easily translate your app into different languages by
providing different strings.xml files for each locale.

• Maintainability: Centralizes all text content, making it easier to manage and update.

• Code Cleanliness: Keeps hardcoded strings out of your Java/Kotlin code, which improves readability and
reduces errors.

53
1. String Resource: A single piece of text.

res/values/strings.xml:

XML

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

<resources>

<string name="app_name">My String App</string>

<string name="welcome_message">Welcome to our Android app!</string>

<string name="button_text">Click Me</string>

<string name="greeting_format">Hello, %1$s! You are %2$d years old.</string>

</resources>

Usage in XML Layouts:

<TextView <Button

android:layout_width="wrap_content" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:layout_height="wrap_content"

android:text="@string/welcome_message" /> android:text="@string/button_text" />

Usage in Java/Kotlin Code:

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

welcomeTextView.setText(getString(R.string.welcome_message));

String name = "Alice";

int age = 30;

String formattedGreeting = getString(R.string.greeting_format, name, age);

Toast.makeText(this, formattedGreeting, Toast.LENGTH_LONG).show();

2. String Array Resource: A collection of strings. Useful for populating Spinners, ListViews, or other dynamic UI
elements.

res/values/strings.xml:

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

<resources> <item>Swift</item>

<string-array name="programming_languages"> <item>C#</item>

<item>Java</item> </string-array>

<item>Kotlin</item> </resources>

54
Usage in Java/Kotlin Code (e.g., with an ArrayAdapter for a Spinner):

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

String[] languages = getResources().getStringArray(R.array.programming_languages);

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

android.R.layout.simple_spinner_item, languages);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

languageSpinner.setAdapter(adapter);

languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

String selectedLanguage = parent.getItemAtPosition(position).toString();

Toast.makeText(MainActivity.this, "Selected: " + selectedLanguage, Toast.LENGTH_SHORT).show();

} @Override

public void onNothingSelected(AdapterView<?> parent) { }});

13. How to create AVD's? How to use spinner in android? Explain with a suitable example.

An AVD (Android Virtual Device) is a configuration that defines the characteristics of an Android phone, tablet,
Wear OS, Android TV, or Automotive OS device that you want to simulate in the Android Emulator. Creating an AVD
allows you to test your Android applications on various device configurations without needing a physical device.

Steps to create an AVD in Android Studio:

1. Open Android Studio: Launch your Android Studio IDE.

2. Open Device Manager:

o From the toolbar, click on the Device Manager icon (it looks like a phone with an Android robot
head).

o Alternatively, go to Tools > Device Manager.

3. Create New Virtual Device: In the Device Manager window, click on the "Create device" button (usually at
the top left or bottom left).

4. Select Hardware Profile:

o The "Select Hardware" dialog appears. Choose a predefined hardware profile (e.g., Pixel 7, Nexus
5X, Tablet, Wear OS device) from the list.

o You can also clone an existing hardware profile or create a new one from scratch if you need
specific custom specifications.

55
o Click "Next".

5. Select System Image:

o The "System Image" dialog appears. This is where you choose the Android version (API level) and
architecture (ABI) you want to install on your AVD.

o If you don't have the desired system image downloaded, you'll see a "Download" link next to it.
Click to download it.

o Choose a recommended image (often a recent stable version) or any other API level relevant to
your testing needs.

o Click "Next".

6. Verify Configuration:

o The "Verify Configuration" dialog shows a summary of your AVD settings (AVD name, OS version,
screen size, memory, etc.).

o You can customize the AVD name, change the startup orientation, and adjust advanced settings
like emulated performance (software/hardware graphics), internal storage, SD card size, and
network speed.

o For "Emulated Performance" > "Graphics," select "Hardware - GLES 2.0" for better performance if
your computer supports it.

o Click "Finish".

How to Use Spinner in Android? Explain with a Suitable Example.

A Spinner in Android is a widget that provides a quick way to select one value from a set of values. It's essentially a
dropdown list. When the user taps the spinner, it displays a dropdown menu with all the available options, and the
user can select one.

Key Components for using a Spinner:

1. Spinner in XML Layout: The UI element itself.

2. Data Source: The collection of items to be displayed in the spinner (e.g., a String array, ArrayList, or data
from a database).

3. Adapter: A bridge between the data source and the Spinner. It's responsible for converting the data into
View objects that the spinner can display.

o ArrayAdapter: Common for simple arrays or Lists of objects.

o CursorAdapter: Used for data from a database Cursor.

4. OnItemSelectedListener: An optional listener to detect when the user selects an item from the spinner.

56
Example: A Spinner for selecting a programming language.

activity_main.xml (Layout):

<?xml version="1.0" encoding="utf-8"?> android:layout_height="wrap_content"

<LinearLayout android:text="Select your favorite programming


xmlns:android="http://schemas.android.com/apk/re language:"
s/android"
android:textSize="18sp"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginBottom="20dp"/>
android:layout_width="match_parent"
<Spinner
android:layout_height="match_parent"
android:id="@+id/language_spinner"
android:orientation="vertical"
android:layout_width="wrap_content"
android:gravity="center_horizontal"
android:layout_height="wrap_content"
android:padding="16dp"
android:minWidth="200dp"
tools:context=".MainActivity">
android:spinnerMode="dropdown" />
<TextView </LinearLayout>

android:layout_width="wrap_content"

res/values/strings.xml (Data Source - String Array):

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

<resources> <item>Swift</item>

<string name="app_name">Spinner <item>C++</item>


Example</string>
<item>JavaScript</item>
<string-array
</string-array>
name="programming_languages_array">
</resources>
<item>Java</item>

<item>Kotlin</item>

MainActivity.java (Logic):

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.Spinner;

57
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

private Spinner languageSpinner;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

languageSpinner = findViewById(R.id.language_spinner);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(

this,

R.array.programming_languages_array,

android.R.layout.simple_spinner_item );

adapter.setDropDown.ViewResource(android.R.layout.simple_spinner_dropdown_item);

languageSpinner.setAdapter(adapter);

languageSpinner.setOnItemSelectedListener(this); } @Override

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

String selectedLanguage = parent.getItemAtPosition(position).toString();

Toast.makeText(this, "Selected: " + selectedLanguage, Toast.LENGTH_SHORT).show(); }

@Override

public void onNothingSelected(AdapterView<?> parent) {

Toast.makeText(this, "Nothing selected", Toast.LENGTH_SHORT).show(); }}

58
15. Develop an android application to display an alert dialog box.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> android:padding="16dp"

<LinearLayout tools:context=".MainActivity">
xmlns:android="http://schemas.android.com/apk/re
<Button
s/android"
android:id="@+id/showAlertButton"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_height="match_parent"
android:text="Show Alert Dialog" />
android:orientation="vertical"
</LinearLayout>
android:gravity="center"

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; @Override

import android.app.AlertDialog; protected void onCreate(Bundle


savedInstanceState) {
import android.content.DialogInterface;
super.onCreate(savedInstanceState);
import android.os.Bundle;
setContentView(R.layout.activity_main);
import android.view.View;
showAlertButton =
import android.widget.Button;
findViewById(R.id.showAlertButton);
import android.widget.Toast;
showAlertButton.setOnClickListener(new
public class MainActivity extends AppCompatActivity View.OnClickListener() {
{
@Override public void onClick(View v) {
private Button showAlertButton;
showAlertDialog(); } }); }

private void showAlertDialog() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Important Alert!");

builder.setMessage("This is a simple alert message. Do you want to proceed?");

builder.setCancelable(false);

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

@Override

59
public void onClick(DialogInterface dialog, int which) {

Toast.makeText(MainActivity.this, "You clicked Yes!", Toast.LENGTH_SHORT).show();

dialog.dismiss(); } });

builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

Toast.makeText(MainActivity.this, "You clicked No!", Toast.LENGTH_SHORT).show();

dialog.dismiss(); } });

builder.setNeutralButton("Later", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

Toast.makeText(MainActivity.this, "You clicked Later!", Toast.LENGTH_SHORT).show();

dialog.dismiss(); } });

AlertDialog alertDialog = builder.create();

alertDialog.show(); }}

60
16. Develop an android application to display 8 programming languages in ListView.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> android:layout_height="wrap_content"

<LinearLayout android:text="Popular Programming Languages"


xmlns:android="http://schemas.android.com/apk/re
android:textSize="20sp"
s/android"
android:textStyle="bold"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_marginBottom="15dp"/>
android:layout_height="match_parent"
<ListView
android:orientation="vertical"
android:id="@+id/languages_listview"
android:padding="16dp"
android:layout_width="match_parent"
tools:context=".MainActivity">
android:layout_height="match_parent" />
<TextView
</LinearLayout>
android:layout_width="wrap_content"

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; import java.util.Arrays;

import android.os.Bundle; import java.util.List;

import android.view.View; public class MainActivity extends AppCompatActivity


{
import android.widget.AdapterView;
private ListView languagesListView;
import android.widget.ArrayAdapter;
@Override
import android.widget.ListView;
protected void onCreate(Bundle
import android.widget.Toast;
savedInstanceState) {
import java.util.ArrayList;
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

languagesListView = findViewById(R.id.languages_listview);

List<String> programmingLanguages = new ArrayList<>(Arrays.asList(

"Java", "Kotlin", "Python", "Swift", "C++", "JavaScript", "C#", "Go" ));

ArrayAdapter<String> adapter = new ArrayAdapter<>(

this, android.R.layout.simple_list_item_1,

programmingLanguages );

61
languagesListView.setAdapter(adapter);

languagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String selectedLanguage = (String) parent.getItemAtPosition(position);

Toast.makeText(MainActivity.this, "You selected: " + selectedLanguage, Toast.LENGTH_SHORT).show();

} }); }}

19. Develop an android application to demonstrate the retrieval of content from a remote server.

Retrieving content from a remote server typically involves making network requests. In Android, modern best
practices involve using asynchronous operations to avoid blocking the UI thread

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> android:id="@+id/fetchContentButton"

<LinearLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/re
android:layout_height="wrap_content"
s/android"
android:text="Fetch Content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginBottom="20dp"/>
android:layout_width="match_parent"
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
android:padding="16dp"
<TextView
android:gravity="center_horizontal"
android:id="@+id/contentTextView"
tools:context=".MainActivity">
android:layout_width="match_parent"
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Fetched content will appear
android:layout_height="wrap_content"
here."
android:text="Content from Remote Server"
android:textSize="16sp"
android:textSize="20sp"
android:textColor="@android:color/black"/>
android:textStyle="bold"
</ScrollView>
android:layout_marginBottom="20dp"/>
</LinearLayout>
<Button

62
MainActivity.java:

import androidx.appcompat.app.AppCompatActivity; import java.io.IOException;

import android.os.AsyncTask; import java.io.InputStream;

import android.os.Bundle; import java.io.InputStreamReader;

import android.view.View; import java.net.HttpURLConnection;

import android.widget.Button; import java.net.URL;

import android.widget.TextView; public class MainActivity extends AppCompatActivity


{
import android.widget.Toast;
private Button fetchContentButton;
import java.io.BufferedReader;
private TextView contentTextView;

private static final String API_URL = "https://jsonplaceholder.typicode.com/posts/1";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); fetchContentButton.setOnClickListener(new
View.OnClickListener() {
setContentView(R.layout.activity_main);
@Override
fetchContentButton =
findViewById(R.id.fetchContentButton); public void onClick(View v) {

contentTextView = ew FetchContentTask().execute(API_URL);
findViewById(R.id.contentTextView); } }); }

private class FetchContentTask extends HttpURLConnection urlConnection = null;


AsyncTask<String, Void, String> {
BufferedReader reader = null;
@Override
String jsonResponse = null;
protected void onPreExecute() {

super.onPreExecute();
try {
contentTextView.setText("Fetching
URL url = new URL(urls[0]);
content...");
urlConnection = (HttpURLConnection)
Toast.makeText(MainActivity.this, "Connecting
url.openConnection();
to server...", Toast.LENGTH_SHORT).show(); }
urlConnection.setRequestMethod("GET");
@Override
urlConnection.connect();
protected String doInBackground(String... urls) {

63
InputStream inputStream = return "Error fetching data: " +
urlConnection.getInputStream(); e.getMessage();

StringBuilder buffer = new StringBuilder(); } finally {

if (inputStream == null) { if (urlConnection != null) {

return null; } urlConnection.disconnect(); }

reader = new BufferedReader(new if (reader != null) { try {


InputStreamReader(inputStream));
reader.close();
String line;
} catch (IOException e) {
while ((line = reader.readLine()) != null) {
e.printStackTrace(); } } }
buffer.append(line).append("\n"); }
return jsonResponse; }
if (buffer.length() == 0) {
@Override
return null; }
protected void onPostExecute(String result) {
jsonResponse = buffer.toString();
super.onPostExecute(result);
} catch (IOException e) {
if (result != null) {
e.printStackTrace();
contentTextView.setText(result);

Toast.makeText(MainActivity.this, "Content fetched successfully!", Toast.LENGTH_SHORT).show();

} else {

contentTextView.setText("Failed to retrieve content.");

Toast.makeText(MainActivity.this, "Failed to fetch content.", Toast.LENGTH_SHORT).show();

} }

AndroidManifest.xml (Crucial for network access):

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

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

package="com.example.yourapp"> <uses-permission android:name="android.permission.INTERNET" />

<application android:label="@string/app_name"

android:allowBackup="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:icon="@mipmap/ic_launcher"

64
android:supportsRtl="true" <category
android:name="android.intent.category.LAUNCHER"
android:theme="@style/Theme.YourApp">
/>
<activity
</intent-filter>
android:name=".MainActivity"
</activity>
android:exported="true">
</application>
<intent-filter>
</manifest>
<action
android:name="android.intent.action.MAIN" />

20. How to generate a signed APK? Write a program to locate the user's current location (write only .java and
manifest file).

How to Generate a Signed APK (or Android App Bundle - AAB):

Generating a signed APK (or preferably an Android App Bundle) is a crucial step before publishing your Android
application to the Google Play Store or distributing it for production. Signing ensures that your app is authentic and
has not been tampered with.

Steps to Generate a Signed APK/AAB in Android Studio:

1. Open Your Project: Open the Android project in Android Studio.

2. Build Menu: Go to Build > Generate Signed Bundle / APK....

3. Choose Output Format:

o A dialog will appear asking you to choose between "Android App Bundle" or "APK."

o Recommended: Select "Android App Bundle" (AAB). AABs are the modern publishing format
required by Google Play for new apps as of August 2021. They allow Google Play to generate
optimized APKs for each user's device, resulting in smaller app downloads.

o If you need a signed APK for direct distribution (e.g., side-loading, specific enterprise
distribution), select "APK."

o Click "Next".

4. Keystore Path & Key:

o If you have an existing keystore:

▪ Click "Choose existing..." next to "Keystore path."

▪ Browse to your .jks or .keystore file.

▪ Enter the "Keystore password."

▪ Select an existing "Key alias" from the dropdown.

▪ Enter the "Key password" for that alias.

65
o If you need to create a new keystore:

▪ Click "Create new..." next to "Keystore path."

▪ Keystore Path: Choose a secure location to save your .jks file (e.g.,
C:\Users\YourUser\AndroidKeystores\my_app_release.jks). Remember this path and
protect this file! Loss of this file means you cannot update your app.

▪ Keystore password: Enter a strong password for your keystore. Confirm it.

▪ Key (Alias):

▪ Alias: A name for your key within the keystore (e.g., my_app_key).

▪ Password: A strong password for this specific key (can be the same as the
keystore password). Confirm it.

▪ Validity (years): Set it to a very long period (e.g., 25 years).

▪ Certificate: Fill in your details (First and Last Name, Organizational Unit, Organization,
City/Locality, State/Province, Country Code).

▪ Click "OK" to create the keystore and key.

o Once chosen/created, click "Next".

5. Build Type:

o Select the "release" build variant. (The "debug" variant is used for development and is signed
with a default debug key).

o Check both "V1 (Jar Signature)" and "V2 (Full APK Signature)" checkboxes for broader
compatibility and security.

o Click "Create" or "Finish".

Program to Locate the User's Current Location (only .java and manifest file):

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

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

package="com.example.yourapp">

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

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

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

66
android:label="@string/app_name" <action
android:name="android.intent.action.MAIN" />

android:roundIcon="@mipmap/ic_launcher_round" <category
android:name="android.intent.category.LAUNCHER"
android:supportsRtl="true"
/>
android:theme="@style/Theme.YourApp">
</intent-filter>
<activity
</activity>
android:name=".MainActivity"
</application>
android:exported="true">
</manifest>
<intent-filter>

MainActivity.java:

import androidx.annotation.NonNull; import android.location.Location;

import androidx.appcompat.app.AppCompatActivity; import android.location.LocationListener;

import androidx.core.app.ActivityCompat; import android.location.LocationManager;

import androidx.core.content.ContextCompat; import android.os.Bundle;

import android.Manifest; import android.widget.TextView;

import android.content.pm.PackageManager; import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {

private TextView locationTextView;

private LocationManager locationManager;

private static final int PERMISSION_REQUEST_CODE = 100;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

locationTextView = findViewById(R.id.locationTextView);

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this,

67
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},

PERMISSION_REQUEST_CODE);

} else { startLocationUpdates(); } }

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]


grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == PERMISSION_REQUEST_CODE) {

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

startLocationUpdates();

} else {

Toast.makeText(this, "Location permission denied. Cannot get current location.",


Toast.LENGTH_LONG).show();

locationTextView.setText("Location permission denied."); } } }

private void startLocationUpdates() {

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) { try {

if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, this);

Toast.makeText(this, "Requesting GPS location updates...", Toast.LENGTH_SHORT).show();

} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this);

Toast.makeText(this, "GPS not available, requesting Network location updates...",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "Location services are not enabled.", Toast.LENGTH_LONG).show();

locationTextView.setText("Location services disabled."); }

} catch (SecurityException e) {

Toast.makeText(this, "Security Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();

e.printStackTrace(); } } }

68
@Override

protected void onPause() {

super.onPause();

if (locationManager != null) {

locationManager.removeUpdates(this); } }

@Override

protected void onResume() {

super.onResume();

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {

startLocationUpdates(); } }

@Override

public void onLocationChanged(@NonNull Location location) {

double latitude = location.getLatitude();

double longitude = location.getLongitude();

String locationInfo = String.format("Latitude: %.6f\nLongitude: %.6f\nAccuracy: %.1f m", latitude, longitude,


location.getAccuracy());

locationTextView.setText(locationInfo);

Toast.makeText(this, "Location updated!", Toast.LENGTH_SHORT).show(); }

@Override

public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override

public void onProviderEnabled(@NonNull String provider) {

Toast.makeText(this, provider + " enabled", Toast.LENGTH_SHORT).show(); }

@Override

public void onProviderDisabled(@NonNull String provider) {

Toast.makeText(this, provider + " disabled. Please enable location services.", Toast.LENGTH_LONG).show();

locationTextView.setText("Location provider disabled."); }}

69
activity_main.xml (for the TextView to display location):

<?xml version="1.0" encoding="utf-8"?> android:text="Current Location:"

<LinearLayout android:textSize="20sp"
xmlns:android="http://schemas.android.com/apk/re
android:textStyle="bold"
s/android"
android:layout_marginBottom="20dp"/>
xmlns:tools="http://schemas.android.com/tools"
<TextView
android:layout_width="match_parent"
android:id="@+id/locationTextView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Waiting for location..."
android:padding="16dp"
android:textSize="18sp"
tools:context=".MainActivity">
android:textColor="@android:color/black"
<TextView
android:gravity="center"/>
android:layout_width="wrap_content"
</LinearLayout>
android:layout_height="wrap_content"

70

You might also like