Monday, 15 March 2021

Android Interview Question

Q1: Mention the difference between RelativeLayout and LinearLayout? 

Ans:- 

Linear Layout — Arranges elements either vertically or horizontally. i.e. in a row or column.

Relative Layout — Arranges elements relative to parent or other elements.


Q2: What is the difference between Bitmap and Drawable in Android?  

Answer

A Bitmap is a representation of a bitmap image (something like java.awt.Image).

A Drawable is an abstraction of "something that can be drawn". It could be a Bitmap (wrapped up as a BitmapDrawable), but it could also be a solid color, a collection of other Drawable objects, or any number of other structures.


Q3: What is a difference between Spannable and String?  

Answer

A Spannable allows to attach formatting information like bold, italic, ... to sub-sequences ("spans", thus the name) of the characters. It can be used whenever you want to represent rich text.


Q4: What is an Activity?

Answer

An Activity provides the window in which the app draws its UI.

This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app. For instance, one of an app’s activities may implement a Preferences screen, while another activity implements a Select Photo screen.


Q5: Explain briefly all the Android application components  

Answer

App components are the essential building blocks of an Android app. Each component is an entry point through which the system or a user can enter your app.

There are four different types of app components:

Activities - An activity is the entry point for interacting with the user. It represents a single screen with a user interface.

Services - A service is a general-purpose entry point for keeping an app running in the background for all kinds of reasons. It is a component that runs in the background to perform long-running operations or to perform work for remote processes.

Broadcast receivers - A broadcast receiver is a component that enables the system to deliver events to the app outside of a regular user flow, allowing the app to respond to system-wide broadcast announcements.

Content providers - A content provider manages a shared set of app data that you can store in the file system, in a SQLite database, on the web, or on any other persistent storage location that your app can access.


Q6: What is ADB and what is it used for?

Answer

ADB is the acronym for Android Debug Bridge, which is part of the Android SDK (Software Development Kit). It uses a client-server-model (i.e. adbd, the ADB daemon, is running on the device and can be connected to), and in most cases is used via an USB connection. It is also possible to use it via WiFi (wireless adb).

There's nothing you need to install on your Android device, as the ADB daemon (adbd) is already integrated into the Android OS. It is usually accessed via a command line interface from the PC, where either the full Android SDK is installed (several 30 MB download archive currently), or a massively stripped-down version for "non-developers", sometimes referred to as "Mini ADB" or "ADB essentials" (for Linux, this is only the adb executable; for Windows it's adb.exe plus two or three .dll files).


Q7: In what situation should one use RecyclerView over ListView?

Answer

RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

Reuses cells while scrolling up/down - this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

To conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.


Q8: What is an AsyncTask?  

AsyncTask is one of the easiest ways to implement parallelism in Android without having to deal with more complex methods like Threads. Though it offers a basic level of parallelism with the UI thread, it should not be used for longer operations (of, say, not more than 2 seconds).

AsyncTask has four methods

onPreExecute()

doInBackground()

onProgressUpdate()

onPostExecute()

where doInBackground() is the most important as it is where background computations are performed.


Q10: How do I pass data between Activities in Android application?  

Problem

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity. Can you guide me on how to keep session id available to all activities?

Answer

The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);

intent.putExtra("EXTRA_SESSION_ID", sessionId);

startActivity(intent);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");


Q11: How to persist data in an Android app? 

Answer

There are basically four different ways to store data in an Android app:

Shared Preferences - to save primitive data in key-value pairs

Internal Storage - you need to store data to the device filesystem, but you do not want any other app (even the user) to read this data

External Storage - you might want the user to view the files and data saved by your app

SQLite database


Q12: Why is it recommended to use only the default constructor to create a Fragment? 

Answer

In short, Fragments need to have a no-args constructor for the Android system to instantiate them. Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

It is used in the case when device has to restore the state of a fragment. No data will be passed and a default fragment will be created and then the state will be restored. Since the system has no way to know what you passed in your constructor or your newInstance, default constructor will be used and saved bundle should be passed via onCreate after the fragment is actually instantiated with the default constructor.


Q13: What is View Group? How are they different from Views?

Answer

View: View objects are the basic building blocks of User Interface(UI) elements in Android. View is a simple rectangle box which responds to the user’s actions. Examples are EditText, Button, CheckBox etc. View refers to the android.view.View class, which is the base class of all UI classes.

ViewGroup: ViewGroup is the invisible container. It holds View and ViewGroup. For example, LinearLayout is the ViewGroup that contains Button (View), and other Layouts also. ViewGroup is the base class for Layouts.


Q14: What is Dalvik?  

Dalvik is a Just In Time (JIT) compiler.

By the term JIT, we mean to say that whenever you run your app in your mobile device then that part of your code that is needed for execution of your app will only be compiled at that moment and rest of the code will be compiled in the future when needed. The JIT or Just In Time compiles only a part of your code and it has a smaller memory footprint and due to this, it uses very less physical space on your device.


Q15: What’s the difference between onCreate() and onStart()? 

Answer

The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated, for example during a configuration change.

The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().


Q16: Explain activity lifecycle  

As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle.

To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.


Q17: What is the most appropriate way to store user settings in Android application?

Answer

In general SharedPreferences are your best bet for storing preferences, so in general I'd recommend that approach for saving application and user settings.

The only area of concern here is what you're saving. Passwords are always a tricky thing to store, and I'd be particularly wary of storing them as clear text. The Android architecture is such that your application's SharedPreferences are sandboxed to prevent other applications from being able to access the values so there's some security there, but physical access to a phone could potentially allow access to the values.


Q18: Explain Android notification system  

Answer

A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.

Notifications appear to users in different locations and formats, such as an icon in the status bar, a more detailed entry in the notification drawer, as a badge on the app's icon, and on paired wearables automatically. Beginning with Android 5.0, notifications can appear on the lock screen.

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. By categorizing notifications into channels, users can disable specific notification channels for your app (instead of disabling all your notifications), and users can control the visual and auditory options for each channel—all from the Android system settings.


Q19: What is an Intent in Android? 

Answer

An Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers).So, it is almost equivalent to parameters passed to API calls. The fundamental differences between API calls and invoking components via intents are:

API calls are synchronous while intent-based invocations are asynchronous.

API calls are compile-time binding while intent-based calls are run-time binding.

To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another's app intent like "take picture", you declare an intent filter in your app's manifest file.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.

An Intent provides a facility for performing late runtime binding between the code in different applications.


Q20: What is a ContentProvider and what is it typically used for?

Answer

A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object.

Typically you work with content providers in one of two scenarios;

you may want to implement code to access an existing content provider in another application, or

you may want to create a new content provider in your application to share data with other applications.


Q21: Is it possible to implement the Model–View–Controller pattern in Java for Android?

Answer

In Android you don't have MVC, but you have the following:

You define your user interface in various XML files by resolution, hardware, etc.

You define your resources in various XML files by locale, etc.

You extend clases like ListActivity, TabActivity and make use of the XML file by inflaters.

You can create as many classes as you wish for your business logic.

A lot of Utils have been already written for you - DatabaseUtils, Html.


Q22: How does the OutOfMemory happens?

Answer

Out of memory error is very common error when you are developing for a application that deals with multiple images sets or large bitmaps or some Animation stuff. In Android, every application runs in a Linux Process. Each Linux Process has a Virtual Machine (Dalvik Virtual Machine) running inside it. There is a limit on the memory a process can demand and it is different for different devices and also differs for phones and tablets. When some process demands a higher memory than its limit it causes a error i.e Out of memory error.

There are number of reasons why we get a Out of memory errors. Some of those are:

1. You are doing some operation that continuously demands a lot of memory and at some point it goes beyond the max heap memory limit of a process.

2. You are leaking some memory i.e you didn’t make the previous objects you allocated eligible for Garbage Collection (GC). This is called Memory leak.

3. You are dealing with large bitmaps and loading all of them at run time. You have to deal very carefully with large bitmaps by loading the size that you need not the whole bitmap at once and then do scaling.


Q23: What is Armv7? 

Answer

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It's similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it's more flexible than RelativeLayout and easier to use with Android Studio's Layout Editor.

Intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.


Q25: How can I get the context in a Fragment?

You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context). You can also override the onAttach() method of fragment:

public static class DummySectionFragment extends Fragment{

...

    @Override

    public void onAttach(Activity activity) {

        super.onAttach(activity);

        DBHelper = new DatabaseHelper(activity);

    }

}


Q26: What types of Context do you know?

Answer

The are mainly two types of context:

1. Application Context: It is an instance that is the singleton and can be accessed in activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.

2. Activity Context: This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.


Q28: What is Context on Android? 

Answer

The documentation itself provides a rather straightforward explanation: The Context class is an Interface to global information about an application environment.

We may assume a Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.


Q29: What is the difference between compileSdkVersion and targetSdkVersion?

Answer

compileSdkVersion

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.


targetSdkVersion

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.


What are Android Annotations and what are they used for?

Answer

Android Annotations is an annotation-driven framework that allows you to simplify the code in your applications and reduces the boilerplate of common patterns, such as setting click listeners, enforcing ui/background thread executions, etc.


What is Parcelable in Android?

A Parcelable is the Android implementation of the Java Serializable. ... To allow your custom object to be parsed to another component they need to implement the android. os. Parcelable interface. It must also provide a static final method called CREATOR which must implement the Parcelable.


When to use Android's ArrayMap instead of a HashMap?

Answer

HashMap uses an array underneath so it can never be faster than using an array correctly.


Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.The reason your array is so slow is due to the equals comparisons, not the array access itself.


An ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.


List:


An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.


Map:


An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.


The list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background. You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).


The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarantee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).


When to use Arrays?


Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.


Sometimes, it may be best to use a combination of the above approaches. For example, you could use a ArrayList of HashMap to suit a particular need.


What is Intent Filter?

An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions.


What is an implicit intent?

Answer

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you'd like the user to pick which app to use


What is Explicit Intent? 

Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent.


We can also pass the information from one activity to another using explicit intent.


What does LayoutInflater in Android do?

Answer

The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.


Explain String vs StringBuilder vs SpannedString vs SpannableString vs SpannableStringBuilder vs CharSequence? 

Answer

String

A String is immutable (ie, the text can't change). It also doesn't have any spans associated with it. (Spans are ranges over the text that include styling information like color, highlighting, italics, links, etc.) So you can use a String when your text doesn't need to be changed and doesn't need any styling.


StringBuilder

A StringBuilder has mutable text, so you can modify it without creating a new object. However, it doesn't have any span information. It is just plain text. So use a StringBuilder when you need to change the text, but you don't care about styling it.


SpannedString

A SpannedString has immutable text (like a String) and immutable span information. It is a concrete implementation of the requirements defined by the Spanned interface. Use a SpannedString when your text has style but you don't need to change either the text or the style after it is created.


Note: There is no such thing as a SpannedStringBuilder because if the text changed then the span information would also very likely have to change.


SpannableString

A SpannableString has immutable text, but its span information is mutable. It is a concrete implementation of the requirements defined by the Spannable interface. Use a SpannableString when your text doesn't need to be changed but the styling does.


SpannableStringBuilder

A SpannableStringBuilder has both mutable text and span information. It is a concrete implementation of the requirements defined by the Spannable and Editable interfaces (among others). Use a SpannableStringBuilder when you will need to update the text and its style.


CharSequence

A CharSequence is an interface and not a concrete class. That means it just defines a list of rules to follow for any class that implements it. And all of the classes mentioned above implement it. So you can use a CharSequence when you want to generalize the type of object that you have for maximum flexibility. You can always downcast it to a String or SpannableStringBuilder or whatever later if you need to.


What is the difference between Handler vs AsyncTask vs Thread? 

Answer

Thread


Android supports standard Java Threads. You can use standard Threads and the tools from the package “java.util.concurrent” to put actions into the background. The only limitation is that you cannot directly update the UI from the a background process.


If you need to update the UI from a background task you need to use some Android specific classes. You can use the class “android.os.Handler” for this or the class “AsyncTask”


Handler


The class “Handler” can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and override handleMessage() to process messages. To process Runable, you can use the method post(); You only need one instance of a handler in your activity.


You thread can post messages via the method sendMessage(Message msg) or sendEmptyMessage.


AsyncTask


If you have an Activity which needs to download content or perform operations that can be done in the background AsyncTask allows you to maintain a responsive user interface and publish progress for those operations to the user.



How would you communicate between two Fragments?

Answer

The recommended way to communicate between fragments is to create a shared ViewModel . Both fragments can access the ViewModel through their containing Activity.


 What is the difference between Service & Intent Service? 

 Answer

 Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.


IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work


What are the differences between ArrayList and ArrayMap?

Answer

ArrayMap keeps its mappings in an array data structure — an integer array of hash codes for each item, and an Object array of the key -> value pairs.


Where ArrayList is a List. Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.


What is the difference between Activity and Context? 

Answer


What is a JobScheduler?

Answer

This is an API for scheduling various types of jobs against the framework that will be executed in your application's own process. See JobInfo for more description of the types of jobs that can be run and how to construct them.



What is the difference between onCreate() and onCreateView() lifecycle methods in Fragment?

Answer

onCreate() : Initialize essential components and variables of the Fragment in this callback. The system calls this method when the Fragment is created. Anything initialized in onCreate() is preserved if the Fragment is paused and resumed. onCreateView() : Inflate the XML layout for the Fragment in this callback.


What is the difference between a Bundle and an Intent?

Answer



what is singleton class in android

Answer

A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency and creating a central point of access for an application to access its data store. This example demonstrate about How to use singleton class in android.


what is application context in android

Answer

 It is the context of the current state of the application. It can be used to get information regarding the activity and application. It can be used to get access to resources, databases, and shared preferences, and etc. Both the Activity and Application classes extend the Context class


 What are some difference between Parcelable and Serializable? 

 Answer

 Serializable


Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable.


Parcelable


Parcelable is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities.


Difference between SparseArray and Hashmap?

Answer



What is Broadcast Receiver?

Answer

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.


What are ‘activities’? Describe the lifecycle of an activity.

Answer

OnCreate(): Here, the views are created and data is collected from bundles.

OnStart(): It is called if the activity is visible to the user. It may be succeeded by onResume() if the activity reaches the foreground and onStop() if it converts into hidden.

OnResume(): It is called when the activity starts an interaction with the user.

OnPause(): This is called when the activity is going to the background but hasn’t been killed yet.

OnStop(): This is called when you are no longer visible to the user.

OnDestroy(): Called when the activity is finishing

OnRestart(): Called after the activity has been stopped, prior to it being started again


Question: How do you find memory leaks in an application on the Android platform?

Answer: To find memory leaks in an application on Android, the Android Device Manager (ADM) is used by the Android Studio. When you open ADM in Android Studio, you can see parameters such as heap size and memory analysis along with many others while you run an application.


Question: State the architecture of an Android application.

Answer: Any Android application has the following components:


Notification- Features such as light, sound, icons and more

Services- To perform background functionalities

Intent- To perform inter-connection between activities and mechanisms that pass on data

Resource Externalization- Features such as strings and graphics

Content Providers- To share data between applications


Question: Explain the difference between implicit and explicit intent.

Answer: Below is the difference between the two intents


Explicit Intent: An explicit intent is where you inform the system about which activity or system component it should use to generate a response to this intent.

Implicit Intent: An implicit intent allows you to declare the action you wish to carry out, after which the Android system will check which components are registered to handle that specific action.


Question: Explain different launch modes in Android

Answer: Below are the different launch modes in Android


Standard: This launch mode generates a new instance of the activity in the task from which it originated. It is possible to create multiple instances of the same activity, which can be added to the same or different tasks.

SingleTop: This launch mode is similar to the Standard launch mode, except if there exists a previous instance of the activity on the top of the stack, then a new instance will not be created, but the intent will be sent to the existing instance of the activity.

SingleTask: This launch mode will always create a new task and push a new instance to the task as the root one.

SingleInstance: This launch mode is the same as the SingleTask launch mode but the system doesn’t launch any new activities in the same task. In a scenario where the new activity is launched, it is launched in a separate task.

No comments:

Post a Comment