Home > Enterprise >  How can I show data from api which has single data only?
How can I show data from api which has single data only?

Time:04-23

I'm new to kotlin and I could not find related solutions. What I want to do is get the data from api(amount and currency) and show it onclick. I was able to loop data but I don't know how to unloop.

The response from api is this:

{
    "data": {
        "amount": 825,
        "currency": "hkd"
    }
}

My Model:

data class MainData(
    var data: AmountData
)

data class AmountData(
    val amount: Int,
    val currency: String,
)

My ApiService:

interface ApiService {

    @GET("posts")
    fun getPosts(): Call<MutableList<PostModel>>

    @GET("checkout/vend/CLIENT_ID/payment/request")
    fun paymentRequest(): Call<MainData>
}

My Adapter:

class PaymentAdapter(private val mainData: MainData): RecyclerView.Adapter<PaymentViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.card_post, parent, false)
        return PaymentViewHolder(view)
    }

    override fun onBindViewHolder(holder: PaymentViewHolder, position: Int) {
        return holder.bindView(mainData) // I don't even know how to bind the data
    }

    override fun getItemCount(): Int {
        return mainData.data.amount // This is also incorrect but I don't know what to do
    }
}

class PaymentViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){

    private val tvAmount: TextView = itemView.findViewById(R.id.tvAmount)
    private val tvCurrency: TextView = itemView.findViewById(R.id.tvCurrency)

    fun bindView(mainData: MainData){
        tvAmount.text = mainData.data.amount.toString()
        tvCurrency.text = mainData.data.currency
    }
}

This is the result so far.

CodePudding user response:

because you only have 1 item always you could just do

override fun getItemCount(): Int {
    return 1
}

And it might give already exactly what you want

Though, it really is unnecessary to use a RecyclerView for this then. I would remove the RecyclerView and just add two TextViews or something.

  • Related