Day92 of #100DaysOfCode

Day92 of #100DaysOfCode

Hii folks 🙌

Today I will be continuing the same pathway in which we will learn about Object declarations

Unit 4: Internet

Pathway 2: Get and Display Data

https://developer.android.com/courses/android-basics-kotlin/course

Object declarations

In Kotlin, object declarations are used to declare singleton objects. Singleton pattern ensures that one, and only one, an instance of an object is created, and has one global point of access to that object. Object declaration’s initialization is thread-safe and done at first access.

Kotlin makes it easy to declare singletons. Following is an example of an object declaration and its access. Object declaration always has a name following the object keyword.

Example:

// Object declaration
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
// ...
}

val allDataProviders: Collection<DataProvider>
get() = // ...
}
// To refer to the object, use its name directly.
DataProviderManager.registerDataProvider(...)

The call to create() function on a Retrofit object is expensive and the app needs only one instance of Retrofit API service. So, we expose the service to the rest of the app using object declaration.

  • Outside the MarsApiService interface declaration, we will define a public object called MarsApi to initialize the Retrofit service. This is the public singleton object that can be accessed from the rest of the app.
object MarsApi {
}
  • Inside the MarsApi object declaration, we will add a lazily initialized retrofit object property named retrofitService of the type MarsApiService.
object MarsApi {
val retrofitService : MarsApiService by lazy {
}
}
  • Initialize the retrofitService variable using the retrofit.create() method with the MarsApiService interface.
object MarsApi {
val retrofitService : MarsApiService by lazy {
retrofit.create(MarsApiService::class.java) }
}

The Retrofit setup is done! Each time the app calls MarsApi.retrofitService, the caller will access the same singleton Retrofit object that implements MarsApiService which is created on the first access.

Call the web service in OverviewViewModel

  • In this step, we will implement the getMarsPhotos() method that calls the retrofit service and then handles the returned JSON string.

ViewModelScope

A ViewModelScope is the built-in coroutine scope defined for each ViewModel in the app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared.

  • We will use ViewModelScope to launch the coroutine and make the Retrofit network call in the background.
  • In MarsApiService, we will make getPhotos() a suspend function. So that we can call this method from within a coroutine.
@GET("photos")
suspend fun getPhotos(): String
  • We will delete the line that sets the status response to "Set the Mars API Response here!". The method getMarsPhotos() should be empty now.
private fun getMarsPhotos() {

}
  • Inside getMarsPhotos(), we will launch the coroutine using viewModelScope.launch.
private fun getMarsPhotos() {
viewModelScope.launch {
}
}

Import androidx.lifecycle.viewModelScope and kotlinx.coroutines.launch when prompted.

  • Inside viewModelScope, we will use the singleton object MarsApi, to call the getPhotos() method from the retrofitService interface. We will then save the returned response in a val called listResult.
viewModelScope.launch {
val listResult = MarsApi.retrofitService.getPhotos()
}
  • We will assign the result we just received from the backend server to the _status.value.
val listResult = MarsApi.retrofitService.getPhotos()
_status.value = listResult
  • We will now run the app, and notice that the app closes immediately, it may or may not display an error popup.
  • Click the Logcat tab in Android Studio and note the error in the log, which starts with a line like this, “------- beginning of crash"
--------- beginning of crash
22803-22865/com.example.android.marsphotos E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.android.marsphotos, PID: 22803
java.lang.SecurityException: Permission denied (missing INTERNET permission?)
...

This error message indicates the app might be missing the INTERNET permissions. We can resolve this by adding internet permissions to the app.

That is all for Day92 ✅

Thanks for reading, See you tomorrow!

--

--

--

https://www.linkedin.com/in/itskushagra

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Color Filtered Widget — Apply multiple colors over images in Flutter | Image Color Filters

Introducing: Torch

Hilt your Feature Module

Data Binding Cookbook: tasty recipes for more logic in your code

First steps with Glance (App Widgets)

Day35 of #100DaysOfCode

Building Single user chat app with Flutter and Firebase

How to improve UI design in android.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kushagra Kesav

Kushagra Kesav

https://www.linkedin.com/in/itskushagra

More from Medium

Day80 of #100DaysOfCode

Day96 of #100DaysOfCode

Day83 of #100DaysOfCode

Day77 of #100DaysOfCode