Android Interview Questions Cheat Sheet

author image Hirely
at 05 Jan, 2025

Question:

What is the role of the Android Application class?

Answer:

The Application class in Android plays a crucial role in managing the global state of the application. It is a base class for maintaining global application state, and it is instantiated before any activity, service, or receiver in the application. The Application class is designed to provide a central location to initialize resources that need to persist throughout the app’s lifecycle, such as singletons, global variables, or shared resources.

Here’s a detailed explanation of the role and usage of the Application class:


1. Global State Management:

  • The Application class allows you to store data that you want to access across multiple activities, services, and components of the app. For example, you can use it to maintain global variables, singleton instances, or shared resources like network clients or database connections.

2. Application Initialization:

  • It provides a good place to perform application-wide initialization tasks, such as setting up third-party libraries, initializing analytics tools, or setting up a network client or database connection.
  • The onCreate() method of the Application class is called when the application is first started, before any other components like activities or services.

3. Access Across Components:

  • The Application class is available globally across all activities, services, and other components in the app. You can access it easily from anywhere in the app using:
    Application app = getApplicationContext();

4. Singleton Storage:

  • The Application class is often used to store singleton instances that need to be shared across activities or services. This ensures that a single instance of a resource is used throughout the app, such as a shared database manager, networking client, or cache.

5. Memory Management:

  • It also provides an opportunity to clean up resources when the app is terminated or backgrounded. For example, you can override onTerminate() (though this is rarely used since it is not called on Android devices in most cases) or handle memory-related issues when your app is low on resources.

How to Use the Application Class:

  1. Create a Custom Application Class: You can create a custom Application class by extending the base Application class.

    public class MyApplication extends Application {
        private static MyApplication instance;
    
        @Override
        public void onCreate() {
            super.onCreate();
            instance = this;
            // Initialize global resources here
        }
    
        public static MyApplication getInstance() {
            return instance;
        }
    }
  2. Declare the Application Class in the AndroidManifest.xml: After creating the custom Application class, you need to declare it in your AndroidManifest.xml file so that Android knows to use it when the app starts.

    <application
        android:name=".MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name">
        <!-- Other components like activities and services -->
    </application>
  3. Access the Application Class: You can access the Application class from anywhere in your app, for example:

    MyApplication app = (MyApplication) getApplicationContext();

Use Cases for the Application Class:

  1. Global Data or Singleton Initialization:

    • If you need to set up a singleton (such as a singleton database manager or API client) that is used throughout the app, you can initialize it in the onCreate() method of the Application class.

    Example:

    public class MyApplication extends Application {
        private static MyDatabase database;
    
        @Override
        public void onCreate() {
            super.onCreate();
            database = new MyDatabase(getApplicationContext());
        }
    
        public static MyDatabase getDatabase() {
            return database;
        }
    }
  2. Third-Party Library Initialization:

    • For third-party libraries such as Firebase, Analytics, or Crashlytics, you can initialize them in the onCreate() method of the Application class. This ensures they are ready to be used by any part of the app right from the start.

    Example:

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseApp.initializeApp(this);
    }
  3. Global Shared Preferences:

    • You can use the Application class to set up shared preferences or any other shared resource that needs to persist across activities.

Important Methods in the Application Class:

  • onCreate():
    This method is called when the application is created and is the place to initialize global resources, libraries, or singletons.

  • onTerminate():
    This method is rarely used, as it is not called in most Android environments. It would be used for cleanup tasks when the app is terminated, but it is generally not necessary.

  • getApplicationContext():
    This method returns the Context object associated with the Application class, which can be used to get access to system services and shared resources.


Example Use Case:

Here’s a simple example where we use the Application class to set up a singleton object:

public class MyApplication extends Application {
    private static MyDatabase database;

    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize the database only once
        if (database == null) {
            database = new MyDatabase(getApplicationContext());
        }
    }

    public static MyDatabase getDatabase() {
        return database;
    }
}

In any Activity, you can now access the singleton database instance like this:

MyDatabase db = MyApplication.getDatabase();

Summary of the Role of the Android Application Class:

  • The Application class provides a central location for managing global state and resources in an Android app.
  • It allows you to initialize singletons, third-party libraries, and shared resources early in the app’s lifecycle.
  • It is also a good place to perform cleanup tasks and manage resources that persist throughout the application’s runtime.

The Application class helps ensure consistency across activities and components, making it easier to manage resources in a well-organized manner.

Question:

What are the different types of storage in Android?

Answer:

Android provides several options for storing data, ranging from temporary storage that is cleared when the app is closed to persistent storage that remains available even after the app is closed or the device is restarted. Below are the different types of storage available in Android:


1. Internal Storage:

  • Description: Internal storage is private to the application. Files saved here can only be accessed by the app that created them. When the app is uninstalled, the files stored in internal storage are deleted.

  • Use Case: Store sensitive data such as authentication tokens, user preferences, or database files that should not be shared with other apps or users.

    How to Use:

    • Store files using Context.getFilesDir().
    • Data stored in this area is private to the application by default.

    Example:

    FileOutputStream fos = openFileOutput("file.txt", Context.MODE_PRIVATE);
    fos.write("Hello, World!".getBytes());
    fos.close();

2. External Storage:

  • Description: External storage is not necessarily a physical SD card, as it includes both removable and non-removable storage areas (e.g., the device’s shared storage space). Files in external storage can be shared between different apps and users.

  • Use Case: Store large files like images, videos, or downloads that should be accessible by other apps or users. Also used for backups.

    How to Use:

    • Files can be saved using the Environment.getExternalStorageDirectory() method or Context.getExternalFilesDir().
    • For Android 10 (API level 29) and higher, apps should use Scoped Storage to access files in external storage, which limits access to specific directories within external storage.

    Example:

    File externalFile = new File(Environment.getExternalStorageDirectory(), "example.txt");
    FileOutputStream fos = new FileOutputStream(externalFile);
    fos.write("Hello from External Storage!".getBytes());
    fos.close();

    Note: Android 6.0 and above requires runtime permissions to read/write to external storage. In Android 10 and above, Scoped Storage applies, which restricts how apps access external storage.


3. Shared Preferences:

  • Description: Shared Preferences is a key-value storage system that allows you to store small amounts of data (e.g., user settings, preferences) in a persistent manner. It is typically used for storing simple data like user settings or app preferences.

  • Use Case: Store simple data such as settings (e.g., theme, language) or user preferences.

    How to Use:

    • Store data using SharedPreferences.Editor and retrieve it using SharedPreferences.getString(), getInt(), etc.

    Example:

    SharedPreferences sharedPref = getSharedPreferences("user_prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("username", "john_doe");
    editor.putInt("age", 30);
    editor.apply();

4. SQLite Database:

  • Description: SQLite is a lightweight relational database that is embedded in Android. It is used for storing structured data in a table format (rows and columns). SQLite databases are stored in the app’s internal storage by default, and they can be accessed using SQL queries.

  • Use Case: Store structured data like user records, app data, or any data requiring complex queries and relationships.

    How to Use:

    • Create a subclass of SQLiteOpenHelper to manage database creation and version management.

    Example:

    SQLiteOpenHelper dbHelper = new MyDatabaseHelper(context);
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("name", "John Doe");
    db.insert("users", null, values);

5. Cloud Storage (Firebase/Google Drive):

  • Description: Cloud storage allows you to store data on a remote server, making it accessible across multiple devices and platforms. Firebase and Google Drive are commonly used for cloud storage in Android applications.

  • Use Case: Store large files or data that needs to be shared across devices or platforms. It is also useful for syncing data between multiple devices and providing remote backups.

    How to Use:

    • Firebase provides FirebaseStorage for file storage and Firestore for database storage.
    • Google Drive can be accessed using the Google Drive API.

    Example (Firebase Storage):

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReference();
    Uri file = Uri.fromFile(new File("path/to/image.jpg"));
    StorageReference imageRef = storageRef.child("images/" + file.getLastPathSegment());
    imageRef.putFile(file);

6. Content Providers:

  • Description: Content Providers allow apps to share data with other apps securely. They abstract the underlying data storage (e.g., databases, files) and provide a standardized interface for data access. This is typically used for sharing data between apps.

  • Use Case: Share data with other apps or access data from other apps, such as contacts, media, and calendar events.

    How to Use:

    • Content providers are accessed using ContentResolver and provide access to various types of data through a URI-based interface.

    Example:

    ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://contacts/people"), null, null, null, null);

7. Network Storage (e.g., HTTP, FTP, etc.):

  • Description: Data can also be stored remotely on a server via network protocols like HTTP, FTP, or other cloud-based storage solutions.

  • Use Case: Store data remotely and access it over a network. Ideal for apps requiring synchronization between devices or users, or when large amounts of data need to be accessed remotely.

    How to Use:

    • Use standard networking methods in Android, such as HttpURLConnection, Retrofit, or Volley, to upload and download data from servers.

    Example (Retrofit):

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.example.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    
    ApiService service = retrofit.create(ApiService.class);
    Call<User> call = service.getUserDetails();
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            // Handle response
        }
    
        @Override
        public void onFailure(Call<User> call, Throwable t) {
            // Handle failure
        }
    });

8. Cache Storage:

  • Description: Cache storage is used for temporarily storing data that might be reused soon. It helps improve performance by reducing the need to fetch data from a remote server or read from storage repeatedly.

  • Use Case: Store temporary data like images, network responses, or app resources that are likely to be used again shortly.

    How to Use:

    • Android offers the CacheDir for temporary files that should be deleted when the app is uninstalled, and the HttpCache for caching network responses.

9. Shared Files (App-Specific):

  • Description: Each app can store files that are accessible to other apps in specific directories in external storage. For instance, app-specific files are stored in a sandboxed area on the external storage that other apps cannot access without explicit permissions.

  • Use Case: Store files that are specific to your app but should be accessible for sharing or export.

    How to Use:

    • Use getExternalFilesDir() to store app-specific files on external storage.

    Example:

    File file = new File(getExternalFilesDir(null), "example.txt");

Summary of Different Types of Storage in Android:

  • Internal Storage: Private, persistent data storage.
  • External Storage: Shared, persistent storage that can be accessed by other apps.
  • Shared Preferences: Simple key-value pair storage for app settings.
  • SQLite Database: Relational database for structured data.
  • Cloud Storage (Firebase/Google Drive): Remote data storage.
  • Content Providers: Share data with other apps securely.
  • Network Storage: Remote data storage over HTTP, FTP, etc.
  • Cache Storage: Temporary storage for frequently used data.
  • Shared Files (App-Specific): Files stored in external storage but specific to the app.

These different storage types provide flexibility in how apps can handle and persist data, ensuring that developers can choose the best storage solution for their specific use cases.

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