This sample code shows some crypto exchanges from CoinGecko API.
The Coingekco API is public. Here is the CoinGecko base url.
https://api.coingecko.com/api/v3/
This example is applied KTX extension.
Note - For BaseURL, you may create a "Configs file" or directly put BASEURL as a parameter.
// init retrofit
val retrofit = Retrofit.Builder()
.baseUrl(Configs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(CoinGeckoExchangeListApi::class.java)
val getExchangeCall : Call<ArrayList<ExchangeResult.ExchangeItem>> = api.getExchangeLists(50, 1)
// setup recyclerview adapter
val adapter = RvExchangeAdapter()
binding.rvList.adapter = adapter
binding.rvList.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
class RvExchangeAdapter : RecyclerView.Adapter<RvExchangeAdapter.ViewHolder>() {
var lists = ArrayList<ExchangeResult.ExchangeItem>()
fun update(lists : ArrayList<ExchangeResult.ExchangeItem>) {
this.lists = lists
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_exchange_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(lists[position])
}
override fun getItemCount(): Int {
return lists.size
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val binding = ItemExchangeListBinding.bind(itemView)
fun bind(item : ExchangeResult.ExchangeItem){
binding.item = item
Glide.with(itemView.context).asBitmap().load(item.image).into(binding.ivExchangeLogo)
}
}
}
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
val viewModel : TestViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
// init retrofit
val retrofit = Retrofit.Builder()
.baseUrl(Configs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(CoinGeckoExchangeListApi::class.java)
val getExchangeCall : Call<ArrayList<ExchangeResult.ExchangeItem>> = api.getExchangeLists(50, 1)
/**
* RecyclerVIew Adapter Setup
*/
val adapter = RvExchangeAdapter()
binding.rvList.adapter = adapter
binding.rvList.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
/**
* Loading Progress Bar
*/
binding.isLoading = true
getExchangeCall.enqueue(object : Callback<ArrayList<ExchangeResult.ExchangeItem>> {
override fun onResponse(
call: Call<ArrayList<ExchangeResult.ExchangeItem>>,
response: Response<ArrayList<ExchangeResult.ExchangeItem>>
) {
Log.d("Response", "onResponse: ${response.body()?.get(0)?.name}")
binding.isLoading = false
viewModel.updateData(response.body()!!)
}
override fun onFailure(
call: Call<ArrayList<ExchangeResult.ExchangeItem>>,
t: Throwable
) {
binding.isLoading = false
t.printStackTrace()
}
})
/**
* The viewModel observer watches the dataset changes.
* Once dataset modification is detected, it will update
*/
viewModel.data.observe(this, {
adapter.update(it)
})
}
}
class TestViewModel : ViewModel() {
private val _data : MutableLiveData<ArrayList<ExchangeResult.ExchangeItem>> by lazy {
MutableLiveData<ArrayList<ExchangeResult.ExchangeItem>>()
}
val data : MutableLiveData<ArrayList<ExchangeResult.ExchangeItem>> get() = _data
fun updateData(list : ArrayList<ExchangeResult.ExchangeItem>){
_data.postValue(list)
}
}
import com.google.gson.annotations.SerializedName
class ExchangeResult : ArrayList<ExchangeResult.ExchangeItem>(){
data class ExchangeItem(
@SerializedName("country")
val country: String?,
@SerializedName("description")
val description: String?,
@SerializedName("has_trading_incentive")
val hasTradingIncentive: Boolean?,
@SerializedName("id")
val id: String,
@SerializedName("image")
val image: String,
@SerializedName("name")
val name: String,
@SerializedName("trade_volume_24h_btc")
val tradeVolume24hBtc: Double,
@SerializedName("trade_volume_24h_btc_normalized")
val tradeVolume24hBtcNormalized: Double,
@SerializedName("trust_score")
val trustScore: Int,
@SerializedName("trust_score_rank")
val trustScoreRank: Int,
@SerializedName("url")
val url: String,
@SerializedName("year_established")
val yearEstablished: Int?
)
}
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="isLoading"
type="Boolean" />
<import type="android.view.View"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/item_exchange_list"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.core.widget.ContentLoadingProgressBar
android:id="@+id/pb_loading"
android:layout_height="0dp"
android:layout_width="0dp"
app:layout_constraintWidth_percent="0.2"
app:layout_constraintDimensionRatio="W, 1:1"
android:indeterminate="true"
android:elevation="2dp"
style="?android:attr/progressBarStyle"
android:backgroundTint="@color/design_default_color_primary"
android:visibility="@{isLoading? View.VISIBLE:View.GONE}"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="viewModel"
type="org.rakulee.retrofitexample.TestViewModel" />
<variable
name="item"
type="org.rakulee.retrofitexample.ExchangeResult.ExchangeItem" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="64dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.utils.widget.ImageFilterView
android:id="@+id/iv_exchange_logo"
android:layout_width="0dp"
android:layout_height="0dp"
android:src="@drawable/ic_launcher_foreground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="H, 1:1"
app:layout_constraintEnd_toStartOf="@+id/guideline3"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.constraintlayout.utils.widget.ImageFilterView>
<com.google.android.material.textview.MaterialTextView
android:id="@+id/tv_exchange_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{item.name}"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline3"
app:layout_constraintTop_toTopOf="parent"
tools:text="Exchange">
</com.google.android.material.textview.MaterialTextView>
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.25" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>