Popular Searches
Popular Course Categories
Popular Courses

Preparing for Android Lifecycle, Intents, and UI Development Questions

Preparing for Android Lifecycle, Intents, and UI Development Questions

Android App Development Portfolio and Interview Preparation

Preparing for Android Lifecycle, Intents, and UI Development Questions

Course: Android App Development

Topic: Preparing for Android Lifecycle, Intents, and UI Development Questions

Course Link: Android App Development Course

Demo Link: Register for a Free Course Demo

Official Website: JustAcademy


1. Introduction

Preparing for Android development questions requires a clear understanding of the Android activity lifecycle, intents, and user interface development. These concepts are essential for building applications that respond correctly to user interactions, handle configuration changes, navigate between screens, and manage application resources efficiently.

Android developers are commonly evaluated on their ability to explain lifecycle callbacks, distinguish between explicit and implicit intents, design responsive layouts, handle user input, and troubleshoot interface-related problems. Practical coding examples and scenario-based questions are useful for strengthening these skills.

Learning Objectives

  • Understand the Android activity lifecycle and its callback methods.
  • Explain how Android manages activities during navigation and configuration changes.
  • Differentiate explicit intents from implicit intents.
  • Pass data between activities using intent extras.
  • Understand layouts, views, event listeners, and UI components.
  • Prepare for common Android technical interview questions.
  • Apply lifecycle, navigation, and UI concepts in a practical application.

2. Understanding the Android Activity Lifecycle

The Android activity lifecycle describes the different states an activity passes through from creation to destruction. An activity represents a single screen or a major interaction point in an Android application.

The Android operating system invokes lifecycle callback methods when an activity is created, becomes visible, receives user interaction, moves into the background, or is destroyed.

2.1 Important Lifecycle Methods

Method Purpose Typical Use
onCreate() Initializes the activity. Load the layout, initialize variables, and configure UI components.
onStart() Makes the activity visible. Prepare resources needed while the screen is visible.
onResume() Brings the activity into the foreground for interaction. Start interactive features and resume camera previews where appropriate.
onPause() Indicates that the activity is losing its foreground interaction state. Pause animations and release resources that should not remain active.
onStop() Indicates that the activity is no longer visible. Stop UI-related background work and release visibility-dependent resources.
onRestart() Called when a stopped activity is about to start again. Prepare an existing activity to become visible again.
onDestroy() Called before an activity is destroyed. Perform final cleanup when appropriate.
onSaveInstanceState() Provides an opportunity to save lightweight UI state. Save a text field value or selected item for restoration.

2.2 Typical Activity Lifecycle Flow

onCreate()
    |
onStart()
    |
onResume()
    |
Activity is active
    |
onPause()
    |
onStop()
    |
Activity may be restarted
    |
onRestart()
    |
onStart()
    |
onResume()

If an activity finishes or is destroyed, the lifecycle may proceed through onPause(), onStop(), and onDestroy(), depending on its current state and the circumstances. The exact callback sequence depends on the transition taking place.

2.3 Example: Logging Lifecycle Events in Kotlin

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private val tag = "ActivityLifecycle"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d(tag, "onCreate called")
    }

    override fun onStart() {
        super.onStart()
        Log.d(tag, "onStart called")
    }

    override fun onResume() {
        super.onResume()
        Log.d(tag, "onResume called")
    }

    override fun onPause() {
        super.onPause()
        Log.d(tag, "onPause called")
    }

    override fun onStop() {
        super.onStop()
        Log.d(tag, "onStop called")
    }

    override fun onRestart() {
        super.onRestart()
        Log.d(tag, "onRestart called")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(tag, "onDestroy called")
    }
}

Explanation: This example records lifecycle callbacks in Logcat. Run the application, open another screen, return to the activity, and observe which methods are called. Use the logs to understand how activity visibility and user interaction affect lifecycle transitions.

2.4 Why Is the Activity Lifecycle Important?

  • Resource management: Helps manage sensors, media playback, camera resources, and other components responsibly.
  • User experience: Prevents unnecessary work while an activity is inactive.
  • State restoration: Helps restore UI state after configuration changes or system-initiated recreation.
  • Performance: Reduces unnecessary processing and resource usage.
  • Stability: Helps prevent crashes, resource leaks, and inconsistent screen behavior.

2.5 Lifecycle Interview Questions

Q1. What is the Android activity lifecycle?

The activity lifecycle is the sequence of states and callback methods that describe how an activity is created, displayed, interacted with, paused, stopped, restarted, or destroyed.

Q2. What is the difference between onCreate() and onStart()?

onCreate() performs initial activity setup, while onStart() is called when the activity is becoming visible to the user.

Q3. What is the difference between onPause() and onStop()?

onPause() indicates that the activity is losing foreground interaction. onStop() indicates that the activity is no longer visible.

Q4. Is onDestroy() always guaranteed to execute?

No. Android can terminate an application's process without calling onDestroy(). Critical data should be saved before the process can be terminated rather than relying on this callback for persistence.

Q5. What happens when the device rotates?

Under the default activity configuration, a configuration change such as rotation commonly causes the activity to be destroyed and recreated. UI state can be preserved using saved instance state, ViewModel, or other suitable state-management approaches.


3. Saving and Restoring Activity State

Android applications should preserve important user input and UI selections when an activity is recreated. For example, a partially completed form should not unexpectedly lose its text when the device rotates.

3.1 Using onSaveInstanceState()

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

    outState.putString("username", "AndroidLearner")
    outState.putInt("selectedTab", 2)
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val username = savedInstanceState?.getString("username")
    val selectedTab = savedInstanceState?.getInt("selectedTab")
}

Explanation: A Bundle stores lightweight values that can be restored when Android recreates an activity. In a complete implementation, restore these values into the corresponding UI components.

3.2 Choosing a State Management Technique

Technique Best Use Limitation
onSaveInstanceState() Small amounts of transient UI state. Not suitable for large objects or permanent storage.
ViewModel Retaining screen-related data across configuration changes. Does not independently guarantee survival of process death.
SavedStateHandle Restoring selected ViewModel state after recreation. Designed for small, serializable state values.
Room database Persistent structured application data. Requires database design and data access logic.
DataStore Persistent preferences and small application settings. Not a replacement for a relational database when complex queries are needed.

3.3 Best Practices for State Management

  • Save important user input before it can be lost.
  • Use ViewModel for screen state that should survive configuration changes.
  • Use persistent storage for information that must remain after the app is closed.
  • Avoid storing large objects inside a saved-state Bundle.
  • Test rotation, backgrounding, and process recreation scenarios.

4. Understanding Android Intents

An Intent is a messaging object used to request an action from another Android component. Intents are commonly used to start activities, start services, deliver broadcasts, and share information between components.

4.1 Types of Intents

Feature Explicit Intent Implicit Intent
Destination Specifies a particular component. Describes an action to be handled by a suitable component.
Common use Moving between activities in your application. Opening a web page, sharing text, or composing an email.
Target resolution Target component is specified directly. Android resolves the action using matching components.
Example Opening DetailsActivity. Opening a URL using a browser.

4.2 Explicit Intent Example in Kotlin

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

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = findViewById<Button>(R.id.openDetailsButton)

        button.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)
            startActivity(intent)
        }
    }
}

Explanation: The intent explicitly identifies DetailsActivity as the destination. When the user presses the button, Android launches that activity, provided it is correctly configured for the application.

4.3 Passing Data Between Activities

Intent extras allow one activity to send small values to another activity. Common values include a user ID, product name, selected category, or record identifier.

Sending data:

val intent = Intent(this, DetailsActivity::class.java)
intent.putExtra("product_name", "Wireless Headphones")
intent.putExtra("product_price", 1999)
startActivity(intent)

Receiving data:

class DetailsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)

        val productName =
            intent.getStringExtra("product_name")

        val productPrice =
            intent.getIntExtra("product_price", 0)

        // Display the received values in the UI.
    }
}

Explanation: The receiving activity reads the values using the same keys used by the sending activity. The default value supplied to getIntExtra() is returned if the expected integer extra is absent.

4.4 Implicit Intent Example: Opening a Website

import android.content.Intent
import android.net.Uri

val webpage = Uri.parse("https://www.justacademy.co/")
val intent = Intent(Intent.ACTION_VIEW, webpage)

if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

Explanation: ACTION_VIEW describes the requested action, while the URI identifies the website. Android attempts to find an application capable of handling the request.

4.5 Implicit Intent Example: Sharing Text

import android.content.Intent

val sendIntent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(
        Intent.EXTRA_TEXT,
        "Learn Android development with practical projects."
    )
}

val chooser = Intent.createChooser(
    sendIntent,
    "Share using"
)

startActivity(chooser)

Explanation: ACTION_SEND allows compatible applications to receive content. The chooser lets the user select an appropriate application. Only include content that is safe to share.

4.6 Intent Interview Questions

Q1. What is an Intent in Android?

An Intent is a messaging object that requests an action from an Android component.

Q2. What is the difference between explicit and implicit intents?

An explicit intent names a specific component, while an implicit intent describes an action that Android resolves to a compatible component.

Q3. How do you pass data between activities?

Use intent extras with putExtra() in the sending activity and retrieve the values using methods such as getStringExtra() or getIntExtra() in the receiving activity.

Q4. What is an intent filter?

An intent filter declares the types of implicit intents that a component can handle. It commonly specifies actions, categories, and data types or URI patterns.

Q5. Can an implicit intent always open another application?

No. A compatible handler must be available, and Android's resolution and security rules must permit the operation. Applications should handle situations in which no suitable activity exists.

Q6. What is a PendingIntent?

A PendingIntent is a token that allows another application or system service to execute a specified operation on behalf of the application that created it, subject to its configured permissions and flags.


5. Android UI Development Fundamentals

User interface development involves designing screens that are readable, accessible, responsive, and easy to navigate. Android supports traditional View-based interfaces and Jetpack Compose, a modern declarative UI toolkit.

5.1 Common UI Components

Component Purpose Example
TextView Displays text. Page title or product description.
EditText Accepts user input. Username or search field.
Button Triggers an action. Login or Submit.
ImageView Displays an image. Product photo or profile picture.
RecyclerView Displays efficiently managed lists. Product catalog or message list.
ProgressBar Indicates progress or loading. API request in progress.
Switch Enables or disables an option. Notification preference.
ConstraintLayout Positions views using constraints. Responsive form layout.

5.2 Common Android Layouts

  • LinearLayout: Arranges child views horizontally or vertically.
  • ConstraintLayout: Positions views through relationships and constraints, supporting complex responsive layouts.
  • FrameLayout: Commonly used to contain a single primary view or stack views.
  • ScrollView: Enables vertical scrolling for a single direct child container.
  • RecyclerView: Efficiently displays large or changing collections of items.

5.3 Example XML 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:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/titleText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome to Android"
        android:textSize="24sp"
        android:accessibilityHeading="true" />

    <EditText
        android:id="@+id/nameInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/submitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>

Explanation: The vertical LinearLayout places the heading, input field, and button one after another. The match_parent and wrap_content attributes control dimensions, while padding adds space inside the container.

5.4 Handling Button Clicks in Kotlin

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

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val nameInput = findViewById<EditText>(R.id.nameInput)
        val submitButton =
            findViewById<Button>(R.id.submitButton)
        val titleText = findViewById<TextView>(R.id.titleText)

        submitButton.setOnClickListener {
            val name = nameInput.text.toString().trim()

            if (name.isNotEmpty()) {
                titleText.text = "Welcome, $name!"
            } else {
                nameInput.error = "Please enter your name"
            }
        }
    }
}

Explanation: The click listener runs when the user taps the button. The application reads the input, removes leading and trailing spaces, checks whether a name was entered, and updates the displayed message.

5.5 UI Development Best Practices

  • Use descriptive resource names and separate UI resources from application logic.
  • Use string resources instead of hardcoding user-facing text in production applications.
  • Prefer dp for layout dimensions and sp for text sizes.
  • Support different screen sizes, orientations, and font scaling.
  • Provide meaningful labels and content descriptions where needed for accessibility.
  • Validate input before processing it.
  • Keep long-running operations off the main thread.
  • Display loading, success, empty, and error states where appropriate.
  • Use RecyclerView for large View-based lists and stable keys or item identities where appropriate.
  • Test the interface on multiple devices and Android versions.

6. Jetpack Compose: Modern UI Development

Jetpack Compose is Android's declarative UI toolkit. Instead of describing the interface primarily through XML layouts, developers write Kotlin composable functions that describe how the UI should appear for the current state.

6.1 Example of a Composable Function

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun GreetingScreen() {
    var name by remember { mutableStateOf("") }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = "Welcome to Android")

        Button(onClick = {
            name = "Android Developer"
        }) {
            Text("Show Greeting")
        }

        if (name.isNotEmpty()) {
            Text(text = "Hello, $name!")
        }
    }
}

Explanation: The composable function defines a column containing text and a button. The name variable holds UI state, and changing it causes Compose to recompose the relevant UI.

6.2 XML Views vs. Jetpack Compose

Aspect XML-Based Views Jetpack Compose
UI definition XML layout resources with Kotlin or Java logic. Kotlin composable functions.
UI updates Often performed by updating view properties. UI is described as a function of state.
State handling Uses view properties, listeners, ViewModel, and related approaches. Uses Compose state and can integrate with ViewModel.
Reuse Reusable layouts and custom views. Reusable composable functions.
Existing projects Common in established Android applications. Can be introduced incrementally into existing applications.

6.3 Compose Interview Questions

Q1. What is Jetpack Compose?

Jetpack Compose is a declarative toolkit for building native Android user interfaces with Kotlin.

Q2. What is recomposition?

Recomposition is the process in which Compose reruns composable functions affected by changes to observed state to update the UI.

Q3. What is the purpose of remember?

remember retains a value across recompositions while the relevant composition remains in place. It does not, by itself, preserve the value across activity recreation or process death.

Q4. What is the difference between remember and rememberSaveable?

remember retains state across recompositions, while rememberSaveable can also save and restore supported values across certain activity or process recreation scenarios using saved instance state.


7. Activity Navigation and Back Stack

Android manages activities through a task and back stack. When an activity starts another activity, the new activity is generally placed on top of the stack. Pressing Back usually returns the user to the previous activity, subject to the application's navigation configuration.

7.1 Example Navigation Flow

MainActivity
    |
    | User taps "View Details"
    v
DetailsActivity
    |
    | User presses Back
    v
MainActivity

7.2 Important Navigation Concepts

  • Task: A collection of activities that interact to complete a user task.
  • Back stack: The ordered stack of activities within a task.
  • startActivity(): Requests that Android launch an activity using an intent.
  • finish(): Finishes the current activity.
  • Launch modes: Configure how activity instances are created and reused.
  • Android Navigation component: Helps manage destinations and navigation actions, especially in fragment-based and Compose applications.

7.3 Common Navigation Mistakes

  • Starting the same activity repeatedly without considering the intended navigation behavior.
  • Passing large or complex data objects through intent extras instead of passing a stable identifier.
  • Failing to validate incoming intent data.
  • Using launch modes or task flags without understanding their effects on Back navigation.
  • Ignoring deep-link validation and access control.

8. Scenario-Based Interview Questions

Q1. What happens when a user presses the Home button?

The current activity commonly receives onPause() and then onStop() if it becomes fully hidden. The process may remain in memory, but Android can terminate it later if resources are needed.

Q2. How would you prevent form data from disappearing during screen rotation?

Use a ViewModel for screen-related state and saved-state mechanisms for values that must be restored after recreation. Use persistent storage if the information must survive app closure or process termination reliably.

Q3. How do you open a web page from an Android application?

Create an ACTION_VIEW intent with the page URI, check whether a suitable activity can handle it when appropriate, and launch the intent.

Q4. What would you do if a button does not respond?

Check whether the view is initialized correctly, whether its click listener is registered, whether another view blocks interaction, and whether Logcat reports an exception. Also verify that the correct layout is loaded.

Q5. How do you avoid freezing the UI while loading data from an API?

Perform network requests asynchronously using suitable tools such as Kotlin coroutines and a networking library. Update observable UI state on the appropriate dispatcher and display loading and error states.

Q6. What should happen when a user submits an empty form?

Validate the fields, provide clear feedback, prevent invalid submission, and move focus to the field that needs attention when appropriate.

Q7. What is the difference between an activity and a fragment?

An activity is an Android application component that provides an entry point for user interaction. A fragment represents a reusable portion of a UI hosted by an activity or another supported host. Both have lifecycles, but a fragment's lifecycle is also connected to its host and view lifecycle.

Q8. How should an application handle a missing intent extra?

Use nullable accessors or suitable defaults, validate required values, and show a safe error or fallback state instead of assuming every extra is present.

Q9. Why should developers avoid storing all screen data in onSaveInstanceState()?

Saved instance state is intended for small amounts of transient UI state. Large data structures can increase memory and serialization overhead. Store durable or complex data in an appropriate repository or database and restore it using identifiers where possible.

Q10. How do you make an Android UI accessible?

Provide meaningful descriptions for relevant images, ensure adequate contrast, use readable text sizes, label input fields, support accessibility services, and test navigation with TalkBack and other accessibility tools.


9. Practical Exercises

Exercise 1: Lifecycle Logger

  • Create an activity that logs all major lifecycle callbacks.
  • Run the application and inspect Logcat.
  • Open another activity, return to the original activity, and observe the callbacks.
  • Rotate the device and compare the results.

Exercise 2: Intent-Based Profile Screen

  • Create MainActivity and ProfileActivity.
  • Accept a name and age in MainActivity.
  • Pass the values through intent extras.
  • Display the received values in ProfileActivity.
  • Handle missing or invalid values safely.

Exercise 3: Responsive Login Screen

  • Create a login screen with email and password fields.
  • Add input validation and a login button.
  • Display suitable validation messages.
  • Support different screen sizes and font settings.
  • Test keyboard behavior and accessibility.

Exercise 4: Product Details Navigation

  • Build a simple product list.
  • Open a details screen when a product is selected.
  • Pass a product ID rather than a large product object.
  • Load the corresponding details and handle missing products.
  • Verify Back navigation and state restoration.

Exercise 5: Compose State Management

  • Create a composable screen with a text field and a button.
  • Store the entered text using Compose state.
  • Display a greeting after the button is pressed.
  • Experiment with remember and rememberSaveable.
  • Explain how recomposition changes the interface.

10. Common Errors and Troubleshooting

Problem Possible Cause Solution
Activity does not open Incorrect destination class or configuration. Check the intent target, manifest configuration, and Logcat.
Intent extra is null Incorrect key or missing extra. Verify matching keys and validate received values.
Application crashes during rotation Incorrect state handling or lifecycle assumptions. Inspect the stack trace and restore state appropriately.
Button does not work Listener not registered or view is not interactive. Check view initialization, listener registration, and overlapping views.
Text disappears after recreation UI state is stored only in temporary view objects. Use ViewModel and saved-state mechanisms as appropriate.
Screen freezes during data loading Blocking work on the main thread. Use asynchronous operations and update the UI safely.
Layout looks different on devices Fixed dimensions or insufficient responsive design. Use flexible layouts, dp, sp, and device testing.
Implicit intent cannot be handled No compatible activity or invalid request. Validate the intent, handle missing handlers, and test supported devices.

11. Best Practices for Android Technical Interviews

  • Understand the purpose of each lifecycle callback instead of memorizing names alone.
  • Explain lifecycle behavior using real scenarios such as rotation, navigation, and backgrounding.
  • Practice writing explicit and implicit intents without copying examples blindly.
  • Explain how extras are passed, retrieved, and validated.
  • Understand both XML-based layouts and Jetpack Compose fundamentals.
  • Use clear variable names, modular code, and suitable architecture.
  • Discuss error handling, accessibility, performance, and security in UI answers.
  • Use Logcat and Android Studio debugging tools to investigate unexpected behavior.
  • Test on an emulator and, where possible, a physical Android device.
  • When answering a scenario question, explain the problem, the technical reason, the solution, and any trade-offs.

12. Quick Revision Checklist

  • Can you explain onCreate(), onStart(), onResume(), onPause(), onStop(), onRestart(), and onDestroy()?
  • Can you describe what may happen when the device rotates or an activity moves to the background?
  • Can you explain saved instance state, ViewModel, and persistent storage?
  • Can you distinguish explicit intents from implicit intents?
  • Can you pass and retrieve strings and integers using intent extras?
  • Can you launch a website and share text using implicit intents?
  • Can you create a layout using XML or a screen using Jetpack Compose?
  • Can you validate form input and handle button clicks?
  • Can you explain activity navigation and Back stack behavior?
  • Can you troubleshoot UI errors using Logcat?

13. Conclusion

Preparing for Android lifecycle, intents, and UI development questions requires both conceptual understanding and hands-on practice. Lifecycle knowledge helps developers manage resources and preserve user experience, intents enable component communication and navigation, and UI development skills help create responsive and accessible screens.

By practicing lifecycle logging, activity navigation, intent data transfer, form validation, and state restoration, learners can develop the confidence needed for Android development assignments and technical interviews.

Continue learning with JustAcademy's Android App Development Course, explore the course demo registration page, and visit the JustAcademy website for additional learning opportunities.

Previous Next
whatsapp