4. Android Development in Kotlin – Some Advance Concepts¶
1 2 App Bundles¶
- App Bundle:
- It is the compiled version of any kotlin/java code, along with any resources and static files that are needed for the app to run.
- It used to be a bundle for each device architecture, but now it is a single bundle for all architectures that should be submitted to the play store.
- The play store takes the bundle and generates the a signed APK bundle for each device architecture.
- The App bundle is not a full APK, thus it can NOT be installed on a device, however it can be used to generate a signed APK, which Google Play does on your behalf.
- The Play Store generates hundreds of signed APKs from the app bundle, each signed APK is optimized for a different device configuration.
bundletool
is a command line tool that can be used to:- Generate APK set from an app bundle, targeting a specific device configuration(s).
- Deploy an app bundle to a connected device.
- Perform E2E testing on a device using an app bundle and test APKs.
- Estimate the download size of an app bundle.
- Basically, Google Play uses the same
bundletool
, so it is a good way to experiment with changes before submitting to the Play Store.
3 SQLite Database in Android¶
- You can use SQLite to create databases on the user’s device and access them from your app at any time.
- It is an Offline database on the user’s device, thus, no internet connection is required to access it.
- The data is stored in a text file that’s convenient for SQLite engine to read and write.
- The permissions required to use SQLite are:
android.permission.READ_EXTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE
- add them to the
AndroidManifest.xml
file in a<uses-permission>
tag.
4 5 Network Connection in Android¶
- The Android platform includes the `HttpsURLConnection`` client, which supports TLS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling.
- Third party libraries: Retrofit (on top of
OkHttp
), and Ktor (kotlin native, uses coroutines, be JetBrains). - The
DnsResolver
interface can be used to resolve host names to IP addresses, and vice versa. - Use the
Repository
pattern to abstract the data layer from the rest of the app. - Network requests can NOT be done one the main thread, as a
NetworkOnMainThreadException
will be thrown. - Functions that perform network operations should be called from a coroutine or from a different thread (aka, should be
suspend
functions). - The
ViewModel
class is designed to store and manage UI-related data in a lifecycle conscious way. That is, it holds component state between renderers (analogy touseState
in React). - Best practices:
- Before doing a request, check the network connection using
ConnectivityManager
orNetworkInfo
. - Avoid large data transfers if device is not connected to a Wi-Fi network.
- Before doing a request, check the network connection using
6 8 Exceptions in Kotlin¶
- Kotlin Try Catch is used to handle the code that could throw an exception at run-time.
try {
//code that code potentially throw and exception
} catch(e: Some_Exception) {
//code to handle if this exception is occurred
} catch(e: Exception) {
//you can have multiple catch blocks
//code to handle if this exception is occurred
} finally {
//code that will be executed regardless of whether an exception is thrown or not
}
val x = try { someFunction() } catch(e: Exception) { 0} //x will be 0 if an exception is thrown from someFunction()
Exception
is the parent class of all exceptions in Kotlin.- Other exceptions include:
ArithmeticException
,IOException
,ClassNotFoundException
. - Exceptions that do not have a suitable catch block are called uncaught exceptions, and they will cause the app to crash (still be throw even if you have a catch block for other exceptions).
- Exception has:
message
property: a string that describes the exception.printStackTrace()
method: prints the stack trace of the exception.
- Ypu can
throw Exception("message")
to throw an exception. Error
andException
are both subclasses ofThrowable
, butError
is used to indicate serious problems that a reasonable application should not try to catch, whileExceptions
are caught.- Example of errors:
OutOfMemoryError
,StackOverflowError
. - To catch all exceptions (including errors), use
catch(e: Throwable)
. - checked exceptions are java feature where a function states what errors it throws, and the callers must handle them. Kotlin does not have this feature.
7 9 Generics in Kotlin¶
class TouchedByAnAngle<T> {
private T thingy;
public T getThingy() { return thingy; }
public void setThingy(T replacement) { thingy = replacement; }
}
val m = TouchedByAnAngle<Int>()
m.setThingy(5)
m.getThingy() //5
data class Person(val name: String, val age: Int)
val p = TouchedByAnAngle<Person>()
p.setThingy(Person("John", 20))
p.getThingy() //Person(name=John, age=20)
Any
is possible to be used as a generic type, but it is not recommended.
val critters = mutableListOf(Frog(), Axolotl(), "ribbit!") //MutableList<Any> as Any is the parent of all classes in the list
- Advantage of generics: Type safety, no need for type casting, and compile time checking.
- As extension function allows to add methods to class without inherit a class or any design pattern.
10 Emulator¶
- Advantages of Emulator: Flexibility (run any Android version, any device, any screen size), Simulate any thing (GPS, network, battery, etc), and Test apps without physical device faster.
- Android Virtual Device (AVD): is a configuration that defines the characteristics of an Android phone, tablet, Wear OS, Android TV, or Automotive OS device that you want to simulate in the Android Emulator.
- The Emulator saves the state of each AVD between each session; the data is stored under a specific folder in the user’s home directory.
References¶
-
About android app bundles. (2022, March 17). Android Developers. https://developer.android.com/guide/app-bundle ↩
-
Build and test your android app bundle. (2021, July 17). Android Developers. https://developer.android.com/guide/app-bundle/test ↩
-
Chaitanyamunje. (2021, February 25). How to create and add data to SQLite database in Android? GeeksforGeeks. Retrieved July 3, 2022, from https://www.geeksforgeeks.org/how-to-create-and-add-data-to-sqlite-database-in-android/ ↩
-
Connect to the network. (2022, June 21). Android Developers. https://developer.android.com/training/basics/network-ops/connecting ↩
-
Kamal, F. (2020, April 6). Android networking with kotlin tutorial: Getting started. raywenderlich.com. https://www.raywenderlich.com/6994782-android-networking-with-kotlin-tutorial-getting-started ↩
-
Kotlin exceptions. (2021, January 21). TutorialKart. https://www.tutorialkart.com/kotlin/kotlin-exceptions/ ↩
-
Kotlin generics. (n.d.). javaTpoint. https://www.javatpoint.com/kotlin-generics ↩
-
Murphy, M. L. (2021). Elements of kotlin. CommonsWare. https://commonsware.com/Kotlin/Kotlin-FINAL.pdf licensed under Creative commons 4.0. Chapter 18: Exceptions. ↩
-
Murphy, M. L. (2021). Elements of kotlin. CommonsWare. https://commonsware.com/Kotlin/Kotlin-FINAL.pdf licensed under Creative commons 4.0. Chapter 17: Generics. ↩
-
Run apps on the android emulator | Android developers. (2021, October 28). Android Developers. https://developer.android.com/studio/run/emulator ↩