Android interview questions

What is Activity and its life cycle in Android?

Activity is a Java class that controls the screen you see on an Android application. Activity life cycle refers to the series of methods that are being called when an Activity is launched.

onCreate(), onStart() and onResume() are called when an activity is brought to the screen on an Android device.

onPause() and onStop() are called when you click on the home button on your phone and the Activity goes to the background.

onRestart(), onStart() and onResume() are called when you go back to the previous activity screen, for example previous activity screen was interrupted becase someone called you, after the call you go back to the previous activity.

onDestroy() is called when the activity is no longer visible and the system determines it need to be killed to save resources for the currently visible activity, or you explictly called onfinish() in the activity.

Activity official document, Activity boilterplate code.

What is Fragment and its life cycle in Android?

A Fragment by definition is small part broken or separated off an activity. A Fragment is like a very cut down Activity, it has to live in an Activity but with its own life cycle methods. Other than that, A Fragment is much like a LinearLayout or RelatveLayout or any other views that lives inside an Activity’s layout file.

Fragment’s life cycle is very similar to Activity’s life cycle, but not exactly the same because Fragment cannot exist by itself, it has to be contained in an Activity. In other words Fragment is created after an Activity is created, and it is destroyed if the Activity containing it is destroyed. But Fragment has it’s own life cycles. For example, an activity can have multiple fragments, and the activity can decide which fragment to show on it’s Activity screen. So, Fragment can be created and destroyed any number of times while the Activity hosting it is running.

The life cycle methods from onCreateView to onDestroy() can be called muliple times at the hosting Activity’s wish.

Fragment Official Document, Fragment Boilerplate code.

What is Service in Android?

From the Official Document on Services.

A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application’s main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

How do you start an activity?

Build an Intent object specifing the current context and the next cnotext, then pass that intent object to the method startActivity();

Intent i = new Intent(this, NewActivityClassName.class);

What happens when an activity is rotated on the device?

When a device is rotated during runtime, or when new peripherals are added such as a keyboard, it is a configuration change. Normally the running Activity restarts whenever there is a configuration change.

On Activity restart, the onDestroy() method is called followed by the onCreate() method. These methods are responsible for destroying the existing Activity and creating a new one. This default behavior helps make it suitable for an application to adapt to the new screen orientation, as well as other configuration changes.

Sometimes this behavior should be overridden in order to provide optimal performance.

If you have an activity with two fragments, and you rotate the screen, what happens behind the scenes?

  • If you have two fragments displayed and changed the orientation, then the parent activity in which they are contained gets re-created.
  • Thus, if the instance of the fragments is not saved then the application will crash.
  • Thus, in Android the easiest way is to throw a if statement right after the on create method is called and check to see if you already have something in there.
  • You could add: android:configChanges=”screenSize|orientation” in application manifest file, manifest.xml, This will prevent Android calling onCreate on screen orientation change. If you want to perform special handling of orientation change, you can override onConfigurationChanges.

How do you handle orientation changes on Activity?

Orientation changes will cause the Activity to lose its current state data and restart. To save the state of the application, do it in the onSaveInstanceState method. To restore the data, get it from onCreate or onRestoreInstanceState method.

See this post for example

How do you pass information from one activity to another?

There are three ways in which you can transfer data between activiites:

  1. Using bundle object to pass small piece of information
  2. Using Serializable interface : It is a marker interface, meaning that there is no method to implement, Java will simply do its best effort to serialize it efficiently.
  3. Using Parceable interface: Allows objects to read and write from Parcels which can contain flattened data inside message containers.

What is an intent?

Intent is an description of an operation to be performed. It can be used with startActivity() to launch an Activity , broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

Code Example:

//Create Intent object which moves from LoginActivity class 
//to WelcomeActivity class
Intent intObj = new Intent(LoginActivity.this,WelcomeActivity.class);
//Set user entered name in value name which will be 
//used in WelcomeActivity class
intObj.putExtra("USERNAME", name);
//Start WelcomeActivity 

Get the string that was passed from the previous activity through intent. Do these from the new activity.

String username = getIntent().getStringExtra(“USERNAME”);

What kind of intents exist? What are the differences?

There are Explicit and Implicit intents. Explcit intent is when you know what is going to be the next screen to show. Implicit intent is when you don’t know what is going to be the next screen.

Explicit Intent

  • Explicit intent specify the component to start by name (the fully-qualified class name).
  • Use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start.
  • Need to register the activity in Android manifest file.
  • No need to define uses-permission
  • Sample Code
    Intent intObj = new Intent(Activity1.this, Activity2.class);

Implicit Intent

  • Implicit intent don’t name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.
  • Implicit intent is when you start a component in other application.
  • The activity of another application doesn’t have to be registered in your own android app’s manifest file.
  • Implicit intent need to define uses-permission in order to access other application.
  • Sample Code
    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));

How does the intent resolution get handled?

When the system receives an implicit intent to start an activity, it searches for the best activity for the intent by comparing the intent to intent filters based on three aspects, action, data and category

More about intent resolution.

What are the differernces between Parcelable and Serializable in Android?

Parcelable and Serializable Java classes that can be used to pass data between Android Activities. Parcelable is


  • In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization.
  • Parcelable is not a general-purpose serialization mechanism.
  • Parcelable objects are designed for fast data transfer purpose, it ensures a complex instance of it can be serialized and de-serialized during runtime.
  • Parcelable object can contain complex types such as ArrayList, Hashmap, array, or struct, etc.
  • Parcelable creates less garbage objects in comparison to Serialization
  • Parcelable was customized and optimized to work with activities in andriod, therefore the performance is about 2 times faster than Serialization.
  • Parcelable Sample class
    public class SampleParcelable implements Parcelable {
        public String fristName;
        public String lastName;
        public SampleParcelable(String sFristName, String sLastName) {
            this.fristName = sFristName;
            this.lastName = sLastName;
        protected SampleParcelable(Parcel in) {
            this.fristName = in.readString();
            this.lastName = in.readString();
        public int describeContents() {
            return 0;
        public void writeToParcel(Parcel dest, int flags) {
        public static final Parcelable.Creator<FormParcelable> CREATOR = new Parcelable.Creator<FormParcelable>() {
            public FormParcelable createFromParcel(Parcel in) {
                return new FormParcelable(in);
            public FormParcelable[] newArray(int size) {
                return new FormParcelable[size];
  • Create Parcelable and send it with intent
    SampleParcelable sp = new SampleParcelable("Danielle", "Robay");
    Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
    i.putExtra("sampledata", sp);
  • Receive Parcelable from the new Activity
    SampleParcelable sp = getIntent().getParcelableExtra("sampledata");
    Log.i(sp.firstName, sp.lastName);


  • Serializable is available in core Java. It is a marker interface, which implies the user cannot marshal the data according to their requirements.
  • It creates a lot of garbage objects.
  • In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API.
  • Serializable is slower than Parcelable.

What’s Loaders in Android?

Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment. Loaders have these characteristics:

  • They are available to every Activity and Fragment.
  • They provide asynchronous loading of data.
  • They monitor the source of their data and deliver new results when the content changes.
  • They automatically reconnect to the last loader’s cursor when being recreated after a configuration change. Thus, they don’t need to re-query their data.

See this post for loader example

What are the building blocks of Android?

Activity, Service, ContentProvider, Intent, and BroadcastReceiver are the building blocks of Android.

  • An activity represents a single screen with a user interface. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email app, each one is independent of the others. As such, a different app can start any one of these activities (if the email app allows it). For example, a camera app can start the activity in the email app that composes a new email for sharing pictures.
  • A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provie a user interface. Examples:
    • Play music in the background while the user is in a different app.
    • Fetch data over the network without blocking user interaction with an activity.
    • Updating Content Providers.
  • A content provider manages a shared set of app data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location you app have access to. Through content provider, other apps can query or even modify the data if the content provider allows it. For example, Android system provides a content provider that manages the user’s contact information. As such, any app with the proper permissions can query part of this contact information through content provider.
  • An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

    An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

    There are two primary forms of intents you will use.

    Explicit Intents have specified a component (via setComponent(ComponentName) or setClass(Context, Class)), which provides the exact class to be run. Often these will not include any other information, simply being a way for an application to launch various internal activities it has as the user interacts with the application.

    Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent.

  • A boradcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system, for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Apps can also initiate broadcasts, for example, to let other apps know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don’t display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs.

What are the differences between ListView and RecyclerView?

  1. ViewHolder Pattern, this is recommended in ListView, mandatory in RecyclerView.
  2. LayoutManager, ListView only allows ListView layout, whereas RecyclerView allows you to use other layouts such as LinearLayout and GridLayout where you can create horizontal scrolling objects.
  3. Item Animator, ListViews are lacking in support of good animations, but the RecylerView brings a whole new dimension to it.
  4. Item decoration, it’s not easy to dynamically decorating items like adding borders or dividers, but in RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.

More about ListView and RecyclerView

What are the differences between an Activity and a Fragment?


  • An Activity can exist independently.
  • An Activity can contain multiple fragments.
  • An Activity is a complete screen where the user interaction happens.
  • When an activity is placed to the backstack of activities the user can navigate back to the previous activity by just pressing the back button.
  • An Activity is an application component that provides a screen, with which users can interact in order to do something.


  • A Fragment cannot exist independently.
  • A Fragment has to live inside an Activity.
  • A Fragment is like an sub Activitiy.
  • When a fragment is placed into an activity, we have to request the instance to be saved by calling addToBackstack() during the fragment transaction.
  • A Fragment represents a behavior or a portion of user interface in an Activity.
  • A fragmemt is a part of an activity, which contributes its own UI to that activity.

How to send Parcelable object from one activity to another?

Create Parcelable and send it with intent

SampleParcelable sp = new SampleParcelable("Danielle", "Robay");
Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("sampledata", sp);

Receive Parcelable from the new Activity

SampleParcelable sp = getIntent().getParcelableExtra("sampledata");
Log.i(sp.firstName, sp.lastName);

How do you preserve the state of a fragment?

Saving the data in onSaveInstanceState method and retrive the data in either onViewStateRestored or onCreate. See this post for example.

How do you pass data from one fragment to another fragment?

All fragment to fragment communcation should be done through the associated Activity by implementing an interface. For example, define a callback interface inside the fragment and require the host activity to implement interface method. When the activity receives a callbak through the interface, it can share the information with other fragments within the activity. See this post for example.

Can you name a few data storage options for saving data from mobile apps?

  • SharedPreferences
  • SD Card
  • Load Database using SQLite database, ORMLite, Otto, ActiveAndroid
  • Cloud Database
  • Google App Engine Backend
  • Third party Database hosting: Amazon, parse API
  • Client Remote database:MySQL

What is Content Provider?

  • The content provider is one of the main building block of Android.
  • They act like the centralized repository for the access of the Database.
  • For example: the contacts database in Android devices, wherein it can be used to import list of contacts(name, phone, number, email) to display in thrid party apps.
  • Other content providers are: media files, call logs, bookmarks of browsers, gallery, audio files.
  • User can also create custom content provider and share database between two different apps.

What is Shared Preferences?

The Shared Preference is used by apps to save data in key-value pairs, like a Bundle. Data is stored in XML file in he directory data/data/package-name/shred-prefs folder. It stores data such as username, password, theme settings, other application settings. It only allows you to save primitive data types like booleans, floats, longs, int and strings.

SharedPreference appPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = appPref.edit();
editor.putString("myValue", "hello world");

//To get data
String myPref = appPref.getString("myValue","null");
Log.i("myValue", myPref);

See this post for more details.

What is ANR?

  • ANR stands for Application Not Responding, it is a dialog shown to the user when your app has been unresponsive for a considerable period of time so that the system offer the user an option to quit the app.
  • ANR is displayed when an application cannot respond to user input, caused by a network access on the UI thread or a long running operation on the UI thread.
  • Both situation should be handled or processed in a separate worker thread from the UI thread.
  • In Android, application responsiveness is monitored by the Activity Manager and Window Manager system service.
  • Conditions that will trigger ANR: No response to input event within 5 seconds, and a broadcastReceiver hasn’t finish executing within 10 seconds.
  • Some performance tools such as Systrace and Traceview can be used to determine bottlenecks in your app’s responsiveness.
public void onClick(final View v){
  try {
  } catch(final InterruptedException e) {
    // TODO Auto-generated catch block

What is dependency injection?

  1. Dependency injection is a software design pattern that in which a dependency is an object that can be used (a service) and an injection is the passing of a dependency to a dependent object (a client) that would use it and the service is made part of the client’s state.
  2. Passing the service to the client, rather than allowing a client to build or find the service , is the fundamental requirement of the pattern.
  3. Separates the creation of a client’s dependencies from the client’s behavior, which allows program designs to be loosely coupled
  4. There are three common means for a client to accept a dependency injection: setter, interface, and constructor-based injection.
  5. Setter and constructor injection differ mainly by when they can be used.
  6. Interface injection differs in that the dependency is given a chance to control its own injection. All require that separate construction code (the injector) take responsibility for introducing a client and its dependencies to each other.
  7. Dependency injection involves four element:

    • the implementation of a service object
    • the client object depending on the service
    • the interface the client uses to communicate with the service
    • the injector object, which is responsible for injecting the service into the client
  8. Dagger, RoboGuice and Android Annotation are 3 popular dependency injection libraries for Android.

Do you know any third party libraries/plugins for collecting analytics data and detect crash events in Android?

  • Google Analytics by Google
  • Crashlytics by Fabric
  • Flurry Analytics by Yahoo
  • ACRA
  • BugSense
  • MixPanel
  • Webtrends
  • Crittercism

How do you improve your code?

Some factors to consider about app design:

  • Performance
  • Usability
  • Data Access
  • Security
  • Connectivity
  • Extensibility (add feature for user feedback for improvement or suggestion for new features)

Code Improvement:

  • Make use of good design patterns to improve your code’s maintenance, simplicity, loosely coupled, extensibility, portability and resuability.
  • Make good documentation using Java annotations (JavaDoc)
  • Consider memory leak issuess (use leak canary)
  • Use TDD and BDD for extensive continuous testing (Robotium, Espresso, Roboletric etc.)
  • Use Crash collecting tools(Google Analytics, Crashlytics, Yahoo Flurry etc.)

Do you know about TDD and BDD?

TDD (Test Driven Development)
  • Write automated test cases before coding
  • Test functionality of the code
  • Test software is been built the right way
  • Software Development in the perspectives of software programmer
BDD (Behavior Driven Development)
  • Write automated test cases after production development.
  • Test product behaviors
  • Test right software is built according to the requirements.
  • SD in the perspectives of Stockholder/business owner.

Robotium, Expresso, Roboletric are testing tools you can use for TDD and BDD.

How do you avoid getting crashes when a long operations is running and you make a rotation change and try to update the layout?

  • Process the long operation in a separate worker thread and update layout or post the result back to the main UI thread using broadcast receiver or handler.
  • The broadcast receiver needs to be unregistered in onStop(), and registered onStart()

Do you have experience supporting old android versions?

  • Define alternative styles (res/values/styles.xml for older theme, res/values-v21/styles.xml for new material theme)
  • Provide alternative layout (res/layout/ and res/values for layout of older versions, res/layout-v21 and res/values-v21 for layout of new attributes introduced in Android 5.0 (API 21)
  • Use the support library (v7 support libraries)
  • Check the system version at runtime before invoke the API for the new feature introduced in Android 5.0 (API 21)

What do you know about software testing?

  1. Unit Testing is a software development process in which a programmer repeatedly test the components that should be isolated by the programmer writes tests.
  2. JUnit is the de-facto standard for units Android
  3. Testing to be performed before release code

    • Unit Testing (verify a minimal unit of source code)
    • Integration Testing (test inter-operation between modules in the application)
    • Operational Testing (Test the correctness of application requirement)
    • System Testing (Test the entire application in the real environment)
  4. TDD and BDD are two popular software testing methodologies.

What do you know about Agile in software development?

Agile is a incrementally iterative approach for software development from the start of the project. It works by breaking projects down to list of functionalities/modules need to be implemented, prioritizing them, and then continuously deliver each module in short cycle called iteration/sprint cycle. Some of important features of Agile development include:

  1. Release often
  2. Continuous Integration
  3. Test Driven Development
  4. Automated developer Test
  5. Collective Code Ownership
  6. Evolutionary Design composed from Simple Design
  7. Stand up Meeting

Search within Codexpedia

Custom Search

Search the entire web

Custom Search