Skip to content

Instantly share code, notes, and snippets.

@senamit2708
Created July 11, 2023 07:11
Show Gist options
  • Save senamit2708/6c3c01469b723f1d4cc958abf504bca9 to your computer and use it in GitHub Desktop.
Save senamit2708/6c3c01469b723f1d4cc958abf504bca9 to your computer and use it in GitHub Desktop.
Retrofit Basic Learning
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
package com.example.coroutinelearning.retrofits
import com.example.coroutinelearning.entity.Root
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiInterface {
@GET("/api/users")
suspend fun getAllUser(
@Query("page") currentPage: Int, @Query("per_page") pageSize: Int
): Response<Root>
}
package com.example.coroutinelearning.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.entity.User
@Database(entities = [User::class, Customer::class], version = 1, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
abstract fun getUserDao(): UserDao
abstract fun getCustomerDao(): CustomerDao
companion object{
private var INSTANCE: AppDatabase? = null
private const val DB_NAME = "database"
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
DB_NAME
).build()
INSTANCE = instance
instance
}
}
}
}
//retrofit
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.1'
<?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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/userRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Switch
android:id="@+id/switchDataLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Switch"
app:layout_constraintBottom_toTopOf="@+id/userRecyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="@+id/textView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Online Data"
android:textColor="#6C0606"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/userRecyclerView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>c
<?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="wrap_content"
android:layout_marginBottom="10dp">
<androidx.cardview.widget.CardView
android:id="@+id/userCard"
android:layout_width="0dp"
android:layout_height="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/divider2"
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_marginStart="120dp"
android:background="?android:attr/listDivider"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="invisible" />
<ImageView
android:id="@+id/imgUser"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/divider2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="@tools:sample/avatars" />
<TextView
android:id="@+id/txtName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="17dp"
android:layout_marginEnd="8dp"
android:fontFamily="sans-serif-black"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="@+id/divider2"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtEmailId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/divider2"
app:layout_constraintTop_toBottomOf="@+id/txtName"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.coroutinelearning.database
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.coroutinelearning.entity.Customer
@Dao
interface CustomerDao {
@Query("SELECT * FROM customer")
suspend fun getAll(): List<Customer>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(customerList: List<Customer>): LongArray
@Delete
suspend fun delete(customer: Customer)
@Query("DELETE FROM customer")
suspend fun clearAll()
}
package com.example.coroutinelearning.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
data class Root(
@SerializedName("page") var page: Int? = null,
@SerializedName("per_page") var perPage: Int? = null,
@SerializedName("total") var total: Int? = null,
@SerializedName("total_pages") var totalPages: Int? = null,
@SerializedName("data") var data: ArrayList<Customer> = arrayListOf(),
@SerializedName("support") var support: Support? = Support()
)
@Entity(tableName = "customer")
data class Customer(
@SerializedName("id") @PrimaryKey var id: Int,
@SerializedName("email") var email: String? = null,
@SerializedName("first_name") var firstName: String? = null,
@SerializedName("last_name") var lastName: String? = null,
@SerializedName("avatar") var avatar: String? = null
)
data class Support(
@SerializedName("url") var url: String? = null,
@SerializedName("text") var text: String? = null
)
package com.example.coroutinelearning.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.coroutinelearning.databinding.CustomerListAdapterBinding
import com.example.coroutinelearning.entity.Customer
class CustomerListAdapter(val context: Context) :
RecyclerView.Adapter<CustomerListAdapter.ViewHolder>() {
private val TAG = CustomerListAdapter::class.simpleName
private lateinit var binding: CustomerListAdapterBinding
private var customerList: List<Customer>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
binding =
CustomerListAdapterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return customerList?.size ?: 0
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.txtName.text =
customerList?.get(position)?.firstName + " " + customerList?.get(position)?.lastName
holder.txtEmail.text = customerList?.get(position)?.email
Glide.with(context).load(customerList?.get(position)?.avatar).into(holder.imageUser)
}
fun setCustomerList(customerList: List<Customer>) {
this.customerList = customerList
notifyDataSetChanged()
}
class ViewHolder(binding: CustomerListAdapterBinding) : RecyclerView.ViewHolder(binding.root) {
val txtName = binding.txtName
val txtEmail = binding.txtEmailId
val imageUser = binding.imgUser
}
}
package com.example.coroutinelearning.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.coroutinelearning.adapter.CustomerListAdapter
import com.example.coroutinelearning.databinding.CustomerListBinding
import com.example.coroutinelearning.viewModels.CustomerViewModel
class CustomerListFragment : Fragment() {
private val TAG = CustomerListFragment::class.simpleName
private lateinit var binding: CustomerListBinding
private val mLayoutManager: LinearLayoutManager by lazy {
LinearLayoutManager(requireContext())
}
private val mCustomerListAdapter: CustomerListAdapter by lazy {
CustomerListAdapter(requireContext())
}
private val customerViewModel: CustomerViewModel by lazy {
ViewModelProvider(requireActivity()).get(CustomerViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
binding = CustomerListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.userRecyclerView.adapter = mCustomerListAdapter
binding.userRecyclerView.layoutManager = mLayoutManager
if (binding.switchDataLoad.isChecked) loadDataFromServer()
else loadDataFromDb()
binding.switchDataLoad.setOnCheckedChangeListener { compoundButton, isChecked ->
if (isChecked) loadDataFromServer()
else loadDataFromDb()
}
}
private fun loadDataFromDb() {
mCustomerListAdapter.setCustomerList(listOf())
customerViewModel.getCustomerListDB().observe(viewLifecycleOwner) { customerList ->
customerList?.let {
mCustomerListAdapter.setCustomerList(customerList)
}
}
}
private fun loadDataFromServer() {
mCustomerListAdapter.setCustomerList(listOf())
customerViewModel.getCustomerList().observe(viewLifecycleOwner) { customerList ->
customerList?.let {
mCustomerListAdapter.setCustomerList(customerList)
}
}
}
}
package com.example.coroutinelearning.repositories
import android.app.Application
import android.util.Log
import com.example.coroutinelearning.database.AppDatabase
import com.example.coroutinelearning.database.CustomerDao
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.retrofits.RetrofitHelper
class CustomerRepository(application: Application) {
private val TAG = CustomerRepository::class.simpleName
private val appDatabase: AppDatabase
private val customerDao: CustomerDao
init {
appDatabase = AppDatabase.getDatabase(application)
customerDao = appDatabase.getCustomerDao()
}
suspend fun getCustomerList(): List<Customer>? {
val result = RetrofitHelper.getServices().getAllUser(1, 12)
val customerData = result.body()?.data
saveCustomerDataToDB(customerData)
return customerData
}
suspend fun saveCustomerDataToDB(customerData: List<Customer>?) {
customerData?.let {
val entrySuccessful = customerDao.insertAll(customerData)
Log.i(TAG, "customer data entry is successful: $entrySuccessful")
}
}
suspend fun getCustomerListDB(): List<Customer> {
return customerDao.getAll()
}
}
package com.example.coroutinelearning.viewModels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.coroutinelearning.entity.Customer
import com.example.coroutinelearning.repositories.CustomerRepository
import kotlinx.coroutines.launch
class CustomerViewModel(application: Application) : AndroidViewModel(application) {
private val TAG = CustomerViewModel::class.simpleName
private val repository: CustomerRepository
private val customerListLiveData: MutableLiveData<List<Customer>?> = MutableLiveData()
private val customerListDBLiveData = MutableLiveData<List<Customer>>()
init {
repository = CustomerRepository(application)
}
fun getCustomerList(): MutableLiveData<List<Customer>?> {
viewModelScope.launch {
val customerList = repository.getCustomerList()
customerListLiveData.value = customerList
}
return customerListLiveData
}
fun getCustomerListDB(): MutableLiveData<List<Customer>> {
viewModelScope.launch {
val customerList = repository.getCustomerListDB()
customerListDBLiveData.value = customerList
}
return customerListDBLiveData
}
}
package com.example.coroutinelearning.retrofits
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitHelper{
private const val baseUrl = "https://reqres.in"
private val mHttpLoginInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
private val mOkHttpClient = OkHttpClient.Builder()
.addInterceptor(mHttpLoginInterceptor)
.build()
fun getInstance() : Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(mOkHttpClient)
.build()
}
fun getServices() : ApiInterface{
return getInstance().create(ApiInterface::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment