Implement Kotlin Project With Mvvm : Using ViewBinding

 








1- Add dependencies on Gradle:

viewBinding {
enabled = true
}

2- add dependencies for viewModel and Live data:

//ViewModel and livedata
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

//Glide
implementation 'com.github.bumptech.glide:glide:4.12.0'
implementation 'com.github.bumptech.glide:compiler:4.12.0'

3- Create class for Networking:

1-common class for networkin:
object RetrofitHelper {
val baseUrl = "https://fake-movie-database-api.herokuapp.com/"

fun getInstance(): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
// we need to add converter factory to
// convert JSON object to Java object
.build()
}
}
2- Create endPoint InterFace :
interface RetrofitService {
@GET("api?s=batman")
fun getAllMovies(): Call<MovieList>
}

4- Create Modal class or data class :

data class MovieList(@SerializedName("Search")
val mList : List<Movieee>)

/*
//if we want use inherit conspt then
@Serializable
open class BaseResponse {
@SerialName("meta")
lateinit var meta: MetaResponse
}
*/
data class Movieee(
@SerializedName("Title")
val title: String,
@SerializedName("Poster")
val poster: String,
val imdbID: String,
@SerializedName("Year")
val year: String
)
5-Create Repository  class :Inside the below repository class, we need to pass the retrofit service
 instance to perform the network call The repository class will only interact with the network source,
 the response of the network call we will handle later in ViewModel.
class MainRepository constructor(private val retrofitService: RetrofitService) {
fun getAllMovies() = retrofitService.getAllMovies()
}

6-Create ViewModel class :

class MainViewModel(private val repository: MainRepository) : ViewModel() {

val movieList = MutableLiveData<List<Movieee>>()
val errorMessage = MutableLiveData<String>()

fun getAllMovies() {
val response = repository.getAllMovies()
response.enqueue(object : Callback<MovieList> {
override fun onResponse(call: Call<MovieList>, response: Response<MovieList>) {
movieList.postValue(response.body()?.mList)
}

override fun onFailure(call: Call<MovieList>, t: Throwable) {
errorMessage.postValue(t.message)
}
})
}

}

7-ViewModel Factory : View model work for,Create viewModel Object.when we pass any value on View model constructer .then we create ;

class MyViewModelFactory constructor(private val repository: MainRepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
MainViewModel(this.repository) as T
} else {
throw IllegalArgumentException("ViewModel Not Found")
}
}
}

8-Create Adapter class:

class MainAdapter : RecyclerView.Adapter<MainViewHolder>() {

var movies = mutableListOf<Movieee>()

fun setMovieList(movies: List<Movieee>) {
this.movies = movies.toMutableList()
notifyDataSetChanged()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = LayoutRvItemBinding.inflate(inflater, parent, false)
return MainViewHolder(binding)
}

override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
val movie = movies[position]
holder.binding.movieTitle.text = movie.title
Glide.with(holder.itemView.context).load(movie.poster)
.into(holder.binding.moviePoster)

}

override fun getItemCount(): Int {
return movies.size
}
}


class MainViewHolder(val binding: LayoutRvItemBinding) : RecyclerView.ViewHolder(binding.root) {

9- Create MainActivity.kt :

class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
private lateinit var binding: ActivityMainBinding

lateinit var viewModel: MainViewModel

// private val retrofitService = RetrofitService.getInstance()
private val retrofitService= RetrofitHelper.getInstance()

val adapter = MainAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val retrofitService=RetrofitHelper.getInstance().create(RetrofitService::class.java)
val repository=MainRepository(retrofitService)
viewModel =
ViewModelProvider(this, MyViewModelFactory(repository)).get(
MainViewModel::class.java
)
binding.recyclerview.adapter = adapter

viewModel.movieList.observe(this, Observer {
Log.d(TAG, "movieList: $it")
adapter.setMovieList(it)
})

viewModel.errorMessage.observe(this, Observer {
Log.d(TAG, "errorMessage: $it")
})

viewModel.getAllMovies()

}
}

10- create layout for mainActivity.Xml:

<LinearLayout
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:orientation="vertical"
android:layout_height="wrap_content"
tools:context=".MainActivity">

<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:id="@+id/recyclerview"
tools:listitem="@layout/layout_rv_item">

</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>

11-Create Layout for Adapter:

<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:elevation="8dp"
app:cardCornerRadius="8dp">

<ImageView
android:id="@+id/moviePoster"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="fitCenter" />

<TextView
android:id="@+id/movieTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/purple_700"
android:gravity="center_vertical"
android:padding="3dp"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/white" />

</androidx.cardview.widget.CardView>

Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post