How do you handle screen rotation in Android to prevent data loss?

Basic

How do you handle screen rotation in Android to prevent data loss?

Overview

Handling screen rotation in Android is crucial to prevent data loss during configuration changes, such as rotating the device from portrait to landscape mode. By default, Android restarts the activity on rotation, leading to the loss of user input or state. Understanding how to manage this behavior is essential for creating smooth and user-friendly Android applications.

Key Concepts

  1. Activity Lifecycle: Understanding how activity states change during screen rotation.
  2. onSaveInstanceState and onRestoreInstanceState: Methods to save and restore UI state.
  3. ViewModels: Using ViewModel to retain data across configuration changes.

Common Interview Questions

Basic Level

  1. What happens to an Android activity when you rotate the screen?
  2. How do you save an activity's state during a screen rotation?

Intermediate Level

  1. How does ViewModel help in handling screen rotation in Android?

Advanced Level

  1. Discuss strategies to handle complex data restoration after screen rotation without using ViewModel.

Detailed Answers

1. What happens to an Android activity when you rotate the screen?

Answer: When the screen is rotated, Android destroys and then recreates the activity to load the layout resources that match the new orientation. This process involves calling the activity's lifecycle callbacks: onPause(), onStop(), and onDestroy(), followed by onCreate(), onStart(), and onResume() with the new configuration.

Key Points:
- Activity is destroyed and recreated.
- Lifecycle methods are called in sequence.
- By default, any user input or state is lost.

Example:

public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Initialization code here
        Console.WriteLine("Activity Created");
    }

    // Add other lifecycle methods if needed to log or handle specific events
}

2. How do you save an activity's state during a screen rotation?

Answer: Use the onSaveInstanceState method to save the activity's state and onRestoreInstanceState or onCreate with the savedInstanceState parameter to restore it. Bundle objects are used to save the state in key-value pairs.

Key Points:
- onSaveInstanceState is used to save state.
- State is restored in onCreate or onRestoreInstanceState.
- Use Bundle for key-value storage.

Example:

protected override void OnSaveInstanceState(Bundle outState)
{
    base.OnSaveInstanceState(outState);
    outState.PutString("savedText", "This is saved instance state");
}

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    // Restore state
    if (savedInstanceState != null)
    {
        string savedText = savedInstanceState.GetString("savedText");
        Console.WriteLine($"Restored state: {savedText}");
    }
}

3. How does ViewModel help in handling screen rotation in Android?

Answer: ViewModel is part of the Android Architecture Components and is designed to store and manage UI-related data in a lifecycle-conscious way. It survives configuration changes such as screen rotations, preventing the loss of data.

Key Points:
- ViewModel survives configuration changes.
- It helps in managing UI-related data efficiently.
- Reduces the need for handling save and restore state manually.

Example:

public class MainViewModel : ViewModel
{
    public string Data { get; set; } = "Persistent Data";

    // ViewModel logic here
}

// In your activity
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    MainViewModel viewModel = new ViewModelProvider(this).Get(typeof(MainViewModel).Name);
    Console.WriteLine($"Data from ViewModel: {viewModel.Data}");
}

4. Discuss strategies to handle complex data restoration after screen rotation without using ViewModel.

Answer: For complex data restoration without ViewModel, one can use:
- Static Data Members: Store data in static fields or properties. However, this approach risks memory leaks and is not recommended.
- Singleton Pattern: Use a singleton class to persist data across configuration changes.
- Fragment setRetainInstance(true): Use a non-UI Fragment with setRetainInstance(true) to hold data. This fragment is not destroyed during screen rotation.

Key Points:
- Each method has its own trade-offs.
- Care must be taken to avoid memory leaks.
- Proper lifecycle management is crucial.

Example:

// Using a singleton pattern
public class DataHolder
{
    public string Data { get; set; } = "Complex Data";
    private static DataHolder instance;

    private DataHolder() {}

    public static DataHolder Instance => instance ?? (instance = new DataHolder());
}

// Usage in Activity
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    string data = DataHolder.Instance.Data;
    Console.WriteLine($"Data from Singleton: {data}");
}

This guide covers the basic to advanced concepts regarding handling screen rotation in Android, focusing on preventing data loss.