Calling callback

Here, we are calling CallBack<> from the MainActivity. This callback will have the response of the REST API request.

Let's check the MainActivity.kt code:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val githubService: GithubService = GithubServiceImpl().getGithubServiceFactory()

val call: Call<List<GitHubUserModel>> = githubService.reposOfUser("sunnat629")
call.enqueue(object: Callback<List<GitHubUserModel>>{
override fun onFailure(call: Call<List<GitHubUserModel>>, t: Throwable) {
Log.wtf("PACKTPUB", t.message)
}

override fun onResponse(call: Call<List<GitHubUserModel>>, response: Response<List<GitHubUserModel>>) {
val listItems = arrayOfNulls<String>( response.body()!!.size)
for (i in 0 until response.body()!!.size) {
val recipe = response.body()!![i]
listItems[i] = recipe.name
}
val adapter = ArrayAdapter<String>(this@MainActivity, android.R.layout.simple_list_item_1, listItems)
displayList.adapter = adapter
}
})
}
}

First of all, we need to initialize GithubServiceImpl().getGithubServiceImpl(username,password) so that we can call  reposOfUser() from  UserService. Here, I add my GitHub username in the parameter. Then, we will call enqueue(retrofit2.Callback<T>)which will be executed asynchronously and send the request and get the response. It has two functions—onResponse() and onFailure(). If there is any server-related error, then it will call onFailure()and if it gets the response and the resources, it will call onResponse(). We can use the resources of the onResponse() function for this.

Here, we will get a response of the UserModel list. So, we can use this list to show our REST output in our application UI.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.111.87