BCA / B.Tech 78 min read

Most Important Questions for Android Programming

Most Important Questions for Android Programming (Exam Special)

Short Answer Questions

  1. What is Android?
    Android is an open-source, Linux-based mobile operating system developed by Google. It is designed for smartphones, tablets, smartwatches, and TVs.
  2. What is an Activity?
    An Activity represents a single screen in an app with which a user can interact. It is a fundamental building block of the user interface.
  3. What is an Intent?
    An Intent is a messaging object used to facilitate communication between app components. It is used to start activities, launch services, and send broadcasts.
  4. What is the AndroidManifest.xml file?
    It is a configuration file in the root directory of every Android app. It provides essential information about the app's components, permissions, and hardware features to the Android system.
  5. What is Gradle?
    Gradle is an advanced build system used in Android Studio to build, test, and package the app. It manages dependencies and automates the build process.
  6. What is Logcat?
    Logcat is a tool in Android Studio that displays real-time messages generated by the system and the app. It is used for debugging to view errors and logs.
  7. What is the full form of AVD?
    The full form of AVD is Android Virtual Device. It is an emulator configuration that allows you to simulate a specific Android device on your computer.
  8. What is a Fragment?
    A Fragment is a reusable portion of an activity's UI. An activity can host multiple fragments at once, which is very useful for tablet UIs.
  9. What is a Service?
    A Service is an application component that can perform long-running operations in the background without a user interface.
  10. What is the use of a Content Provider?
    A Content Provider is used to share data between applications. It manages data access and provides security.
  11. What is a Toast?
    A Toast is a small popup message that appears on the screen for a short duration. It is used to provide simple feedback to the user.
  12. What does the findViewById() method do?
    This method finds a view defined in an XML layout file based on its unique ID and returns its reference in the Java code.
  13. What are Layouts?
    Layouts are `ViewGroup`s that define the arrangement of UI widgets on the screen. Examples: LinearLayout, RelativeLayout, ConstraintLayout.
  14. What is SQLite?
    SQLite is a lightweight, serverless SQL database engine that comes built-in with Android. It is used to store structured data.
  15. What is the full form of APK?
    The full form of APK is Android Package Kit. It is the file format that the Android OS uses to distribute and install mobile apps.
  16. What is the `R.java` file?
    It is a file automatically generated by Android Studio. It contains unique integer IDs for all the resources in the `res` directory (like layouts, strings, drawables).
  17. What is the full form of ADB?
    The full form of ADB is Android Debug Bridge. It is a command-line tool that lets you communicate with a device (emulator or physical).
  18. What is the use of `setContentView()`?
    This method is used to set the UI for an activity. It inflates an XML layout file and displays it on the screen.
  19. What is the difference between an Explicit Intent and an Implicit Intent?
    An Explicit Intent is used to start internal components of an app (like from one activity to another). An Implicit Intent is used to ask the system to perform an action (like sending an email).
  20. What is an ANR?
    ANR stands for "Application Not Responding." It is a dialog that appears when the UI thread is blocked for a long time (more than 5 seconds).

Medium Answer Questions

  1. Explain the main methods of the Activity Lifecycle in order.
    The main methods of the Activity Lifecycle are:
    • onCreate(): When the activity is first created. The UI is initialized here.
    • onStart(): When the activity is about to become visible to the user.
    • onResume(): When the activity comes to the foreground and the user can interact.
    • onPause(): When the activity loses focus (e.g., a dialog appears).
    • onStop(): When the activity is completely invisible to the user.
    • onRestart(): When a stopped activity is starting again.
    • onDestroy(): When the activity is being destroyed from memory.
    This flow ensures that the app manages resources efficiently.
  2. How are SharedPreferences used to save data? Provide a small code snippet.
    SharedPreferences are used to save simple key-value pairs, which is ideal for user settings. To save data, we use `SharedPreferences.Editor`.
    
    // Saving Data
    SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("username", "Ravi");
    editor.apply();
    
    // Loading Data
    String name = prefs.getString("username", "DefaultUser");
            
  3. What are the main differences between ListView and RecyclerView?
    • ViewHolder Pattern: RecyclerView enforces the ViewHolder pattern, which improves performance. It is optional in ListView.
    • Layout Manager: RecyclerView has a LayoutManager that positions items (e.g., LinearLayoutManager, GridLayoutManager). ListView only supports a vertical list.
    • Flexibility: RecyclerView is more flexible for item animations and customization.
    `RecyclerView` should always be used in modern development.
  4. How are permissions handled in Android? (Manifest and Runtime)
    Permissions in Android are handled in two ways:
    • Install-time (Manifest) Permissions: These are normal permissions that are granted when the app is installed. They are declared in `AndroidManifest.xml`, such as `android.permission.INTERNET`.
    • Runtime Permissions: These are dangerous permissions (like `CAMERA`, `LOCATION`, `SEND_SMS`) that must be requested from the user while the app is running (at runtime). This was introduced in Android 6.0 (API 23).
  5. Describe two ways to handle screen orientation changes.
    1. Save/Restore State (Recommended): Use the `onSaveInstanceState()` method to save data to a `Bundle` and restore it in `onCreate()`. This prevents data loss when the activity is recreated.
    2. Handle Configuration Change: Add `android:configChanges="orientation|screenSize"` to the `` tag in `AndroidManifest.xml`. This prevents the activity from being recreated, but you have to manually handle UI changes in the `onConfigurationChanged()` method.
  6. What are the main methods of the Fragment Lifecycle?
    The Fragment Lifecycle is tied to the activity lifecycle. Its main methods are: `onAttach()`, `onCreate()`, `onCreateView()` (to inflate the layout), `onViewCreated()`, `onStart()`, `onResume()`, `onPause()`, `onStop()`, `onDestroyView()` (to destroy the view), `onDestroy()`, and `onDetach()`.
  7. What is the purpose of the SQLiteOpenHelper class? Name its two main methods.
    The `SQLiteOpenHelper` class simplifies database creation and version management.
    • onCreate(SQLiteDatabase db): This method is called when the database is first created. It is used to create tables and initial data.
    • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion): This is called when the `DATABASE_VERSION` is incremented. It is used to update the database schema (e.g., alter a table).
  8. How would you use an Intent to send an email from an app?
    An Implicit Intent with the action `ACTION_SEND` is used to send an email. You add the recipient, subject, and body using `putExtra` and set the type to `"message/rfc822"` to ensure only email clients handle it.
    
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Email Body");
    startActivity(Intent.createChooser(intent, "Send Email"));
            
  9. What is the difference between the `drawable` and `mipmap` folders?
    • `drawable`: This folder is used for general graphics (like images, shapes, backgrounds).
    • `mipmap`: This folder is used specifically for app launcher icons. The Android system optimizes the `mipmap` folder to pick the best quality icon for different screen densities, even if the app doesn't provide resources for that density.
  10. What is a Notification Channel and why is it important?
    Notification Channels were introduced in Android 8.0 (API 26). They give users control over managing different types of notifications from an app. Developers must define a channel for each notification (e.g., "Messages," "Updates"). The user can block or customize individual channels, which improves the user experience.
  11. What is the difference between Internal and External Storage?
    • Internal Storage: This is the app's private storage. Data saved here is secure and cannot be accessed by other apps. This data is deleted when the app is uninstalled.
    • External Storage: This is public/shared storage (like an SD card). Data saved here can be accessed by the user and other apps. It is suitable for large files (photos, videos).
  12. What are the advantages of using `ConstraintLayout`?
    `ConstraintLayout` is a flexible and powerful layout. Its advantages are:
    • Flat View Hierarchy: It reduces the need for nested layouts, which improves performance.
    • Flexible Rules: You can position child views with complex rules (constraints) relative to the parent or other views.
    • Responsive UI: It makes it easier to build responsive UIs for different screen sizes.
  13. What is the difference between a Context Menu and an Options Menu?
    • Options Menu: This is the primary menu for an activity and appears in the Action Bar/Toolbar. It is for actions related to the entire screen (e.g., Settings, Search).
    • Context Menu: This appears when a user long-presses a specific view. It is for actions related to that particular item (e.g., Edit, Delete).
  14. What is the difference between a Service and a Thread?
    • Thread: This is a path of execution separate from the UI thread, used to perform a background task so the UI doesn't freeze. It is part of the app process and gets killed when the app is destroyed.
    • Service: This is an Android component that runs in the background, even if the app is not visible. It runs on the UI thread by default (unless you create a new thread inside it) and has its own lifecycle.
  15. What is the use of WebView? What is one security precaution when using it?
    WebView is used to display web pages (HTML, CSS, JS) inside an app.

    Security Precaution: By default, JavaScript is disabled. If you use `setJavaScriptEnabled(true)`, you must be careful not to load untrusted web content, as it can expose vulnerabilities like Cross-Site Scripting (XSS).

  16. What is the difference between `build.gradle (Project)` and `build.gradle (Module)`?
    • `build.gradle (Project)`: This is the top-level build file. It defines common configurations for all modules in the project (like repositories, gradle plugin versions).
    • `build.gradle (Module)`: This defines specific configurations for each individual app module (like `applicationId`, `minSdkVersion`, `targetSdkVersion`, dependencies).
  17. What is the use of the `SmsManager` class?
    The `SmsManager` class is used to programmatically send SMS messages from an app. Its `sendTextMessage()` method takes a destination address and message body. It requires the `SEND_SMS` permission.
  18. What is the significance of the `scaleType` attribute in an `ImageView`?
    The `scaleType` attribute controls how an image is resized to fit the size of the `ImageView`. Common values are:
    • `fitCenter`: Fits the image inside the view while maintaining its aspect ratio.
    • `centerCrop`: Scales the image to completely fill the view, cropping any extra parts.
    • `centerInside`: Centers the image inside the view and only scales it down if it is larger than the view.
  19. Why is it necessary to create a custom adapter?
    `ArrayAdapter` is good for simple lists with a single `TextView`. When you need a complex list item layout (e.g., an image and two text fields), you need to create a custom adapter by extending `BaseAdapter` or `RecyclerView.Adapter` so you can map the data to the custom layout.
  20. Why is `AsyncTask` deprecated and what is its modern alternative?
    `AsyncTask` is deprecated due to problems like memory leaks and state loss on configuration changes. In modern Android development, it is recommended to use Kotlin Coroutines or, for Java, Executors and Handlers/LiveData for background tasks.

Long Answer Questions

  1. Explain the Android Architecture in detail with a diagram.
    The Android Architecture is divided into five main layers:
    • 1. Linux Kernel: This is the base of the architecture. It provides an abstraction layer between the hardware and the software. It handles core system services like memory management, process management, power management, and device drivers (camera, display, WiFi).
    • 2. Hardware Abstraction Layer (HAL): This provides a standard interface between the higher-level Java API framework and the device drivers. It makes Android independent of device-specific driver implementations.
    • 3. Android Runtime (ART) and Native C/C++ Libraries:
      • ART: Since Android 5.0, ART has replaced the Dalvik VM. It executes app bytecode. It uses Ahead-of-Time (AOT) compilation, which improves app performance and battery life.
      • Native Libraries: The Android platform uses native libraries written in C/C++ for many core features (like graphics, media, database). Examples: SQLite, WebKit, OpenGL ES.
    • 4. Java API Framework: This is the layer that developers primarily interact with. It provides a set of feature-rich APIs used for high-level tasks. It includes: Activity Manager, Content Providers, Resource Manager, Notification Manager, etc.
    • 5. System Apps (Applications Layer): This is the top layer. It includes core system apps (like Phone, Contacts, Browser) and third-party apps installed by the user. All these apps are built using the Java API Framework.
  2. Describe the complete process of publishing an application to the Google Play Store.
    The process of publishing an application involves several steps:
    1. Preparation:
      • Finalize Application ID: Ensure the package name is unique and final.
      • Set Versioning: Correctly set the `versionCode` and `versionName` in `build.gradle`.
      • Create App Icon: Create a high-resolution app icon.
      • Remove Debug Code: Remove `Log` statements and debugging flags.
    2. Generating a Signed App Bundle:
      • It is mandatory to digitally sign the app to upload it to Google Play.
      • In Android Studio, go to Build > Generate Signed Bundle / APK....
      • Create a new Keystore (if you don't have one) and protect it with a strong password. Never lose this Keystore.
      • Choose the release build type and generate the signed Android App Bundle (.aab) file.
    3. Setup on Google Play Console:
      • Create a Google Developer Account ($25 one-time fee).
      • Create a new app in the Play Console and fill in the app details.
      • Prepare Store Listing: Add an engaging title, detailed description, high-quality screenshots, and a feature graphic.
      • Upload App Bundle: Upload the generated .aab file to the Production track.
      • Fill Content Rating Questionnaire: Complete the survey to get an age rating for your app.
      • Set Pricing & Distribution: Choose if the app is free or paid, and in which countries it will be available.
      • Add Privacy Policy: If your app collects sensitive data, providing a privacy policy URL is mandatory.
    4. Review and Release:
      • Once everything is set, submit the release for review.
      • Google's review team will check your app for policies. After approval, your app will be live on the Play Store.
  3. Explain the Activity Lifecycle in detail with a diagram and code examples for each callback method.
    The Activity Lifecycle manages the various states of an activity.
    
    public class MyActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // UI Initialization, one-time setup
        }
        @Override
        protected void onStart() {
            super.onStart();
            // Activity is about to become visible
        }
        @Override
        protected void onResume() {
            super.onResume();
            // Activity is in the foreground, user can interact
            // Start animations, open camera, etc.
        }
        @Override
        protected void onPause() {
            super.onPause();
            // Another activity is coming into the foreground
            // Save unsaved data, stop animations
        }
        @Override
        protected void onStop() {
            super.onStop();
            // Activity is no longer visible
            // Release resources that are not needed
        }
        @Override
        protected void onRestart() {
            super.onRestart();
            // Activity is restarting from stopped state
        }
        @Override
        protected void onDestroy() {
            super.onDestroy();
            // Activity is being destroyed
            // Final cleanup, release all resources
        }
    }
            
    When an activity launches, `onCreate() -> onStart() -> onResume()` are called. When the user navigates away, `onPause() -> onStop()` are called. If the user returns, `onRestart() -> onStart() -> onResume()` are called. If the app is finished, `onPause() -> onStop() -> onDestroy()` are called.
  4. Explain the different methods of data persistence in Android.
    Data persistence means saving data even after the app is closed. The main methods in Android are:
    • 1. SharedPreferences: Used to save simple data in key-value pairs of private primitive data. It is ideal for user settings, flags, or small amounts of data. The data is stored as an XML file in the app's private directory.
    • 2. Internal File Storage: Used to save files in the device's internal memory. This data is private to the app and cannot be accessed by other apps. This data is deleted when the app is uninstalled. It is good for unstructured data like text files, JSON, or serialized objects.
    • 3. External File Storage: Used to save files on shared external storage (like an SD card). It is suitable for large files (photos, documents) that need to be shared with the user or other apps. It requires storage permissions.
    • 4. SQLite Databases: Used to store a large amount of structured data in a private database. Android provides full support for the SQLite database engine. The `SQLiteOpenHelper` class simplifies database management.
    • 5. Room Persistence Library: This is an abstraction layer over SQLite. It verifies SQL queries at compile-time and reduces boilerplate code, making it much easier and more robust to work with databases. It is the recommended approach for modern Android development.
  5. Explain the step-by-step process to create a RecyclerView with a custom layout (containing one ImageView and two TextViews).
    1. Add Dependency: Add the RecyclerView dependency to the `build.gradle (Module)` file: `implementation 'androidx.recyclerview:recyclerview:1.2.1'`
    2. Create Custom Row Layout: Create a new XML file (`list_item.xml`) in `res/layout`. Design it with an `ImageView` and two `TextViews` inside a `LinearLayout` or `ConstraintLayout`.
    3. Create Model Class: Create a Java class (`MyItem.java`) that will hold the data for a single item in the list (e.g., an image resource ID and two strings).
    4. Create Custom Adapter:
      • Create a new Java class (`MyAdapter.java`) that extends `RecyclerView.Adapter`.
      • Inside it, create an inner class `MyViewHolder` that extends `RecyclerView.ViewHolder`. In this class, initialize the views from `list_item.xml` using `findViewById()`.
      • Override three methods in the adapter:
        • onCreateViewHolder(): Inflate the `list_item.xml` layout and return a new `MyViewHolder` instance.
        • onBindViewHolder(): Get the data from the data list based on the `position` and set it to the views of the `MyViewHolder`.
        • getItemCount(): Return the total size of the data list.
    5. Setup RecyclerView in Activity:
      • Add `` to the activity's XML layout.
      • In the Java code, get a reference to the RecyclerView.
      • Create a `LinearLayoutManager` and set it on the RecyclerView (`recyclerView.setLayoutManager(...)`).
      • Create an `ArrayList` of data.
      • Create an instance of your custom adapter, pass the data list, and set it on the RecyclerView (`recyclerView.setAdapter(...)`).
  6. Explain the complete process of creating a Content Provider and consuming it from another app.

    In the Provider App:

    1. Database Setup: Create an `SQLiteOpenHelper` class that will manage the data.
    2. Create ContentProvider Class: Create a class that extends `ContentProvider`.
      • `onCreate()`: Initialize the database helper.
      • `query()`: Write the logic to fetch data from the database and return a `Cursor`.
      • `insert()`, `update()`, `delete()`: Write the logic to manipulate data in the database.
      • `getType()`: Return the MIME type of the data.
    3. Define Authority and URI: Define a unique authority string for the provider (e.g., "com.example.provider"). Create a content URI which is the path to access the data (e.g., `content://com.example.provider/items`).
    4. Register in Manifest: Register the provider in `AndroidManifest.xml` using the `` tag. Set the `android:authorities` and `android:exported="true"` so other apps can access it.

    In the Consumer App:

    1. Use ContentResolver: Get an instance of `ContentResolver` using the `getContentResolver()` method.
    2. Query Data from Provider:
      • Create a `Uri` object by parsing the provider's content URI.
      • Call the `contentResolver.query(uri, ...)` method. This method will trigger the `query()` method of the Provider App.
      • The result will be available in a `Cursor` object.
    3. Process Data from Cursor: Iterate over the `Cursor` object and extract data using column names, then display it in the UI.
  7. What are Fragments? Explain their lifecycle and the ways they can communicate with an activity.
    Fragments are modular sections of an activity's UI. They have their own lifecycle and can be reused in multiple activities.

    Lifecycle: A fragment's lifecycle is closely tied to the host activity's lifecycle. When the activity pauses, all its fragments are also paused. The main callbacks are: `onAttach()`, `onCreate()`, `onCreateView()`, `onViewCreated()`, `onStart()`, `onResume()`, `onPause()`, `onStop()`, `onDestroyView()`, `onDestroy()`, `onDetach()`.

    Communication Methods:

    • Fragment to Activity: A fragment can define an interface and cast the host activity to this interface in `onAttach()`. The fragment can then call the interface methods to communicate with the activity. This is the recommended approach.
    • Activity to Fragment: The activity can get a reference to the fragment using the `FragmentManager` (`findFragmentById()` or `findFragmentByTag()`) and then call the fragment's public methods directly.
    • ViewModel: In the modern approach, a shared `ViewModel` is used. Both the activity and the fragment access the same `ViewModel` instance, which holds the UI-related data. When the data in the `ViewModel` changes, `LiveData` notifies both the activity and the fragment.
  8. Explain the methods for background processing in Android. What is the difference between a Service, IntentService, and WorkManager?
    Background processing is essential for executing long-running tasks without blocking the UI thread.
    • Service: It is a component that runs in the background. It runs on the UI thread by default, so a new thread must be created inside it for long tasks. It can run even after the app is closed.
    • IntentService: This is a subclass of `Service` that handles requests on a worker thread sequentially. Each intent request is processed one by one. It automatically stops when the task is complete. It was good for simple background tasks but is now deprecated.
    • WorkManager: This is the current recommended solution for background work. It is a flexible library for scheduling deferrable (should not run immediately) and guaranteed (will run even if the app restarts) background tasks. It intelligently runs work based on constraints like network availability and charging state, keeping the device's battery life in mind. It is the modern replacement for `AsyncTask`, `IntentService`, and `JobScheduler`.
  9. Explain the process of integrating Google Maps into an Android app and displaying the user's current location on the map.
    1. Setup on Google Cloud Console:
      • Create a project and enable the "Maps SDK for Android" API.
      • Generate an API key and restrict it so that only your app can use it (using the package name and SHA-1 certificate fingerprint).
    2. Setup in Project:
      • Add the `play-services-maps` dependency in `build.gradle`.
      • Add the API key, internet permission, and location permissions (`ACCESS_FINE_LOCATION`) in `AndroidManifest.xml`.
    3. Displaying the Map:
      • Add a `SupportMapFragment` using the `` tag in the activity's XML layout.
      • Make the activity implement the `OnMapReadyCallback` interface.
      • In `onCreate()`, call `getMapAsync(this)`.
      • In the `onMapReady(GoogleMap map)` callback method, save the reference to the `GoogleMap` object.
    4. Displaying Current Location:
      • Check and request location permission at runtime.
      • Once permission is granted, get the last known location or request location updates using `FusedLocationProviderClient`.
      • Call `mMap.setMyLocationEnabled(true)` on the map object. This will add a blue dot on the map and a button to center on the current location.
      • (Optional) When the location is obtained, you can manually animate the map to that location using `mMap.moveCamera()`.
  10. What are the high-level steps to fetch JSON data from a REST API and display it in a RecyclerView?
    1. Add HTTP Library: Add a dependency for a networking library like Retrofit or Volley in `build.gradle`. Retrofit is the standard for modern development.
    2. Internet Permission: Add the internet permission in `AndroidManifest.xml`.
    3. Create Model (POJO) Class: Create a Java class that matches the structure of the JSON response. This helps in parsing the JSON into Java objects (using a library like GSON or Moshi).
    4. Retrofit Setup:
      • Create a `Retrofit` instance, specify the base URL, and add a converter factory (like `GsonConverterFactory`).
      • Create a Java interface and define the API endpoints (e.g., `@GET("users") Call> getUsers();`).
    5. Fetch Data:
      • In the Activity or ViewModel, create an instance of the Retrofit service.
      • Call the API call method. It will be executed on a background thread.
      • In the `onResponse()` callback, get the successful response (list of users) and add it to the RecyclerView adapter's data set. Call `adapter.notifyDataSetChanged()`.
      • In the `onFailure()` callback, handle the error.
    6. RecyclerView Setup:
      • Create a RecyclerView in the UI.
      • Create a custom adapter and ViewHolder that will display the data from the model class in the list item layout.
      • In the activity, setup the RecyclerView, adapter, and LayoutManager. Update the adapter when the data is fetched from the API.