Pages

Android Developer

Thursday, 7 November 2019

Difference between MVC & MVP & MVVM?

77. Difference between MVC & MVP & MVVM?

MVC is the Model-View-Controller architecture where model refers to the data model classes. The view refers to the xml files and the controller handles the business logic. The issue with this architecture is unit testing. The model can be easily tested since it is not tied to anything. The controller is tightly coupled with the android apis making it difficult to unit test. Modularity & flexibility is a problem since the view and the controller are tightly coupled. If we change the view, the controller logic should also be changed. Maintenance is also an issues.
MVP architecture: Model-View-Presenter architecture. The View includes the xml and the activity/fragment classes. So the activity would ideally implement a view interface making it easier for unit testing (since this will work without a view).Sample Implementation
MVVM: Model-View-ViewModel Architecture. The Model comprises data, tools for data processing, business logic. The View Model is responsible for wrapping the model data and preparing the data for the view. IT also provides a hook to pass events from the view to the model.Sample Implementation

78. S.O.L.I.D principles in software development?

  • The Single Responsibility Principle (SRP)
  • The Open-Closed Principle (OCP)
  • The Liskov Substitution Principle (LSP)
  • The Interface Segregation Principle (ISP)
  • The Dependency Inversion Principle (DIP)
You can checkout the whole article on what this means from here.

79. RxJava in Android?

Android Interview Questions Part 5

64. How to load bitmap to memory?

  • Checkout this article on it. I couldn’t have explained it better myself.

65. What are the permission protection levels in Android?

  • Normal — A lower-risk permission that gives requesting applications access to isolated application-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a requesting application at installation, without asking for the user’s explicit approval.
  • Dangerous — A higher-risk permission. Any dangerous permissions requested by an application may be displayed to the user and require confirmation before proceeding, or some other approach may be taken to avoid the user automatically allowing the use of such facilities.
  • Signature — A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user’s explicit approval.
  • SignatureOrSystem — A permission that the system grants only to applications that are in the Android system image or that are signed with the same certificate as the application that declared the permission.

66. What is an Application Not Responding (ANR) error, and how can you prevent them from occurring in an app?

An ANR dialog appears when your UI has been unresponsive for more than 5 seconds, usually because you’ve blocked the main thread. To avoid encountering ANR errors, you should move as much work off the main thread as possible.

67. What is a singleton class in Android?




A singleton class is a class which can create only an object that can be shared all other classes.

64. How to load bitmap to memory?

  • Checkout this article on it. I couldn’t have explained it better myself.

65. What are the permission protection levels in Android?

  • Normal — A lower-risk permission that gives requesting applications access to isolated application-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a requesting application at installation, without asking for the user’s explicit approval.
  • Dangerous — A higher-risk permission. Any dangerous permissions requested by an application may be displayed to the user and require confirmation before proceeding, or some other approach may be taken to avoid the user automatically allowing the use of such facilities.
  • Signature — A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user’s explicit approval.
  • SignatureOrSystem — A permission that the system grants only to applications that are in the Android system image or that are signed with the same certificate as the application that declared the permission.

66. What is an Application Not Responding (ANR) error, and how can you prevent them from occurring in an app?

An ANR dialog appears when your UI has been unresponsive for more than 5 seconds, usually because you’ve blocked the main thread. To avoid encountering ANR errors, you should move as much work off the main thread as possible.

67. What is a singleton class in Android?



A singleton class is a class which can create only an object that can be shared all other classes.

Android Interview Questions Part 4 - Fragment

50. What is Toast in Android?

Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime.

51. What are Loaders in Android?

Loader API was introduced in API level 11 and is used to load data from a data source to display in an activity or fragment. Loaders persist and cache results across configuration changes to prevent duplicate queries.

52. What is the difference between Dialog & DialogFragment?

A fragment that displays a dialog window, floating on top of its activity’s window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment’s state. Dialogs are entirely dependent on Activities. If the screen is rotated, the dialog is dismissed. Dialog fragments take care of orientation, configuration changes as well.

53. Difference between margin & padding?

Padding will be space added inside the container, for instance, if it is a button, padding will be added inside the button. Margin will be space added outside the container.

54. What is View Group? How are they different from Views?

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.

55. What is the difference between a regular .png and a nine-patch image?

It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.

56. Difference between RelativeLayout and LinearLayout?

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.

57. What is ConstraintLayout?

It 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.

58. When might you use a FrameLayout?

Frame Layouts are designed to contain a single item, making them an efficient choice when you need to display a single View.
If you add multiple Views to a FrameLayout then it’ll stack them one above the other, so FrameLayouts are also useful if you need overlapping Views, for example if you’re implementing an overlay or a HUD element.

59. What is Adapters?

An adapter responsible for converting each data entry into a View that can then be added to the AdapterView (ListView/RecyclerView).

60. How to support different screen sizes?

  • Create a flexible layout — The best way to create a responsive layout for different screen sizes is to use ConstraintLayout as the base layout in your UI. ConstraintLayout allows you to specify the position and size for each view according to spatial relationships with other views in the layout. This way, all the views can move and stretch together as the screen size changes.
  • Create stretchable nine-patch bitmaps
  • Avoid hard-coded layout sizes — Use wrap_content or match_parent. Create alternative layouts — The app should provide alternative layouts to optimise the UI design for certain screen sizes. For eg: different UI for tablets
  • Use the smallest width qualifier — For example, you can create a layout named main_activity that’s optimised for handsets and tablets by creating different versions of the file in directories as follows:res/layout/main_activity.xml — For handsets (smaller than 600dp available width)res/layout-sw600dp/main_activity.xml — For 7” tablets (600dp wide and bigger).
  • The smallest width qualifier specifies the smallest of the screen’s two sides, regardless of the device’s current orientation, so it’s a simple way to specify the overall screen size available for your layout.

61. Outline the process of creating custom Views:

  • Create a class that Subclass a view
  • Create a res/values/attrs.xml file and declare the attributes you want to use with your custom View.
  • In your View class, add a constructor method, instantiate the Paint object, and retrieve your custom attributes.
  • Override either onSizeChanged() or onMeasure().
  • Draw your View by overriding onDraw().

62. Briefly describe some ways that you can optimize View usage

  • Checking for excessive overdraw: install your app on an Android device, and then enable the “Debug GPU Overview” option.
  • Flattening your view hierarchy: inspect your view hierarchy using Android Studio’s ‘Hierarchy Viewer’ tool.
  • Measuring how long it takes each View to complete the measure, layout, and draw phases. You can also use Hierarchy Viewer to identify any parts of the rendering pipeline that you need to optimise.

63. Bitmap pooling in android?

Bitmap pooling is a simple technique, that aims to reuse bitmaps instead of creating new ones every time. When you need a bitmap, you check a bitmap stack to see if there are any bitmaps available. If there are not bitmaps available you create a new bitmap otherwise you pop a bitmap from the stack and reuse it. Then when you are done with the bitmap, you can put it on a stack.

Android Interview Questions Part 3 - Fragment

39. What are intent Filters?

Specifies the type of intent that the activity/service can respond to.

40. Describe fragments:

Fragment is a UI entity attached to Activity. Fragments can be reused by attaching in different activities. Activity can have multiple fragments attached to it. Fragment must be attached to an activity and its lifecycle will depend on its host activity.

41. Describe fragment lifecycle

  • onAttach() : The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.
  • onCreate() : The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
  • onCreateView() : The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.
  • onActivityCreated() : The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object
  • onStart() : The onStart() method is called once the fragment gets visible.
  • onResume() : Fragment becomes active.
  • onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
  • onStop() : Fragment going to be stopped by calling onStop()
  • onDestroyView() : Fragment view will destroy after call this method
  • onDestroy() :called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.

42. What is the difference between fragments & activities. Explain the relationship between the two.

An Activity is an application component that provides a screen, with which users can interact in order to do something whereas a Fragment represents a behavior or a portion of user interface in an Activity (with its own lifecycle and input events, and which can be added or removed at will).

43. When should you use a fragment rather than an activity?

  • When there are ui components that are going to be used across multiple activities.
  • When there are multiple views that can be displayed side by side (viewPager tabs)
  • When you have data that needs to be persisted across Activity restarts (such as retained fragments)

44. Difference between adding/replacing fragment in backstack?

  • replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked.
  • add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in ‘paused’ state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added).
  • In terms of fragment’s life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.

45. Why is it recommended to use only the default constructor to create a Fragment?

The reason why you should be passing parameters through bundle is because when the system restores a fragment (e.g on config change), it will automatically restore your bundle. This way you are guaranteed to restore the state of the fragment correctly to the same state the fragment was initialised with.

46. You’re replacing one Fragment with another — how do you ensure that the user can return to the previous Fragment, by pressing the Back button?

We need to save each Fragment transaction to the backstack, by calling addToBackStack() before you commit() that transaction

47. Callbacks invoked during addition of a fragment to back stack and while popping back from back stack:

addOnBackStackChangedListener is called when fragment is added or removed from the backstack. Checkout this link for reference.

48. What are retained fragments?

By default, Fragments are destroyed and recreated along with their parent Activity’s when a configuration change occurs. Calling setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.

49. Difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?

  • FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).
  • FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.