Skip to content

Instantly share code, notes, and snippets.

@rahulkhatri19
Last active February 25, 2020 07:13
Show Gist options
  • Save rahulkhatri19/a8cd7026bb16df9802591f1c5cba3499 to your computer and use it in GitHub Desktop.
Save rahulkhatri19/a8cd7026bb16df9802591f1c5cba3499 to your computer and use it in GitHub Desktop.
Android Basic, Interview Questions with Answers, Basic concept.
Helpful Links
------
- [Google Doc - Room Db Query](https://developer.android.com/reference/android/arch/persistence/room/Query)
- [Google Doc - Accessing data from Dao](https://developer.android.com/training/data-storage/room/accessing-data)
- [Android Room: Handling Relations Using LiveData](https://proandroiddev.com/android-room-handling-relations-using-livedata-2d892e40bd53)
- [SQLite on Android Made Simple: Room Persistence Library with a Touch of RxJava](https://android.jlelse.eu/sqlite-on-android-made-simple-room-persistence-library-with-a-touch-of-rxjava-55e8dc5301cf)
-[Insert and fetch records with Room on Android using Kotlin](https://heartbeat.fritz.ai/insert-and-fetch-records-with-room-on-android-using-kotlin-2de28fdeae2b)
Dagger Dependency Injection
1. Setting Up Dagger:
app: build.gradle
apply plugin: 'kotlin-kapt'
ext {
dagger_version = '2.17'
auto_value_version = '1.6.2'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kapt "com.google.dagger:dagger-compiler:$dagger_version"
implementation "com.google.dagger:dagger:$dagger_version"
2. Essential Dagger:
Graph like code Structure -> Dagger has graph like code structure which is Direct Acyclic Graph (DAG) names it dagger.
Factory: way of creating dependency is a factory.
@Injector:
It will create object and there dependency.
class Client @Inject constructor(private val connection: Connection) {}
@Component:
It is a top level factory which can get object which are required.
3. It has different type:
a. Method Injection: property setter
// setting up setter for menthod injection.
@Inject constructor()
var client: Network.Client? = null
@Inject set
private var presenter = DaggerPresenterFactory.create().presenter()
b. Field Injection: properiy itself so it is lateinit.
// Create Abstract Factoty
@Component
interface PresenterFactory {
fun presenter(): Presenter
fun inject(act: MainActivity)
}
@Inject
lateinit var presenter: Presenter
DaggerPresenterFactory.create().inject(this)
c. Lazy Injection:
A Lazy<t> is a factory for object of type T. Used when code need lazy created singleton of type t.
class Presenter @Inject constructor( private val client: Lazy<Client>){
fun connect(show: (String?) -> Unit) {
val data = client.get().fetchData()
show(data)
}
}
Note : necessary to import dagger.Lazy // as is not imported by default.
d. Provider Injection: New connection to serever every new client request ie single instance of client object need to create new instance of connnection call to fetch data.
A Provider<T> is factory for object of type T. Used when code depends on multiple ojects of type t,
class Client @Inject constructor(private val connection: Provider<Connection>) {}
Kotlin Basic:
1. Null safe operator (?) :
println(name?.toUpperCase()) // if upper case then print name in uppercase else print null.
in java :
if (name.toUppercase != null){
print(name.toUpperCase())
} else print("null")
2. Not null assert(!!):
println(name!!.toUpperCase()) // if upper case then print name in upper case else null pointer exception.
fun main(args: Array<String>){
var name:String? = null
name = "rahul"
println(name.toUpperCase())
}
3. constructor :
class Student(val name:String, val rollNo:Int, var rank:Int){ }
or
class Student{
val name:String
val rollNo:Int
var rank:Int
// constructor by default name as val and it can't be changed and no need of annotation val as it by default.
construcutor(name:String, rollNo:Int, rank:Int){
this.name = name
this.rollNo = rollNo
this.rank = rank
}
}
// TO print any thing inside a constructor we need use init.
class Student(val name:String, val rollNo:Int, var rank:Int){
init {
println("constructor is called")
}
}
example :
4. secondary constructor:
class Student(val name:String, val rollNo:Int, var rank:Int){
construcutor(rollNo:Int, rank:Int) : this("", rollNo, rank){}
}
5. static method:
for making an menthod static we need to use companion object
class Studnet {
companion object{
fun getMethod(){}
}
}
class Teacher{
Student.getMethod()
}
6. if else:
simple as if(){} else{}
or like ?: operator // can use return keyword.
if (name != null) println(name.toUpperCase()) else println("null ops")
7. let function:
8. when exp : Similar to switch statement
val a = readLine()?.toInt()
when (a){
1, 3, 5 -> println("It is a odd les than 5")
2, 4, 6, 8 -> println("it is even less 10")
7 -> println(" It is 7")
else -> println("I dont know")
}
9. while loop:
var a = 2
while(a < 8) {
println("value of a=$a")
a++
}
10. for loop:
val userList = ArrayList<User>()
userList.add( User("1", "name 1", "img 1", "prof 1"))
userList.add( User("2", "name 2", "img 2", "prof 2"))
userList.add(User("3", "name 3", "img 3", "prof 3"))
userList.add(User("4", "name 4", "img 4", "prof 4"))
for (user:User in userList){
println("${user.id} name= ${user.name} image= ${user.imageUrl}")
}
loop with hash map
val userList = HashMap<Int, User>()
userList.put(1, User("1", "name 1", "img 1", "prof 1"))
userList.put(2, User("2", "name 2", "img 2", "prof 2"))
userList.put(3, User("3", "name 3", "img 3", "prof 3"))
userList.put(4, User("4", "name 4", "img 4", "prof 4"))
for ((key, value) in userList){
println("$key is ${value.id} name= ${value.name} image= ${value.imageUrl}")
}
Itrating loop with range operator (..)
for (i in 0..9){
println(i)
}
Range oprerator other use :
(0..9).forEach { i -> println(i) }
or
(0..9).forEach { it }
(9 downTo 0).forEach { println(it) } // print reverse 9 to 0
(0 until 9).forEach { println(it) } // print one digit less than 9
(0..7 step 2).forEach { println(it) } // print with two diff 0,2,4,6
('A'..'E').forEach { println(it) } // print A to E
val intArray:IntArray = intArrayOf(1,2,3,4,5,6)
val color = listOf("Red", "Blue", "Green")
intArray.set(2,-4)
intArray[3] = -7
intArray.forEach { println(it) } // 1 2 -4 -7 5 6
println(color[1]) // Blue
11. Exception Handling:
val result = try {
divide(5,23)
} catch (e: Exception){
println(e)
}
Article :
1. https://github.com/anitaa1990/Android-Cheat-sheet/blob/master/README.md
2. Interview Question Basic: https://www.softwaretestinghelp.com/android-interview-questions/
3. Interview Question 2 yr exp: https://blendinfotech.com/android-interview-questions-and-answers-for-2-years-experience
key skill : Learn Dagger, RxJava, Kotlin, MVVM, Architecture Components, Unit Testing.
1. Difference in activity and services
To answer this question you should have understanding of what activity and services do. Once you understand that it will be very easy to explain it.
For better understanding: https://stackoverflow.com/questions/5050005/what-is-the-difference-between-an-android-activity-and-service.
2. Difference in Activity context Vs Application context
Ans. https://blog.mindorks.com/understanding-context-in-android-application-330913e32514
3. How Android system Render/draw layout on screen
https://developer.android.com/guide/topics/ui/how-android-draws
Ans. When an Activity receives focus, it will be requested to draw its layout. The Android framework will handle the procedure for drawing, but the Activity must provide the root node of its layout hierarchy.
Drawing begins with the root node of the layout. It is requested to measure and draw the layout tree. Drawing is handled by walking the tree and rendering each View that intersects the invalid region. In turn, each ViewGroup is responsible for requesting each of its children to be drawn (with the draw() method) and each View is responsible for drawing itself. Because the tree is traversed pre-order, this means that parents will be drawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree.
4. Nested Recycler view and Nested Scroll view — advantage Vs disadvantage or issues
Sol.
Issue RV and SV : As we already know that recyclerView has a smooth scrolling by itself but when we need to put recyclerView within any scrollView it will not working.
Sol to issue: Use Nested Scroll view.
5. Given an Android app which is very slow ,For ex — UI is lagging and user has to wait a lot to see data on screen. Or May be list view scroll is slow. Where should we start looking into to find the reason.
Approach: To answer this question you must know how UI rendering happens in android. For ex you can have thousands of item to show in list, but on phones at a time limited set of data is shown. So suppose you open the screen and then you try to load data and do some parsing on those data, you have to be a little smart while doing all these. If you process all data at once it will be performance heavy and will lead to bad User experience. In such cases you should use pagination or Android Paging library. To understand pagination check my post : https://medium.com/@thegraduateguy/pagination-with-recyclerview-in-android-2506c4d09a5c
Further you should avoid any long running operation on UI thread.
6. Issues with Async task
https://blog.danlew.net/2014/06/21/the-hidden-pitfalls-of-asynctask/
AsyncTask and Rotation, AsyncTasks and the Lifecycle, Cancelling AsyncTasks, Limitations on Concurrent AsyncTasks.
The modern AsyncTask is limited to 128 concurrent tasks, with an additional queue of 10 tasks (if supporting Android 1.5, it’s a limit of ten tasks at a time, with a maximum queue of 10 tasks). That means that if you queue up more than 138 tasks before they can complete, your app will crash. Most often I see this problem when people use AsyncTasks to load Bitmaps from the net.
7. Can we change UI from asynchronous task using application context
Yes, Implementation would be AsyncTask or RxJava.
8. Design handler thread in java
To answer this one should know how handler thread works in Android. For more information about Handler Thread from Google docs and you can also refer my previous article at below link
https://medium.com/@thegraduateguy/understanding-handler-looper-and-handler-thread-5cd9bf444802
You can read about it more and then formulate your answer.
9. Activity Launch Modes
https://developer.android.com/guide/components/activities/tasks-and-back-stack
https://inthecheesefactory.com/blog/understand-android-activity-launchmode/en
10. Activity/Fragment LifeCycle
Activity: https://developer.android.com/guide/components/activities/activity-lifecycle
Fragment: https://developer.android.com/guide/components/fragments
11. Permission handling in Android
Reference: https://developer.android.com/training/permissions/requesting
12. Difference in Service and Intent Service
https://www.linkedin.com/pulse/service-vs-intentservice-android-anwar-samir/
13. Options in Android to do long running task.
Ans: Handler thread, Async task, Services ,Traditional Java threads
Be careful while using services as by default it runs on main thread so to do any long running task one must create a separate thread within service,
14. Does activity instance gets garbage collected after rotation . If activity reference is in Asynctask , will it cause null pointer after rotation?
Yes activity can get garbage collected if it’s recreated after rotation and there is no reference of it. If this is used as a weak reference it can cause null pointer exception
15. Does two activity has same UI thread ?
NO. There is only one UI thread in Android System.
16. Difference in UI thread Vs main thread in Android
https://stackoverflow.com/questions/3261370/is-main-thread-the-same-as-ui-thread
17. What changes with respect to services came in Android P and Android O
Ref: https://developer.android.com/about/versions/oreo/background
W18. hat are content provider ?
Ref: https://developer.android.com/guide/topics/providers/content-provider-basics
19. What is inter app communication in Android and how to achieve it ?
Inter app communication is way in android by which two app can communicate and/or send data to each other. Two preferred way to do it Content Provider and AIDL
For ex whenever we want to see contact detail of any user we can query contact app using content provider.
19/02/20
Q1 RecyclerView vs List view
Ans.
1. The ViewHolder pattern allows us to make our list scrolling act smoothly. It stores list row views references and, thanks to this, calling the findViewById() method only occurs a couple of times, rather than for the entire dataset and on each bind view.
without implementing the ViewHolder pattern inside the getView() method, we’ll end with inefficient scrolling in our list.
2. LayoutManager class gives the opportunity to choose the way that we want to show the row views and how to scroll the list.
ListView, we were only able to create a vertical-scrolling list, so it wasn’t that flexible.
3. ItemDecoration, if add a divider need to use DividerItemDecoration and add it to the RecyclerView.
ListView, we have to figure out rows decorations by ourselves. There is no helper class like ItemDecoration.
4. handling row views animations like list appearance and disappearance, adding or removing particular views. RecyclerView’s list animations are nice and smooth
5. RecyclerView’s adapter able to use notifyDataSetChanged() but there are also ones for particular list elements, like notifyItemInserted(), notifyItemRemoved() or even notifyItemChanged() and more. ListView, we were able to use just notifyDataSetChanged() on the adapter and then had to handle the rest ourselves.
Q2. Activity LifeCycle, senario From One activity to another. For orientation changes, Alert dialog box is open.
Q3. Different components in Room Db.
Q4. Conflict Statgegies in Db/ Room db.
Q5. Advantage of fragments.
Q6. Layout for UI design.
Q7 Different Coordinate and Constraint Layout.
Q8 Adavntage of Constraint layout over Relative, Linear layout.
Q9 Chains concept in Constraint layout.
Q10 Guide line and barrier in Constraint layout.
Q11 Difference b/w Array and List.
Q12 What is thread. Process is killed then what happen to thread, lifecycle of thread.
Q13 Dagger and RxJava.
Q14 Difference observe and subscriber in RxJava.
Q15 any Architecture pattern, MVVM explain. repository concept in MVVM
Q16 Live Data explain.
Q17 Advantage of MVVM over other Architecture pattern.
Clearn Architecture with MVVM.
Q1 Intent service different from service.
Service run in new thred or main thred. and intent service in which thread.
Ans. Service run in Main Thread.
Q2 Support Multiple Langugae in Android.
Q3 Implict intent.
Q4 Make app avalible to come in dialog picker (list of Broswers, vedio)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment