Most Frequently asked Android Interview Questions

author image Hirely
at 05 Jan, 2025

Question: What is the difference between an Activity and a Fragment in Android?

Answer:

In Android, both Activity and Fragment are fundamental components used to build user interfaces and manage the app’s flow. While they are related, they serve different purposes and have distinct characteristics. Understanding the difference between them is important for designing an efficient and flexible Android application.

1. Definition:

  • Activity:

    • An Activity represents a single screen in an Android application. It acts as the entry point for a user’s interaction with the app.
    • An activity is typically tied to a single UI screen (e.g., a login screen, a settings screen).
    • Each Android app has at least one activity, typically called the MainActivity.
  • Fragment:

    • A Fragment is a reusable portion of an activity’s user interface. It represents a modular section of an activity’s layout and behavior.
    • A fragment can be thought of as a sub-activity that helps break the activity into smaller, more manageable pieces.
    • Fragments are designed to be used within an activity to create dynamic UIs, especially for flexible layouts like tablets and smartphones.

2. Lifecycle:

  • Activity Lifecycle:
    • An activity has its own lifecycle, controlled by methods such as onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). These methods control how an activity is created, paused, resumed, and destroyed.
  • Fragment Lifecycle:
    • A fragment has its own lifecycle but is closely tied to the activity’s lifecycle. Fragments use similar lifecycle methods (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc.) but are invoked in conjunction with the activity’s lifecycle.
    • Additionally, fragments have methods like onAttach(), onCreateView(), and onDetach(), which are specific to fragments.
    • Fragments are created and destroyed when their parent activity is created or destroyed, but they can be reused across different activities.

3. Purpose and Use Cases:

  • Activity:

    • An activity is generally used to represent an entire screen and handles all of the UI and interaction for that screen. It manages the UI layout and event handling for the entire screen.
    • For example, an activity might display a form, a list of items, or an interactive game screen.
  • Fragment:

    • A fragment is used to represent a part of an activity’s UI or a part of the functionality of the app. Fragments allow you to create flexible and modular UIs that can adapt to different screen sizes and orientations.
    • For example, a fragment could represent a settings section, list of items, or map view that can be added to different activities or even used on different screen orientations (like phone and tablet).

4. Reusability:

  • Activity:
    • Activities are typically not reused across multiple screens in an app. Each activity is designed to manage a single UI screen, and navigation between activities usually requires starting a new activity (via Intents).
  • Fragment:
    • Fragments are reusable and can be added or replaced within multiple activities. They allow for more modular and flexible UI designs. For example, you can add the same fragment to different activities or dynamically replace fragments based on user interaction.

5. Interaction:

  • Activity:

    • An activity handles communication between the user and the system. It receives inputs, manages UI elements, and can perform actions based on those inputs.
    • Activities can communicate with each other via Intents, which are messages used to start activities or pass data between them.
  • Fragment:

    • A fragment communicates with its parent activity through interfaces and can interact with other fragments by calling methods on them.
    • Fragments can also share data through Bundle objects or ViewModel (in the case of architecture components).

6. UI Management:

  • Activity:
    • An activity is responsible for inflating the layout and controlling the entire UI of a screen.
  • Fragment:
    • A fragment is responsible for inflating a portion of the layout, often for more complex UIs. Multiple fragments can be combined within an activity to create a complete screen. For example, one fragment can manage a list view, while another fragment can manage a detailed view.

7. Example:

  • Activity Example:

    • A LoginActivity where a user enters their credentials. This activity could include the UI elements for the login form and manage user authentication.
  • Fragment Example:

    • A UserProfileFragment that displays the user’s profile information. This fragment can be used in different activities, such as a HomeActivity or a SettingsActivity.

8. Fragment Transactions:

  • Activity:

    • Activities are generally static and manage their lifecycle from start to end. Transition between activities involves a new activity being launched.
  • Fragment:

    • Fragments support dynamic operations. You can add, remove, or replace fragments within an activity during runtime using FragmentTransaction. This enables flexible UI designs where fragments can be updated or swapped dynamically without restarting the entire activity.
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, new MyFragment());
    fragmentTransaction.commit();

9. Example Comparison:

Activity Example:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // Set up the activity layout
    }
}

Fragment Example:

public class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the fragment layout
        return inflater.inflate(R.layout.fragment_example, container, false);
    }
}

Summary of Differences:

FeatureActivityFragment
PurposeRepresents a full screen UI.Represents a modular section of an activity’s UI.
LifecycleIndependent lifecycle.Lifecycle is tied to the activity’s lifecycle.
UI ManagementManages full-screen UI.Manages a portion of UI.
ReusabilityNot easily reusable.Reusable across multiple activities.
InteractionUses Intents to communicate.Communicates with its parent activity via interfaces.
Use CasesUsed for single-screen UI.Used for creating dynamic, modular UIs.

Conclusion:

  • Activity is the basic building block of an app that handles a full screen of user interaction.
  • Fragment is a modular UI component that can be reused and dynamically adjusted within activities, allowing for more flexible and adaptable user interfaces.

Question: What is an Intent in Android?

Answer:

An Intent in Android is a messaging object that is used to request an action from another component of the application or from the Android system. It is a crucial part of the Android app’s communication mechanism, allowing components such as activities, services, and broadcast receivers to interact with each other.

There are two main types of intents in Android:

  1. Explicit Intent
  2. Implicit Intent

1. Explicit Intent:

An explicit intent is used to start a specific activity or service within the same application. It explicitly defines the component (activity or service) to be invoked by specifying the class name of the target component.

Example of Explicit Intent:

Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);

In the above example:

  • The Intent is created with the current context (this) and the target activity (TargetActivity.class).
  • The startActivity(intent) method is used to launch the target activity.

2. Implicit Intent:

An implicit intent does not specify a specific component but instead declares a general action to be performed, which can be handled by any component that can respond to that action. The Android system will find the appropriate component to handle the intent, based on the registered filters in the system.

Example of Implicit Intent:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"));
startActivity(intent);

In this example:

  • The Intent.ACTION_VIEW is an implicit action to display data (in this case, a URL).
  • The Uri.parse("https://www.example.com") specifies the data (the URL).
  • Android will launch the appropriate app (e.g., a web browser) that can handle the ACTION_VIEW intent.

Key Features of Intents:

  • Start Activities: Intents are used to navigate between different activities in an app, or to launch activities from different apps.

    • Example: Launch a new screen (Activity), like opening a camera or launching a web browser.
  • Start Services: Intents are also used to start background services, such as downloading data or performing background tasks.

    • Example: Start a service to download a file in the background.
  • Send Broadcasts: Intents can be used to send broadcasts to multiple receivers. Broadcasts allow apps to communicate across different parts of the system.

    • Example: Notify all apps when a new message is received.
  • Pass Data Between Components: Intents can carry data to be used by the target activity or service using extras (putExtra() method) or Uri data.

    • Example: Passing information such as a user’s name or settings to another activity.

Passing Data in an Intent:

You can put additional data in an intent, which can be retrieved by the target activity or service.

Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("username", "JohnDoe");
startActivity(intent);

In the target activity (TargetActivity), you can retrieve the data like this:

String username = getIntent().getStringExtra("username");

Common Methods in Intents:

  • putExtra(String name, Bundle value): Adds additional data (bundle) to the intent.
  • putExtra(String name, String value): Adds a String data to the intent.
  • getStringExtra(String name): Retrieves String data from the intent.
  • setAction(String action): Sets the action of the intent, which indicates what kind of action is to be performed (e.g., ACTION_VIEW).
  • setData(Uri data): Sets the data (e.g., a URI) to be used by the target component.
  • setFlags(int flags): Sets special flags to modify the behavior of the intent (e.g., FLAG_ACTIVITY_NEW_TASK).

Use Cases of Intents:

  1. Navigating Between Activities:

    • Intents are used to launch one activity from another. For instance, clicking a button might take the user to another activity where they can input data.
  2. Opening External Apps:

    • Intents are used to launch external apps (e.g., opening the camera, calling the dialer, or opening a URL in a browser).
  3. Starting Services:

    • Intents can be used to start background services that perform tasks such as downloading files or playing music.
  4. Sending Broadcasts:

    • Intents can be sent to broadcast receivers, for example, sending a broadcast to inform other apps or the system about a change, like an incoming message or network connectivity status change.

Example Use Case: Launching a Web Page (Implicit Intent):

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"));
startActivity(intent);

Here, the implicit intent requests the Android system to open the URL with any app that can handle it (like a web browser).

Example Use Case: Sending Data Between Activities (Explicit Intent):

Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("userName", "JohnDoe");
startActivity(intent);

In TargetActivity, you can retrieve the data:

String userName = getIntent().getStringExtra("userName");

Summary:

  • An Intent is a messaging object used to perform actions such as navigating between activities, starting services, or broadcasting events.
  • Explicit intents target specific components by specifying their class names.
  • Implicit intents specify a general action to be performed, and the system finds the appropriate component to handle it.
  • Intents are also used to pass data between components and manage inter-component communication in Android apps.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as android interview questions, android interview experiences, and details about various android job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now