REST api Call Retrofit using Callback in Kotlin
In android many type of data storing and operations. That means Create Read Update Delete ( CRUD ). Data storing in android internal storage using like for SQLite and Room. If that data is small amout of data and its a key value pair used shared preference and Datastore. This are in connected with internal storage. But here store a limit amout of data and that not in a network based.
for example,
We have lot of data in online shopping like images of products and its category,name,price,quantity etc. That huge data stored in a Room DB. But how can access this datas in another device use as shopping app. Its not possible so we are using backend technologies. That means the backend is actually a computer in that we are store the huge amount of data and to store data using SQL or NoSQL database technologies, also contain backend programs (php, Laravel , Node Js, Node Js Express , python Django, Java hibernate etc…) for CRUD operations. This type webtechnology developers called backend developers. This backend developers provide a URL when we call that URL and returns data. This kind of URL is called API.
So,
In android this type Api called and perform action in server like CRUD operations. And manage huge amount of data.Here its very faster and user friendly application is possible. In kotlin avalable to call Api lot of dependacies. The most popular two dependancies are Volley and Retrofit. We will discuss volley in next time.
Retrofit is actually a dependacy to help call api and perform actions (CRUD ). Retrofit contains two type of api calling first one callback method. Its an old method and another one is response method.Here we are discussing about callback method.
Here we using open api
https://gorest.co.in/public/v1/users
Steps for Api call below,
1. Add Dependancies
in build.gradle,
plugins {
id ‘com.android.application’
id ‘org.jetbrains.kotlin.android’
id ‘kotlin-android-extensions’
}
android {
compileSdk 32
defaultConfig {
applicationId “com.riyaspullur.learningrestapimethods”
minSdk 21
targetSdk 32
versionCode 1
versionName “1.0”
testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = ‘1.8’
}
}
dependencies {
implementation ‘androidx.core:core-ktx:1.7.0’
implementation ‘androidx.appcompat:appcompat:1.4.1’
implementation ‘com.google.android.material:material:1.6.0’
implementation ‘androidx.constraintlayout:constraintlayout:2.1.3’
//Retrofit Dependancy for Process actions using api
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
//Gson convertor to fetch Json data from api and convert in to Kotlin objects
implementation ‘com.squareup.retrofit2:converter-gson:2.9.0’
//depndacy for lifeccycle viwmodel
implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’
//logging Interceptor Depndancy used For monitoring data.
implementation ‘com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.7’
testImplementation ‘junit:junit:4.13.2’
androidTestImplementation ‘androidx.test.ext:junit:1.1.3’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.4.0’
}
2.Test Api
Just call api through browser of any api testing tools like Postman and test api is it working or not if it succesfull we can see json data and its arrays and so on.
3. Copy Json Data And Generate Kotlin Data class.( generate kotlin calss is plugin download.)
4. Activate permission of Internet.
AndroidManifest.xml
<?xml version=”1.0" encoding=”utf-8"?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android" xmlns:tools=”http://schemas.android.com/tools" package=”com.riyaspullur.learningrestapimethods”>
<uses-permission android:name=”android.permission.INTERNET” />
<application android:allowBackup=”true” android:dataExtractionRules=”@xml/data_extraction_rules” android:fullBackupContent=”@xml/backup_rules” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:roundIcon=”@mipmap/ic_launcher_round” android:supportsRtl=”true” android:theme=”@style/Theme.LearningRESTAPIMethods” tools:targetApi=”31">
<activity android:name=”.CreateNewUserActivity” android:exported=”false” />
<activity android:name=”.MainActivity” android:exported=”true”> <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity>
</application>
</manifest>
5. Create layout to perform actions in api
activity_create_new_user.xml
<?xml version=”1.0" encoding=”utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=”http://schemas.android.com/apk/res/android"
xmlns:app=”http://schemas.android.com/apk/res-auto"
xmlns:tools=”http://schemas.android.com/tools"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.CreateNewUserActivity”>
<EditText
android:id=”@+id/editTextName”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”20dp”
android:layout_marginEnd=”20dp”
android:hint=”Enter Name”
android:textColor=”@color/black”
android:textSize=”20dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.0"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.07" />
<EditText
android:id=”@+id/editTextEmail”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”20dp”
android:layout_marginEnd=”20dp”
android:hint=”Enter Email”
android:textColor=”@color/black”
android:textSize=”20dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.0"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.169" />
<EditText
android:id=”@+id/editTextGender”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”20dp”
android:layout_marginEnd=”20dp”
android:hint=”Gender”
android:textColor=”@color/black”
android:textSize=”20dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”1.0"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.269" />
<EditText
android:id=”@+id/editTextUserID”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”20dp”
android:layout_marginEnd=”20dp”
android:hint=”UserID”
android:textColor=”@color/black”
android:textSize=”20dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.0"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.732" />
<Button
android:id=”@+id/createButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:backgroundTint=”@color/black”
android:text=”create”
android:textSize=”20sp”
android:textStyle=”bold”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.115"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.436" />
<Button
android:id=”@+id/deleteButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:backgroundTint=”@color/black”
android:text=”delete”
android:textSize=”20sp”
android:textStyle=”bold”
android:visibility=”gone”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.851"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.434" />
</androidx.constraintlayout.widget.ConstraintLayout>
6. Create Row card for Recycler
recycler_row_list.xml
<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android"
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”
android:padding=”5dp”
android:layout_margin=”4dp”
android:background=”#FFD7D7">
<TextView
android:layout_width=”match_parent”
android:background=”@color/black”
android:gravity=”center”
android:layout_height=”wrap_content”
android:textStyle=”bold”
android:textColor=”@color/white”
android:text=”name”
android:textSize=”20sp”
android:id=”@+id/textViewName”/>
<TextView
android:layout_width=”match_parent”
android:background=”@color/black”
android:gravity=”center”
android:layout_height=”wrap_content”
android:textStyle=”bold”
android:textColor=”@color/white”
android:text=”email”
android:textSize=”18sp”
android:id=”@+id/textViewEmail”/>
<TextView
android:layout_width=”match_parent”
android:background=”@color/black”
android:gravity=”center”
android:layout_height=”wrap_content”
android:textStyle=”bold”
android:textColor=”@color/white”
android:text=”status”
android:textSize=”16sp”
android:id=”@+id/textViewStatus”/>
<TextView
android:layout_width=”match_parent”
android:background=”@color/black”
android:gravity=”center”
android:layout_height=”wrap_content”
android:textStyle=”bold”
android:textColor=”@color/white”
android:text=”status”
android:textSize=”16sp”
android:id=”@+id/textViewGender”/>
<TextView
android:layout_width=”match_parent”
android:background=”@color/black”
android:gravity=”center”
android:layout_height=”wrap_content”
android:textStyle=”bold”
android:textColor=”@color/white”
android:text=”ID number”
android:textSize=”16sp”
android:id=”@+id/textViewID”/>
</LinearLayout>
7.Design activity_main
activity_main.xml
<?xml version=”1.0" encoding=”utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=”http://schemas.android.com/apk/res/android"
xmlns:app=”http://schemas.android.com/apk/res-auto"
xmlns:tools=”http://schemas.android.com/tools"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#E6F7FB”
tools:context=”.MainActivity”>
<com.google.android.material.textfield.TextInputEditText
android:id=”@+id/searchEditText”
android:shadowRadius=”@integer/material_motion_duration_long_1"
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”10dp”
android:layout_marginEnd=”10dp”
android:padding=”5dp”
android:textSize=”18dp”
android:background=”#F1C5EA”
android:hint=”Search User”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.037"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.048" />
<Button
android:id=”@+id/search_button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Search”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.827"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.125" />
<androidx.recyclerview.widget.RecyclerView
android:id=”@+id/recyclerView”
android:layout_width=”match_parent”
android:layout_height=”455dp”
android:layout_margin=”10dp”
android:padding=”5dp”
android:background=”@color/white”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.515"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.8" />
<Button
android:id=”@+id/createUserButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”create”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.059"
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.125" />
</androidx.constraintlayout.widget.ConstraintLayout>
8. When Generated Data calss Name ‘UserList’ so other class Auto Generate.
//data class to hold data
data class UserList( val data:List<User>)
data class User( var id:String?, var name:String?, var email:String?, var gender:String?, var status:String?)
data class UserResponse(val code:Int?, val meta:String?, val data:User?)
9. Create Instance class named ‘RetrofitInstance’
class RetrofitInstance {
var BASE_URL=”https://gorest.co.in/public/v1/"
fun getRetroInstance():Retrofit{
val logg=HttpLoggingInterceptor() logg.level=(HttpLoggingInterceptor.Level.BODY)
val client=OkHttpClient.Builder()
client.addInterceptor(logg)
return Retrofit.Builder() .baseUrl(BASE_URL) .client(client.build())
.addConverterFactory(GsonConverterFactory.create()) .build()
}
}
}
10. create Interface for call HTTP methods
interface RetroService.kt
//users is sub url
@GET(“users”)
@Headers(“Accept:application/json”,”Content-Type:application/json”)
fun getUserList():Call<UserList>
interface RetroService {
//https://gorest.co.in/public/v2/users?name=a
@GET(“users”)
@Headers(“Accept:application/json”,”Content-Type:application/json”)
fun searchUsers(@Query(“name”) searchText:String):Call<UserList>
//https://gorest.co.in/public/v2/users/3838
@GET(“users/{user_id}”)
@Headers(“Accept:application/json”,”Content-Type:application/json”)
fun getUsers(@Path(“user_id”) user_id:String):Call<UserResponse>
@POST(“users”)
@Headers(“Accept:application/json”,”Content-Type:application/json”, “Authorization: Bearer 93e0d54a7328dabcbed3f20c726427178bba5eef1ce095251dcf1d44c573a16c”)
fun createUser(@Body params:User):Call<UserResponse>
@PATCH(“users/{user_id}”)
@Headers(“Accept:application/json”,”Content-Type:application/json”, “Authorization: Bearer 93e0d54a7328dabcbed3f20c726427178bba5eef1ce095251dcf1d44c573a16c”)
fun updateUser(@Path(“user_id”) user_id:String,@Body params:User):Call<UserResponse>
@DELETE(“users/{user_id}”)
@Headers(“Accept:application/json”,”Content-Type:application/json”, “Authorization: Bearer 93e0d54a7328dabcbed3f20c726427178bba5eef1ce095251dcf1d44c573a16c”)
fun deleteUser(@Path(“user_id”) user_id:String):Call<UserResponse>
}
11. Create view model named
CreateNewUserViewModel.kt
class CreateNewUserViewModel :ViewModel(){
lateinit var createNewUserLiveData:MutableLiveData<UserResponse?>
lateinit var loadUserData:MutableLiveData<UserResponse?>
lateinit var deleteUserLiveData:MutableLiveData<UserResponse?>
init {
createNewUserLiveData= MutableLiveData()
loadUserData= MutableLiveData()
deleteUserLiveData= MutableLiveData()
}
fun getCreateNewUserObservable():MutableLiveData<UserResponse?>{
return createNewUserLiveData
}
fun getLoadUserObservable():MutableLiveData<UserResponse?>{
return loadUserData
}
fun getdeleteUserObservable():MutableLiveData<UserResponse?>{
return deleteUserLiveData
}
fun createUser(user:User){
val retroInstance=RetrofitInstance.getRetroInstance()
.create(RetroService::class.java)
val call=retroInstance.createUser(user)
call.enqueue(object:Callback<UserResponse?> {
override fun onResponse(call: Call<UserResponse?>, response:Response<UserResponse?>) {
if (response.isSuccessful){ createNewUserLiveData.postValue(response.body())
}else{
createNewUserLiveData.postValue(null)
}
}
override fun onFailure(call: Call<UserResponse?>, t: Throwable) {
createNewUserLiveData.postValue(null)
}
})
}
fun updateUser(user_id:String,user:User){
val retroInstance=RetrofitInstance.getRetroInstance()
.create(RetroService::class.java)
val call=retroInstance.updateUser(user_id,user)
call.enqueue(object:Callback<UserResponse?> {
override fun onResponse(call: Call<UserResponse?>, response: Response<UserResponse?>) {
if (response.isSuccessful){ createNewUserLiveData.postValue(response.body())
}else{
createNewUserLiveData.postValue(null)
}
}
override fun onFailure(call: Call<UserResponse?>, t: Throwable) { createNewUserLiveData.postValue(null)
}
})
}
fun deleteUser(user_id:String?){
val retroInstance=RetrofitInstance.getRetroInstance()
.create(RetroService::class.java)
val call=retroInstance.deleteUser(user_id!!)
call.enqueue(object:Callback<UserResponse?> {
override fun onResponse(call: Call<UserResponse?>, response: Response<UserResponse?>) {
if (response.isSuccessful){
deleteUserLiveData.postValue(response.body())
}else{
deleteUserLiveData.postValue(null)
}
}
override fun onFailure(call: Call<UserResponse?>, t: Throwable) { deleteUserLiveData.postValue(null)
}
})
}
fun getUserData(user_id:String?){
val retroInstance=RetrofitInstance.getRetroInstance()
.create(RetroService::class.java)
val call=retroInstance.getUsers(user_id!!)
call.enqueue(object:Callback<UserResponse?> {
override fun onResponse(call: Call<UserResponse?>, response: Response<UserResponse?>) {
if (response.isSuccessful){
loadUserData.postValue(response.body())
}else{
loadUserData.postValue(null)
}
}
override fun onFailure(call: Call<UserResponse?>, t: Throwable) { loadUserData.postValue(null)
}
})
}
}
12. Create kotlin class for activity_create_new_user
CreateNewUserActivity.kt
class CreateNewUserActivity : AppCompatActivity() {
lateinit var viewModel: CreateNewUserViewModel
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_create_new_user)
var user_id=intent.getStringExtra(“user_id”)
initViewModel()
createUserObservable()
if (user_id!=null){
loadUserData(user_id)
}
var aa=1111
createButton.setOnClickListener {
aa++
user_id=”$aa”
createUser(user_id!!)
}
deleteButton.setOnClickListener {
deleteUser(user_id)
}
}
private fun deleteUser(user_id:String?){ viewModel.getdeleteUserObservable().observe(
this, Observer <UserResponse?>{
if (it==null){
Toast.makeText(this,”Failed to Delete”,Toast.LENGTH_LONG).show()
}else{
Toast.makeText(this,”Successfully Deleted User”,Toast.LENGTH_LONG).show()
finish()
} //Toast.makeText(this,”Failed to create”,Toast.LENGTH_LONG).show()
})
viewModel.deleteUser(user_id!!)
}
private fun loadUserData(user_id:String?){ viewModel.getLoadUserObservable().observe(
this, Observer <UserResponse?>{
if (it!=null){
editTextName.setText(it.data?.name)
editTextEmail.setText(it.data?.email) editTextGender.setText(it.data?.gender)
createButton.setText(“Update”)
deleteButton.visibility=View.VISIBLE
} //Toast.makeText(this,”Failed to create”,Toast.LENGTH_LONG).show()
})
viewModel.getUserData(user_id)
}
private fun createUser(user_id:String) {
val user=User(“”,editTextName.text.toString(),
editTextEmail.text.toString(),
editTextGender.text.toString(),”Active”
)
if (user_id==null) viewModel
.createUser(user) else
viewModel.updateUser(user_id,user)
}
private fun initViewModel() { viewModel=ViewModelProvider(this).get(
CreateNewUserViewModel::class.java )
}
private fun createUserObservable(){ viewModel.getCreateNewUserObservable().observe(
this, Observer <UserResponse?>{
if (it==null){
Toast.makeText(this,”Failed to create / Update”,Toast.LENGTH_LONG).show()
}else{
Toast.makeText(this,”Succesfully created / Updated User”,Toast.LENGTH_LONG
).show()
finish()
}
})
}
}
13. Create view model for main activity
MainActivityViewModel.kt
class MainActivityViewModel:ViewModel() {
lateinit var recyclerListData:MutableLiveData<UserList>
init {
recyclerListData= MutableLiveData()
}
fun getUserListObservable():MutableLiveData<UserList>{
return recyclerListData
}
fun getUserList(){
val retroInstance=RetrofitInstance.getRetroInstance().create(
RetroService::class.java
)
val call=retroInstance.getUserList()
call.enqueue(object:Callback<UserList>{
override fun onResponse(call: Call<UserList>, response: Response<UserList>) {
if (response.isSuccessful){
recyclerListData.postValue(response.body())
}else{
recyclerListData.postValue(null)
}
}
override fun onFailure(call: Call<UserList>, t: Throwable) { recyclerListData.postValue(null)
}
})
}
fun searchUserList(searchText:String){
val retroInstance=RetrofitInstance.getRetroInstance().create(
RetroService::class.java
)
val call=retroInstance.searchUsers(searchText)
call.enqueue(object:Callback<UserList>{
override fun onResponse(call: Call<UserList>, response: Response<UserList>) {
if (response.isSuccessful){
recyclerListData.postValue(response.body())
}else{
}
}
override fun onFailure(call: Call<UserList>, t: Throwable) { recyclerListData.postValue(null)
}
})
}
}
14. Create adapter for Recyclerview
RecyclerViewAdapter.kt
class RecyclerViewAdapter(
val clickListener:OnItemClickListener) :
RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>() {
var userList= mutableListOf<User>()
class MyViewHolder(view:View):RecyclerView.ViewHolder(view) {
val textViewName=view.textViewName val textViewEmail=view.textViewEmail
val textViewStatus=view.textViewStatus
val textViewGender=view.textViewGender
val textViewId=view.textViewID
fun bind(data:User){
textViewName.text=data.name
textViewEmail.text=data.email
textViewStatus.text=data.status
textViewGender.text=data.gender
textViewId.text=”id = ${data.id}”
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater=LayoutInflater.from(parent.context)
.inflate(R.layout.recycler_row_list,parent,false)
return MyViewHolder(inflater)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(userList[position])
holder.itemView.setOnClickListener { clickListener.onItemEditClick(userList[position])
}
}
override fun getItemCount(): Int
return userList.size
}
interface OnItemClickListener{
fun onItemEditClick(user:User)
}
}
15 . activity_main.xml for create Main activity class
MainActivity.kt
class MainActivity : AppCompatActivity(),RecyclerViewAdapter.OnItemClickListener {
lateinit var reclerViewAdapter:RecyclerViewAdapter
lateinit var viewModel:MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initRecycleView()
initViewModel()
searchUser()
createUserButton.setOnClickListener { startActivity(Intent(this,CreateNewUserActivity::class.java))
}
}
private fun searchUser() {
search_button.setOnClickListener {
if (!TextUtils.isEmpty(searchEditText.toString())){ viewModel.searchUserList(searchEditText.text.toString())
}else{
viewModel.getUserList()
}
}
}
private fun initRecycleView() {
recyclerView.apply { layoutManager=LinearLayoutManager(this@MainActivity)
val decoration=DividerItemDecoration(
this@MainActivity,DividerItemDecoration.VERTICAL)
addItemDecoration(decoration) reclerViewAdapter= RecyclerViewAdapter(this@MainActivity)
adapter=reclerViewAdapter
}
}
fun initViewModel(){
viewModel = ViewModelProvider(this)
.get(MainActivityViewModel::class.java)
viewModel.getUserListObservable()
.observe(this, Observer<UserList>{
if (it==null){ Toast.makeText(this,”no result found…”,Toast.LENGTH_LONG).show()
}else{
reclerViewAdapter.userList=it.data.toMutableList() reclerViewAdapter.notifyDataSetChanged()
}
})
viewModel.getUserList()
}
override fun onItemEditClick(user: User) {
val intent=Intent(this,CreateNewUserActivity::class.java) intent.putExtra(“user_id”,user.id) startActivityForResult(intent,1000)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data) if (requestCode==1000){ viewModel.getUserList()
}
}
}
Callback method completed…
Just look
HTTP methods
1 GET
The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
2 HEAD
Same as GET, but transfers the status line and header section only.
3 POST
A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
4 PUT
Replaces all current representations of the target resource with the uploaded content.
5 DELETE
Removes all current representations of the target resource given by a URI.
6 CONNECT
Establishes a tunnel to the server identified by a given URI.
7 OPTIONS
Describes the communication options for the target resource.
8 TRACE
Performs a message loop-back test along the path to the target resource.
Http response codes.
- Informational responses (
100
–199
) - Successful responses (
200
–299
) - Redirection messages (
300
–399
) - Client error responses (
400
–499
) - Server error responses (
500
–599
)
Thank you for reading.
If think Buy me a coffee,
https://www.paypal.com/paypalme/riyaspullur?country.x=IN&locale.x=en_GB