Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Fragment Lifecycle in Android

The lifecycle of a Fragment in Android consists of various callback methods which indicate states the Fragment transitions through. Understanding this lifecycle is crucial for developing robust and bug-free Android apps, as it helps in ensuring that resources are used efficiently and user experiences remain consistent.

Here's a brief description of the Fragment lifecycle:

  1. onAttach():

    • Called when the fragment has been associated with an activity.
    • The fragment can access the activity instance using getActivity() method after this callback.
  2. onCreate():

    • The system calls this when creating the fragment.
    • Initialization that needs to be retained beyond the fragment's lifecycle should be done here.
  3. onCreateView():

    • Called to create the view hierarchy of the fragment.
    • Returns the root view for the fragment's UI, or null if the fragment doesn't provide a UI.
  4. onViewCreated():

    • Called after onCreateView() completes.
    • This is useful for obtaining references to views and setting up any listeners.
  5. onActivityCreated():

    • Called when the onCreate() method of the parent activity completes.
    • Indicates that the activity's lifecycle is now initialized enough that you can start interacting with it.
  6. onViewStateRestored():

    • Called when restoring the view state from a saved instance.
  7. onStart():

    • Fragment becomes visible to the user.
    • UI preparations that are done here should be light to ensure a fast user experience.
  8. onResume():

    • Fragment is running and user can interact with it.
    • Always followed by onPause().
  9. onPause():

    • The fragment is going to the background, but remains visible.
    • Used to store changes that should be persisted beyond the current user session.
  10. onStop():

    • Fragment is no longer visible to the user.
    • Always followed by either onStart() or onDestroy().
  11. onDestroyView():

    • Called when the view hierarchy associated with the fragment is being removed.
    • Good place to clean up resources related to the UI.
  12. onDestroy():

    • Called to indicate the fragment is no longer in use.
    • Clean up remaining resources that won't be needed anymore.
  13. onDetach():

    • Fragment is being disassociated from its activity.
    • Clean up any references set up in onAttach().

Additionally, there are a few other methods related to saving and restoring the state:

  • onSaveInstanceState(): Allows saving the state before the fragment is stopped, so that the state can be restored later.

  • onConfigurationChanged(): Called when a configuration change occurs (like a change in device orientation) that doesn't lead to the fragment being destroyed.

It's important to remember that a Fragment's lifecycle is closely tied to its hosting activity's lifecycle. If the activity is paused, all fragments in it are also paused. Similarly, when the activity is destroyed, all fragments will be destroyed. However, a fragment may be added, replaced, or removed without the activity going through a lifecycle transition.

  1. Handling configuration changes in Fragment lifecycle:

    • Description: When the device undergoes a configuration change (like a screen rotation), the fragment might be destroyed and recreated. You can retain essential data during these changes using setRetainInstance(true) or by handling the changes in onSaveInstanceState.
    • Code:
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setRetainInstance(true);
      }
      
  2. Creating and destroying Fragments in Android:

    • Description: Fragments are created and destroyed by the host activity. The FragmentManager is used to add, replace, or remove fragments dynamically.
    • Code:
      // Create a new fragment
      MyFragment fragment = new MyFragment();
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
      transaction.add(R.id.fragment_container, fragment);
      transaction.commit();
      
      // Remove a fragment
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
      transaction.remove(fragment);
      transaction.commit();
      
  3. Fragment state restoration in Android:

    • Description: Fragment state can be restored by saving and restoring instance states. This is often done in onSaveInstanceState and by retrieving the state in onCreate.
    • Code:
      @Override
      public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          outState.putString("key", "value");
      }
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          if (savedInstanceState != null) {
              String value = savedInstanceState.getString("key");
          }
      }
      
  4. Using onSaveInstanceState in Fragment lifecycle:

    • Description: onSaveInstanceState is called before the fragment is potentially destroyed. It allows saving essential data to the Bundle for later restoration.
    • Code:
      @Override
      public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          outState.putString("key", "value");
      }