Android Flashcards
What is Android?
Android is an open-source operating system based on Linux, mainly focused on mobile, IoT and standalone devices.
What are the 4 main components of an Android App?
Activities
Content Providers
Services
Broadcast Receivers
What is an Activity?
It is one of the main Android components,
It is an entry point which makes the interaction with the user,
It is able to contain a view (layout) and fragments
and it has its own lifecycle which are a set of methods
that tell us the status of the Activity, for example:
onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy() and onRestart().
What is the lifecycle of an Activity?
It is a set of methods or functions that tell us the status of the Activity. These methods or functions are: onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy() and also onRestart()
Activity Life cycle description:
onCreate - called when activity is first created.
onStart - called when activity is becoming visible to the user.
onResume - called when activity will start interacting with the user.
onPause - called when activity is no longer in the foreground.
onStop - called when activity is no longer visible to the user.
onRestart - called after your activity is stopped, prior to start.
onDestroy - called before the activity is destroyed.
What is the difference between onCreate() and onStart() method?
The onCreate() method is called just one time and onStart() method could be called many times.
How can you share information between activities?
We can share information using bundles and passing[pasing] them through[thru] Intents. You need to instantiate[instanshieit] the Intent class, then pass the data on the putExtra() method before doing startActivity(intent).
What is a Fragment?
A Fragment is a portion of an activity, a Fragment can’t live on its own[oun] and it has to be contained in an Activity to exist, but has its own lifecycle which are a set of methods that tell us the status of the Fragment, for example:
onAttached(), onCreate(), onCreatedView(), onViewCreated(), onActivityCreated(), onStart(), onResume(), onPause(), onStop(), onDestroyView(), onDestroy(), onDetach().
What is the lifecycle of a Fragment?
Answer: It is a set of methods that tells us the states of the Fragment. These methods are:
onAttached - It’s the first method that it’s going to be called inside a Fragment, because it letting us know that this fragment it’s been attached to an activity
onCreate - it’s called to create the fragment without view
onCreatedView - Called for the fragment to draw the UI for the first time. It returns the layout or can return null if the fragment doesn’t provide UI
onViewCreated - This inherits to onCreateView but the particular reason to use it is because you can initialize some components that are on the UI.
onActivityCreated* - This method indicates that the activity is onCreate() has completed. And you can use this method to initialize something that is needed on the fragment that depends upon the activity’s onCreated.
onStart - This method is called once the fragment gets visible
onResume - The fragment is active and ready for the user interaction
onPause - It’s called when the system indicates that the user is leaving the fragment
onStop - It’s called when the fragment is not longer visible
onDestroyView - It’s called the Fragment view is destroyed but not the instance
onDestroy - It’s called the fragment instance is destroyed.
You can do a final clean up of the fragment’s state, but it is not guaranteed to be called by the Android platform. **
onDetach - This method notify that the fragment has been disassociated from the hosting activity
What is the difference between Activity and Fragment?
Both have their own lifecycle.
Fragments need to be attached to an Activity.
The activity is able to work without a Fragment.
Activity can have multiple fragments.
Google recommends the usage of fragments when possible since fragments are lighter to create than an activity.
Can an activity contain many fragments?
Yes, It is able to do that. For example you can use the Single Activity pattern where you have only one activity and many fragments for the screens, you can use fragmentManager or the Navigation component library from Jetpack for the navigation and pass information between fragments with SafeArgs.
How can you share information between Fragments?
We can share information by using the FragmentManager (bundles), a shared ViewModel with lived data , Navigation Component library (safeArgs) with Jetpack, or using interfaces through the host activity.
Note: As a best practice, do not directly communicate a fragment with another.
What is a Service?
A Service is one of the main Android components, it is used to represent 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.
There are 3 different types of services:
Background Service: This service is used for executing a long-running task without[widout] notifying the user that a task is running in the background. Google is not recommending this service because it is a good practice to notify the user what is running in the background.
Foreground Service: This service is used for executing a long-running task but it has to be executed with a notification and this notification has to show the progress of the task or just notify the user that something is running in the background.
Bound Service: It works as Server-Client where the server is the bound[baund] service and the client could be any application component with a context (Activity). This architecture enables communication between different[difrent] processes/apps (same service attached to different Activities from different Applications). And it is finished when all the components unsubscribe from the service.
Does a service run on the background thread?
No, It runs on the Main thread by default.
What is an IntentService?
It is a service which is used when you need to run a long-running task on a background thread instead of main thread, once the IntentService finishes the task it will be stopped. This service type is deprecated, it is better to use WorkManager since it allows us to schedule background tasks depending on device constraints like battery, network connection and system restarts.
What is the difference between a Service and an IntentService?
Service runs on the main thread and stops when you call the stopService method, IntentService runs on background thread and stops when the task is finished.
What is a BroadcastReceiver?
A broadcastReceiver is another main Android component, that is able to receive events from the Android system such as when the device starts charging, when the device has internet connection or the system boots up. It is a best practice to subscribe to these events using an Activity and perform some action when the event occurs, instead of declaring them on the manifest.
What is a ContentProvider?
A ContentProvider is another main Android component, that gives to the application the capability to manage access to data stored by itself, stored by other apps and provide a way to share data between applications. An example of this would be accessing the device contacts from your application.
What is the difference between ContentProvider and Database?
ContentProvider is the contract or interface that exposes the data from an application that usually needs to be stored in some place, we could use a Database to store and get the information that the ContentProvider is going to use
What is an Intent?
Is an abstract description of an operation to be performed by the Android system. Intent could contain an action, category and/or data.
There are two types :
Explicit: You specify the android component that is going to resolve the action. Like navigating to a specific activity using startActivity with the class name.
Implicit: In this case, you don’t specify the target, and instead you let the Android system pick one for you based on the intent action and the intent-filters declared on the installed apps manifest. Or if you use an Intent Chooser you can let the User decide. For example, opening the gallery or sending an email using Intent.Action.Text/Email/PickImage/etc.
How does your data flow in your architecture, for example while launching an API call (MVVM/Clean Architecture)?
<Acting I: mmm alright, actually for that I have some scenario that I usually give to junior developers, so they understand the flow for a network call through different layers>
Let’s say:
1. We want to implement a login screen, we have user credentials and a button to make the request.
2. And we are using; Clean Architecture, MVVM and Repository pattern for the project.
<Act>
Now, when the user clicks the login button->
1. We receive button action with setOnClickListener
2. This executes a viewmodel method
3. Then the viewmodel
a. Applies some business logic, like validating the inputs are not empty
b. If all is fine, then it launches a coroutine for the repository call with the user credentials
4. The repository
a. Has a remote dataSource with the retrofit implementation
b. Serializes the request using GSON/Moshi/any parser
c. Makes the call using a suspend function through the API interface
5. When the server responds, the datasource will deserialize the response to a Data Model
6. Pass it back to the repository and the ViewModel
7. Then the ViewModel
a. validates the response
b. map it to a Domain Model,
c. It updates a LiveData that the UI is observing
8. Finally the user can visualize the result of their action (error login, or navigate to new screen)
</Act>
What do you like/dislike about Kotlin?
I like Koltin better because it provides many different features that makes the code more efficient and readable, like:
- Extension functions: provides a way to extend functionality without needing to inherit from a class, and we can use it directly in objects.
- Scope Functions: We can execute a block of code within an object context and make the code more idiomatic using english words like Let and Apply.
- Null safety: Help us prevent crashes because we need to always check for
- null abi-li-ty.
- Coroutines: Gives us an easy way to make multithreading operations.
And many other features that make me like Kotlin.
So this is why it is hard to find something that I dislike about Kotlin, if I had to say anything it would be that Kotlin’s community is not as big as Java’s (for now).
What are the advantages/features of Kotlin?
Kotlin has many features, like
● Null safety: This is the main advantage/feature that helps us to prevent the headache (hed-ek) when programming with Java: The null pointer exception.
● Extension functions: I really like this one, since we can add functionality without needing to create another class and inherit just to add functionality, a really cool feature.
● Supports full Java Interoperability: That means if we have an old Java codebase, we can take our time to migrate Kotlin gradually, or create new modules in Kotlin without problems.
We have more features, such as:
● Scope functions
● Coroutines
● Higher Order functions and Lambda Expressions
● It’s based on Functional Programming
● And all of these features make Kotlin more efficient, readable and easier to understand as a programming language.
What is Null-Safety?
Null safety is the main advantage/feature that helps us to prevent the headache (hed-ek) when programming with Java: The null pointer exception. Kotlin offers some operators to handle this, for example:
● Safe calls operator (?): It is used in case you want to check the null condition and if the expression is null then by default it will return null or else it will return the value.
● Elvis operator (? :): This operator simplifies the validation of a value that could be null. This can guarantee that an expression won’t return a null value, as you will provide a non-nullable value if the provided value is null.
● The not-null assertion operator (!!): As the Kotlin’s documentation says, this is for NullPointerExcetion-lovers. This operator converts any value to a non-null type and throws an exception if the value is null. But that is returning Java.
We have some other features, but those are the most important. (Safe cast and Collections of a nullable type)
How do you handle it?
Kotlin offers some operators to handle this, for example:
● Safe calls operator (?): It is used in case you want to check the null condition and if the expression is null then by default it will return null or else it will return the value.
● Elvis operator (? :): This operator simplifies the validation of a value that could be null. This can guarantee that an expression won’t return a null value, as you will provide a non-nullable value if the provided value is null.
● The not-null assertion operator (!!): As Kotlin’s documentation says, this is for NullPointerExcetion-lovers. This operator converts any value to a non-null type and throws an exception if the value is null. But that is returning Java.
We have some other features, but those are the most important. (Safe cast and Collections of a nullable type)
When do you use null assertion (!!)?
Never. Google doesn’t recommend using it, but maybe some Java implementation or API requires it, and if this is the case, we need to use a try-catch to protect against exceptions.
What is a Data class?
The purpose of a Data Class is to simplify classes whose main purpose is to hold data. For this class, the compiler automatically generates:
- copy() function,
- equals() and hashCode() pair,
- toString() form of the primary constructor,
- And componentN() functions
What is an Extension function?
An extension function provides a better way of extending a class without modifying the original class. It is important to say that by defining an extension do not actually modify the classes they extend, only making new functions callable with the dot-notation on variables of this type.
What are the Scope functions?
Scope functions are whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name.
let , run , with , apply , also
What is a Sealed class?
Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. Sealed classes can have fields and methods defined in them, including both abstract and implemented functions.
What are inline and noinline functions?
When using lambdas, the extra memory allocations and extra virtual method call, introduce some runtime overhead.
When using inline functions, the compiler inlines the function body. That is, it substitutes the body directly into places where the function gets called.
When using inline functions, there is no extra object allocation and no extra virtual method calls.
However, we should not overuse the inline functions, especially for long functions since the inlining may cause the generated code to grow quite a bit.
By default, all lambdas passed to an inline function would be inlined, too. However, we can mark some of the lambdas with the noinline keyword to exclude them from inlining.
What is a high order function?
High order function is one which can accept a function as a parameter or can return a function.We can pass a lambda expression as a parameter which is essentially anonymous functions that we can treat as values. Finally, in High-Order functions we have two types of functions which can be passed:
- a function which returns Unit,
- And a function which returns any of the value integer, string etc.
What is an object keyword in kotlin?
Object represents a single static instance, and can never have any more or any less than this one instance.
Object expressions create objects of anonymous classes, that is, classes that aren’t explicitly declared with the class declaration.
This is useful for various techniques, including singleton objects and simple packaging up of functionality for encapsulation.
What is a Companion object?
Companion objects are singleton objects whose properties and functions are tied to a class but not to the instance of that class. So, basically like the “static” keyword in Java.
What is the difference between ‘val’ and ‘var’?
Val
- Is a read-only local variable (can be assigned a value only once)
- is assigned one time on runtime execution.
Var
- Is a mutable variable (I mean, can be reassigned)
So, var can be re-assigned and val can not be.
What is the difference between val and const val?
Val is assigned in runtime and Const val in compile time.
What is the difference between ‘lazy’ and ‘lateinit’?
Lateinit
- It is used with VAR
- Reserves a space in memory
- And you promise Kotlin that you will initialize it before you use it, or else the app will crash (Throws: Property not initialized)
Lazy
- It is used with VAL
- Creates a wrapper class and delegates the value to it (by Lazy)
- Used usually if getting the value requires expensive computation.
- It will assign the value when you read it for the first time.
How do you do a migration from Java to Kotlin? What do you need to look out for?
Migrate Whole Project
1. We want to do a meeting with the team, to plan and prioritize what modules we need to migrate first
Migrate Module
2. Make sure we have the documentation from the module we want to migrate or create it if necessary.
3. Start by taking smaller to bigger and complex classes to migrate.
Migrate Class
4. We take a Class and pass it through the IntelliJ Idea migration tool to convert Java to Kotlin
5. It is not perfect, but at least we have a starting point.
6. We now check for optimizations in the resultant code with the Kotlin features (scope functions, extensions, when, if, for statements, etc)
7. Also it is important to review Null cases, because Java doesn’t work with this unless you annotate with @Nullable or @Non-Nullable.
8. Finally we can run the class tests to make sure it still works as expected.
Do you need to add anything if you want to extend a class in Kotlin?
How do you create a Singleton?
How do you create static methods?
What is the superclass in Kotlin?
The superclass is Any.
When to use ‘lateinit’ and when ‘lazy’?
by lazy use it when you must waiting a event to initialize the val
and this val cant not be null. Late init use when yo dou want initialize a var and you assign which type is
Can a ‘lateinit’ variable be nullable?
no
What are the advantages of Kotlin?
null safety, less verbosal , clearer code
Difference between ? and !!?
safety call verify if a variable is null and double bang you affirm your variable is not null. Also you never must use double bang
When would you use ‘!!’?
never
When would you use ‘!!’
: there are simple classes used as data containers and do not encapsulate any additional logic. Simply put, Kotlin’s solution enables us to avoid writing a lot of boilerplate code.
How do you do a Java to Kotlin migration?
- Open the . java file.
- Copy all the code to the clipboard.
- Create the corresponding Kotlin. kt file.
- Paste the code. (Click “Yes” when it asks for your permission to convert the code.)
- If needed, check the class and update it.
What are the best practices for migrate code?
● Change Java models to Kotlin first.
● Use default parameters and partialize annotation.
● While converting utils classes to extension function, use the same class name.
● To avoid changing the client code, use Kotlin JVM Annotation.
● Avoid loops with collection extensions.
● Kotlin recommends using “if” for binary for three or more options.
What’s the use for an open modifier?
when you need that a class have inheritance because , kotlin class created by default are final
What are the different layouts in Android?
We have ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout and TabLayout.
What is the ConstraintLayout?
This layout allows you to create large and complex layouts that are responsive. It is similar to RelativeLayout because all views are laid out according to relationships between views and the parent layout but ConstraintLayout is more flexible and easier to use with Android Studio’s Layout Editor.
To define the view’s position, you must add at least one horizontal and one vertical, if you missed it, you will get a compilation error.
What is the RelativeLayout?
This layout allows you to position the views or components by relations between components and parent
What is the difference between ConstraintLayout and LinearLayout?
LinearLayout aligns the views or components one by one horizontally or vertically and ConstraintLayout uses relations to position and size the views or components and you can easily edit with the LayoutEditor.
What is the difference between ConstraintLayout and RelativeLayout?
Basically, ConstraintLayout comes to update RelativeLayout. They look similar but the big difference is that the ConstraintLayout uses a lower cost , and is faster than RelativeLayout since it only does one pass to calculate the views position.
Constraint layout has many attributes and tools that allow us to better position the content, like vertical/horizontal bias, barriers, guidelines and chains.
Also ConstraintLayout is optimized to use the Android Layout editor.
What is a CustomView?
It is when you create a class and extend from View in order to create a totally new view Overriding the OnDraw method and OnMeasure.
Like one I created for Gaszen, it was a specific circular progress bar that they wanted. I had to draw it using Paths with circles and arcs. Provide some methods to set the progress and colors.