Mobile
Mobile
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.
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.
• Using an OnClickListener (Anonymous Inner Class): This is a very common approach, especially for simple
interactions like button clicks.
Java
myButton.setOnClickListener(new View.OnClickListener() {
@Override
}});
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
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
if (v.getId() == R.id.my_button) {
• 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
• Lambda Expressions (Java 8+): For more concise code, especially with functional interfaces.
Java
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.
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 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 Resource Manager: Provides access to non-code resources like strings, layouts, and images.
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:
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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"
<fragment
android:id="@+id/my_static_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:
• Text Views (UITextView): To allow users to input or display multiple lines of text.
• Segmented Controls (UISegmentedControl): To select from a small set of mutually exclusive options.
5
Swift program to find the sum of all elements of a 1-D array:
Swift
var sumOfNumbersTraditional = 0
sumOfNumbersTraditional += number
Output:
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.
Limited flexibility. Primarily supports Highly flexible. Supports various layout managers (linear,
Flexibility
vertical scrolling and basic item layouts. grid, staggered grid) and animations.
6
Using ListView (Conceptual - requires BaseAdapter or ArrayAdapter):
Java
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" />
Java
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
mNames = names; }
@NonNull
@Override
7
return new MyViewHolder(itemView);
@Override
holder.nameTextView.setText(mNames[position]);
@Override
return mNames.length;
super(view);
17. How do you find a view element in your program? Which dialog boxes can you use in your android
application?
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:
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"
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
Java
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = findViewById(R.id.myTextView);
myButton = findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
} }); }}
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 Example: "Are you sure you want to delete this item?", "Choose an option from the list."
Java
new AlertDialog.Builder(this)
.setTitle("Delete Item")
})
.show();
2. DatePickerDialog:
Java
int day = 2;
10
3. TimePickerDialog:
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.
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.
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
@Override
db.execSQL(SQL_CREATE_STUDENT_TABLE); }
@Override
db.execSQL(SQL_DELETE_STUDENT_TABLE);
onCreate(db); }}
12
MainActivity.java (Database Operations & Display):
import androidx.appcompat.app.AppCompatActivity;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayTextView = findViewById(R.id.displayTextView);
operateButton = findViewById(R.id.operateButton);
operateButton.setOnClickListener(new View.OnClickListener() {
@Override
SQLiteDatabase db = dbHelper.getWritableDatabase();
values1.put(CollegeDbHelper.COLUMN_ROLL, 101);
values2.put(CollegeDbHelper.COLUMN_ROLL, 102);
13
values2.put(CollegeDbHelper.COLUMN_NAME, "Bob Williams");
db.close();
String[] projection = {
CollegeDbHelper.COLUMN_ROLL,
CollegeDbHelper.COLUMN_NAME,
CollegeDbHelper.COLUMN_ADDRESS };
CollegeDbHelper.TABLE_STUDENT,
stringBuilder.append("Student Records:\n\n");
while (cursor.moveToNext()) {
stringBuilder.append("Roll: ").append(roll)
.append("\n"); }
cursor.close(); db.close();
displayTextView.setText(stringBuilder.toString());
}}
14
activity_main.xml:
XML
<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: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:textSize="16sp"/>
</ScrollView>
</LinearLayout>
15
19. Develop an android application to calculate simple interest using a customize dialog box.
activity_main.xml:
<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:textSize="20sp"
android:layout_marginBottom="30dp"/>
<Button
android:id="@+id/openDialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
16
dialog_simple_interest.xml:
<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:
@Override
super.onAttach(context);
try {
} catch (ClassCastException e) {
@NonNull
@Override
calculateButton.setOnClickListener(new View.OnClickListener() {
@Override
18
try {
if (listener != null) {
} catch (NumberFormatException e) {
} catch (Exception e) {
MainActivity.java:
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
@Override
19
20. Develop an android application to input your Name, Age, gender and other personal information. Pass and
display this information in another activity.
<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: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: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: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):
22
activity_display_info.xml (For displaying data):
<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;
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);
24
AndroidManifest.xml:
<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>
</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):
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
<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:
28
14. Android Application for Volume Calculation using Two Fragments:
<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):
<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):
<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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
31
.add(R.id.fragment_container, new InputFragment())
.commit(); } }
@Override
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(); }
getSupportFragmentManager().popBackStack(); }}
InputFragment.java:
import android.view.LayoutInflater;
32
private OnVolumeCalculatedListener listener;
@Override
super.onAttach(context);
@Override
@Nullable @Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
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
return; } try {
33
double height = Double.parseDouble(heightStr);
if (listener != null) {
} catch (NumberFormatException e) {
} } });
return view; }}
ResultFragment.java:
import androidx.annotation.NonNull;
import android.view.View;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
volumeResultTextView = view.findViewById(R.id.volumeResultTextView);
backToInputButton = view.findViewById(R.id.backToInputButton);
if (args != null) {
} else {
34
volumeResultTextView.setText("Volume: Error (No data)"); }
backToInputButton.setOnClickListener(new View.OnClickListener() {
@Override
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."
• Non-blocking: It does not prevent user interaction with the current activity.
• Informative: Provides quick feedback without requiring user action.Non-focusable: Users cannot tap on it.
activity_main.xml:
android:layout_width="wrap_content"
35
MainActivity.java:
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openFactorialDialogButton = findViewById(R.id.openFactorialDialogButton);
openFactorialDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
showFactorialInputDialog(); } }); }
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
if (numStr.isEmpty()) {
return; }try {
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
} else {
} catch (NumberFormatException e) {
} });
builder.show(); }
if (n == 0 || n == 1) {
return 1; }
long result = 1;
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.
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).
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.
• NUMERIC Affinity: Columns with NUMERIC affinity can store INTEGER, REAL, or BLOB data. Dates and
booleans are often stored as NUMERIC.
• 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
o Example: BLOB
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.
Let's say you receive the following JSON string from a web API:
JSON
{ "midterm": 85,
"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 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).
/ \
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.
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).
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:
40
AppGridAdapter.java (Custom Adapter):
if (convertView == null) {
holder.appLogoImageView = convertView.findViewById(R.id.appLogoImageView);
holder.appNameTextView = convertView.findViewById(R.id.appNameTextView);
convertView.setTag(holder);
holder.appLogoImageView.setImageResource(app.getLogoResId());
holder.appNameTextView.setText(app.getName());
return convertView; }
ImageView appLogoImageView;
TextView appNameTextView; }}
41
grid_item_app.xml (Layout for each GridView item):
<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>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<shape android:shape="rectangle">
</shape> </item>
<item>
<shape android:shape="rectangle">
<corners android:radius="8dp"/>
</shape> </item>
</selector>
42
activity_main.xml (Main Activity Layout):
<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:
@Override
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) {
intent.putExtra(EXTRA_URL, clickedApp.getUrl());
startActivity(intent); } }); }
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.
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.
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).
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
45
COLUMN_DNAME + " TEXT," +
@Override
db.execSQL(SQL_CREATE_DOCTOR_TABLE); }
@Override
db.execSQL(SQL_DELETE_DOCTOR_TABLE);
onCreate(db); }}
import android.widget.Toast;
46
private void insertDoctorRecords() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
values1.put(HospitalDbHelper.COLUMN_DID, 1);
values1.put(HospitalDbHelper.COLUMN_SPECIALIZATION, "Cardiology");
values2.put(HospitalDbHelper.COLUMN_DID, 2);
values2.put(HospitalDbHelper.COLUMN_SPECIALIZATION, "Pediatrics");
values2.put(HospitalDbHelper.COLUMN_EXPERIENCE, 6.0);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {
HospitalDbHelper.COLUMN_DID,
HospitalDbHelper.COLUMN_DNAME,
HospitalDbHelper.COLUMN_SPECIALIZATION,
HospitalDbHelper.COLUMN_EXPERIENCE };
HospitalDbHelper.TABLE_DOCTOR,
47
StringBuilder stringBuilder = new StringBuilder();
if (cursor.getCount() == 0) {
} else {
while (cursor.moveToNext()) {
String specialization =
cursor.getString(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_SPECIALIZATION));
double experience =
cursor.getDouble(cursor.getColumnIndexOrThrow(HospitalDbHelper.COLUMN_EXPERIENCE));
.append(", Spec:
").append(specialization)
} }
cursor.close(); db.close();
displayTextView.setText(stringBuilder.toString()); }}
activity_main.xml
<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 & 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"
</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.
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.
activity_main.xml: tools:context=".MainActivity">
XML <TextView
<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:
} @Override
50
case MENU_YELLOW:
mainLayout.setBackgroundColor(Color.YELLOW);
return true;
case MENU_GREEN:
mainLayout.setBackgroundColor(Color.GREEN);
return true;
case MENU_BLACK:
mainLayout.setBackgroundColor(Color.BLACK);
return true;
case MENU_BLUE:
mainLayout.setBackgroundColor(Color.BLUE);
return true;
case MENU_DEFAULT:
mainLayout.setBackgroundColor(Color.WHITE);
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:
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:
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:
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:
52
12. Draw the hierarchical directory structure of an Android application. How can you use string and string array
in android? Explain.
A typical Android Studio project has a well-defined hierarchical directory structure to organize different types of
files. Here's a simplified representation:
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
<resources>
</resources>
<TextView <Button
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
welcomeTextView.setText(getString(R.string.welcome_message));
2. String Array Resource: A collection of strings. Useful for populating Spinners, ListViews, or other dynamic UI
elements.
res/values/strings.xml:
<resources> <item>Swift</item>
<item>Java</item> </string-array>
<item>Kotlin</item> </resources>
54
Usage in Java/Kotlin Code (e.g., with an ArrayAdapter for a Spinner):
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) {
} @Override
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.
o From the toolbar, click on the Device Manager icon (it looks like a phone with an Android robot
head).
3. Create New Virtual Device: In the Device Manager window, click on the "Create device" button (usually at
the top left or bottom left).
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".
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".
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.
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.
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):
android:layout_width="wrap_content"
<resources> <item>Swift</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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
languageSpinner = findViewById(R.id.language_spinner);
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) {
@Override
58
15. Develop an android application to display an alert dialog box.
activity_main.xml:
<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:
builder.setTitle("Important Alert!");
builder.setCancelable(false);
@Override
59
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); } });
@Override
dialog.dismiss(); } });
@Override
dialog.dismiss(); } });
alertDialog.show(); }}
60
16. Develop an android application to display 8 programming languages in ListView.
activity_main.xml:
MainActivity.java:
setContentView(R.layout.activity_main);
languagesListView = findViewById(R.id.languages_listview);
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) {
} }); }}
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:
<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:
@Override
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); } }); }
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();
} else {
} }
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<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).
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.
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".
65
o If you need to create a new keystore:
▪ 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.
▪ Certificate: Fill in your details (First and Last Name, Organizational Unit, Organization,
City/Locality, State/Province, Country Code).
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.
Program to Locate the User's Current Location (only .java and manifest file):
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<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:
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationTextView = findViewById(R.id.locationTextView);
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
if (requestCode == PERMISSION_REQUEST_CODE) {
startLocationUpdates();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) { try {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
} else {
} catch (SecurityException e) {
e.printStackTrace(); } } }
68
@Override
super.onPause();
if (locationManager != null) {
locationManager.removeUpdates(this); } }
@Override
super.onResume();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
startLocationUpdates(); } }
@Override
locationTextView.setText(locationInfo);
@Override
@Override
@Override
69
activity_main.xml (for the TextView to display 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