Mobile Computing Android
Mobile Computing Android
1|Pag e
Q2)Draw and explain activity life cycle in detais
2|Pag e
2. onStart()
Called when the activity becomes visible to the user.
The activity is not yet in the foreground.
You can start animations or visual updates here.
protected void onStart() {
super.onStart();
}
3. onResume()
Called when the activity is now interactive with the user (in the
foreground).
Best place to resume anything paused in onPause() (like music or
camera).
4. onPause()
Called when the activity is partially obscured, but still alive (like a
dialog appears).
Used to pause activities like animations, video playback, or save unsaved
data.
protected void onPause() {
super.onPause();
}
5. onStop()
Called when the activity is completely hidden.
The app might go into the background or transition to another activity.
Release resources like broadcast receivers, network connections, etc.
protected void onStop() {
super.onStop();
}
6. onRestart()
3|Pag e
Called when the activity is restarting after being stopped.
Used to re-initialize components that were released in onStop().
protected void onRestart() {
super.onRestart();
}
7. onDestroy()
Called when the activity is about to be destroyed.
Clean up all resources (like threads, file handles, database connections).
@Override
protected void onDestroy() {
super.onDestroy();
}
4|Pag e
Q3)Various Layouts in Android
Android provides several types of layouts to organize UI elements (Views) in an
application. Common layouts include:
1. LinearLayout
2. RelativeLayout
3. ConstraintLayout
4. FrameLayout
5. TableLayout
6. GridLayout
7. CoordinatorLayout
Explanation of LinearLayout (in detail)
LinearLayout is a view group that aligns all its children in a single direction —
either vertically or horizontally.
Key Features:
Arranges child views in a single column (vertical) or row (horizontal).
You specify the direction using the android:orientation attribute.
Each child can use layout_weight to distribute space proportionally.
Example:
xml
CopyEdit
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
5|Pag e
android:text="Hello, World!" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Pros:
Simple and easy to use.
Ideal for small UIs with few elements.
Cons:
Not efficient for complex nested structures.
Deep nesting can affect performance.
6|Pag e
Q4)Spinner in Android
A Spinner is a dropdown menu that allows users to select an item from a list.
It’s similar to a combo box in other programming environments.
Steps to Use Spinner in an Android App
1. Add Spinner to XML Layout
You define the spinner in the XML layout file.
<Spinner
android:id="@+id/mySpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
7|Pag e
android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdow
n_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), "Selected: " + selectedItem,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
8|Pag e
Q5)What is a Service in Android?A Service is an Android component that
performs long-running operations in the background without providing a user
interface. It runs independently of an activity and can continue its work even if
the user switches to another app. Services are used for tasks such as playing
music, downloading files, or fetching data over the network.
There are mainly two types of services:Started Service: Runs until stopped
explicitly.Bound Service: Provides a client-server interface for interaction.
Differences Between Activity and Service
Feature Activity Service
onCreate(), onStart(),
Lifecycle onCreate(), onStartCommand(),
onResume(), onPause(),
Methods onBind(), onDestroy()
onStop(), onDestroy()
Started by user
Started by components like
Start launching the app or
activities or broadcast receivers.
navigating.
9|Pag e
Short note-1)A widget in Android is a small, interactive component that
provides quick access to information or app functions directly from the home
screen or lock screen. Also known as App Widgets, these are mini-application
views that can be embedded in other applications (like the launcher) and receive
periodic updates. Widgets enhance the user experience by offering real-time
data and allowing users to interact with essential app features without opening
the full application. Common examples of widgets include clock widgets,
weather updates, calendar events, music controls, and note-taking shortcuts.
Widgets are implemented as Broadcast Receivers and use a special layout
defined in XML using the RemoteViews class, which allows limited UI
components such as TextView, ImageView, and Buttons. The Android system
uses AppWidgetProvider to handle updates and user interactions. Developers
define widget properties like size, update frequency, and layout in an XML file
placed in the res/xml folder and declare the widget in the AndroidManifest.
Widgets are updated either periodically, based on the interval defined in the
widget metadata, or through explicit triggers using AppWidgetManager. Unlike
standard views, widgets have limited interactivity and do not support full View
or ViewGroup capabilities due to system limitations and performance
constraints. However, developers can add click handlers that launch activities or
services in response to user actions. With Android 12 and above, widget design
has improved with support for responsive layouts and better accessibility.
Widgets must be lightweight and efficient to avoid draining system resources
and affecting performance. They are ideal for apps that provide frequently
changing data or quick actions, helping users stay informed and engaged.
Overall, Android widgets are a powerful tool for enhancing app visibility,
improving user engagement, and delivering timely content directly on the user’s
home screen in a compact and accessible format.
10 | P a g e
Short note-2) Content Resolver in AndroidThe Content Resolver in Android is
a key component that facilitates access to data from content providers. It acts as
an intermediary between the application and content providers, enabling secure
and structured access to data such as contacts, media, messages, or custom app
data. Through the Content Resolver, an app can perform operations like
querying, inserting, updating, and deleting data using a URI (Uniform Resource
Identifier), which uniquely identifies the data to be accessed. The Content
Resolver uses methods like query(), insert(), update(), and delete() to interact
with the content provider. When querying, it returns a Cursor object that can be
used to read the result set. For example, an app that needs to read contacts can
use getContentResolver().query() with the appropriate URI
(ContactsContract.Contacts.CONTENT_URI) to retrieve contact details.
Content Resolver ensures proper permissions are enforced before allowing
access to the data, which is critical for security and privacy. It can also be used
to observe changes in data by registering a ContentObserver, which notifies the
app when the underlying data changes. This is particularly useful for
applications that need to stay updated with real-time changes to shared data.
Since content providers are the standard way to share data between applications,
the Content Resolver plays a central role in enabling inter-process
communication and data sharing in Android. For example, one app can expose
its data through a content provider, and another app can access that data using
the Content Resolver without needing direct access to the underlying database.
This abstraction allows data sharing to happen in a secure, decoupled, and
standardized manner. Overall, the Content Resolver is an essential API for
managing access to shared app data and for integrating with Android's built-in
or third-party content providers.
11 | P a g e
Short note-3) A Fragment in Android is a modular section of an activity,
representing a portion of the user interface or behavior that can be placed within
an activity. Introduced to support flexible and dynamic UI designs on different
screen sizes, fragments help in creating adaptable applications that can work
efficiently on both phones and tablets. Unlike activities, fragments cannot live
on their own—they must be hosted within an activity. However, they have their
own lifecycle, receive their own input events, and can be added or removed
dynamically while the activity is running. This modular approach allows
developers to build UI components that can be reused in multiple activities,
thereby reducing code duplication and improving app structure. A fragment’s
lifecycle includes methods such as onAttach(), onCreate(), onCreateView(),
onActivityCreated(), onStart(), onResume(), onPause(), onStop(),
onDestroyView(), and onDetach(). These callbacks provide fine control over
how the fragment is created, displayed, and destroyed. Developers manage
fragments using the FragmentManager and perform operations like adding,
replacing, or removing fragments through FragmentTransaction. Fragments can
be used to build multi-pane UIs, where one part of the screen shows a list
(ListFragment) and another part shows details (DetailFragment). This is
common in master-detail interfaces on tablets. Additionally, Android supports
specialized fragments such as DialogFragment for displaying dialogs and
BottomSheetDialogFragment for bottom sheets. With the introduction of
Jetpack’s Navigation Component, managing fragment transitions and back stack
has become even easier and more consistent. Fragments promote better
separation of concerns by encapsulating UI and behavior in standalone
components. They also make it easier to manage complex UIs and respond to
configuration changes like screen rotation. As a result, fragments are a
fundamental building block for building rich, responsive, and maintainable
Android applications.
12 | P a g e
Short note-4)Navigation Drawer in Android:-A Navigation Drawer is a UI
panel that slides in from the left edge of the screen, providing a convenient way
to navigate between different sections or activities within an app. It is a popular
navigation pattern in Android apps, allowing users quick access to app
destinations without cluttering the main interface.
Key Features:
Typically hidden off-screen and revealed by swiping from the left edge or
tapping the “hamburger” menu icon in the app’s toolbar.
Contains menu items such as links to different fragments, activities, or
settings.
Provides a consistent and intuitive way to switch between major app
sections.
How It Works:
When a user taps an item in the drawer, the app usually replaces the main
content with the corresponding fragment or navigates to another activity. The
drawer then automatically closes to maintain focus on the selected
content.Benefits:Keeps the UI clean by hiding navigation options until
needed.Supports multi-level navigation via submenus.Can easily be customized
with icons, headers, and badges.Works well on various screen sizes and
orientations.
Example Use Case:In a social media app, the navigation drawer might include
options like Home, Profile, Messages, Settings, and Logout, allowing users to
jump to these sections without cluttering the main screen.
13 | P a g e
Q1.20)Buid an app with button that displays a message when clicked.
Step 1: Create the Layout (XML)
Create or edit your activity_main.xml file under res/layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/buttonShowMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
14 | P a g e
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.buttonShowMessage);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Show a toast message when button is clicked
Toast.makeText(MainActivity.this, "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});
}
}
Output
When you run the app, it shows a button labeled "Click Me".
When you tap the button, a short message “Button Clicked!” appears as
a toast notification.
15 | P a g e
Q2.20)Implement a small database user information
UserDatabaseHelper.java
public class UserDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "UserDB", TABLE = "users";
private static final int VERSION = 1;
public UserDatabaseHelper(Context c) { super(c, DB_NAME, null,
VERSION); }
@Override public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE + "(id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT, email TEXT)");
}
@Override public void onUpgrade(SQLiteDatabase db, int o, int n) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
public boolean addUser(String name, String email) {
ContentValues v = new ContentValues();
v.put("name", name); v.put("email", email);
return getWritableDatabase().insert(TABLE, null, v) != -1;
}
public Cursor getUsers() {
return getReadableDatabase().rawQuery("SELECT * FROM " + TABLE,
null);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
UserDatabaseHelper db;
16 | P a g e
@Override
protected void onCreate(Bundle s) {
super.onCreate(s); setContentView(R.layout.activity_main);
db = new UserDatabaseHelper(this);
findViewById(R.id.buttonAddUser).setOnClickListener(v -> {
boolean inserted = db.addUser("John Doe", "john@example.com");
Toast.makeText(this, inserted ? "User Added" : "Error",
Toast.LENGTH_SHORT).show();
});
findViewById(R.id.buttonShowUsers).setOnClickListener(v -> {
Cursor c = db.getUsers();
if (c.getCount() == 0) Toast.makeText(this, "No users",
Toast.LENGTH_SHORT).show();
else {
StringBuilder sb = new StringBuilder();
while (c.moveToNext()) sb.append(c.getInt(0)).append(":
").append(c.getString(1)).append(", ").append(c.getString(2)).append("\n");
Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
}
c.close();
});}}
Layout (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:gravity="center"
android:padding="16dp">
17 | P a g e
<Button android:id="@+id/buttonAddUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Add User" />
<Button android:id="@+id/buttonShowUsers"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Users"
android:layout_marginTop="20dp" />
</LinearLayout>
Output:
Clicking Add User inserts a dummy user ("John Doe").
Clicking Show Users displays all users in a Toast message.
18 | P a g e
Q3.20)Create an app that loads and displays image from the gallery.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:gravity="center"
android:padding="16dp">
<Button android:id="@+id/btnLoad" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Load Image" />
<ImageView android:id="@+id/imgView" android:layout_width="300dp"
android:layout_height="300dp" android:layout_marginTop="20dp"
android:scaleType="centerCrop" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMG = 1;
ImageView imgView;
@Override
protected void onCreate(Bundle s) {
super.onCreate(s);
setContentView(R.layout.activity_main);
imgView = findViewById(R.id.imgView);
findViewById(R.id.btnLoad).setOnClickListener(v -> {
startActivityForResult(new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI),
PICK_IMG);
});
19 | P a g e
}
@Override
protected void onActivityResult(int req, int res, Intent data) {
super.onActivityResult(req, res, data);
if (req == PICK_IMG && res == RESULT_OK && data != null) {
imgView.setImageURI(data.getData());
}
}
}
Output:
Tapping Load Image from Gallery opens the gallery.
User picks an image.
The selected image displays inside the ImageView.
20 | P a g e