VETLance
VETLance

Reputation: 43

Load SVG files from a API into an ImageView in Android in Kotlin

I am using Nomics API with my CryptoCurrencyTrackerApp. I already search my problem in github but i can't find proper solution. So here is my problem : My app works complitely fine but i can't load crypto currency logos in my recycler view. Here is a photo while i run my app : enter image description here

I already managed to take price,name,symbol but as you see i can't load image API nomics uses svg format as a image Can some one help me with load imageviews Here is my code :

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

private val nameView: TextView = itemView.findViewById(R.id.coinName)

private val priceView: TextView = itemView.findViewById(R.id.priceUsd)

private val currencyView: TextView = itemView.findViewById(R.id.coinSymbol)

private val imageCurrencyView : ImageView = itemView.findViewById(R.id.imgCurrencyIcon)

fun bind(cryptoModel: CoinModel) {

    this.nameView.text = cryptoModel.name

    this.currencyView.text = cryptoModel.currency
    
    when {

        cryptoModel.price ?: 0.0 > 100.0 -> {
            this.priceView.text = String.format("%.0f", cryptoModel.price)
        }

        cryptoModel.price ?: 0.0 > 1.0 -> {
            this.priceView.text = String.format("%.2f", cryptoModel.price)
        }

        else -> {
            this.priceView.text = String.format("%.4f", cryptoModel.price)
        }

    }

}

} My CurrencyFragment

class CurrencyFragment : Fragment() {

private val baseUrl = "https://api.nomics.com/v1/currencies/"

private var cryptoModels: ArrayList<CoinModel>? = arrayListOf()

private var fragmentView: View? = null

private var recyclerView: RecyclerView? = null

private var coinAdapter: CoinAdapter? = null



override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.fragment_currency, container, false)
    }

    return fragmentView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.coin_recycler_view)

    coinAdapter = context?.let { CoinAdapter(it, arrayListOf()) }

    recyclerView?.layoutManager =
        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

    recyclerView?.adapter = coinAdapter

    loadData()

}


private fun loadData() {

    val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val service = retrofit.create(CryptoAPI::class.java)

    val call = service.getData()

    call.enqueue(object : Callback<List<CoinModel>> {
        @SuppressLint("NotifyDataSetChanged")
        override fun onResponse(
            call: Call<List<CoinModel>>,
            response: Response<List<CoinModel>>
        ) {
            if (response.isSuccessful) {

                response.body()?.let {
                    cryptoModels = ArrayList(it)

                    coinAdapter?.cryptoList = cryptoModels ?: arrayListOf()

                    coinAdapter?.notifyDataSetChanged()

                }
            }

        }

        override fun onFailure(call: Call<List<CoinModel>>, t: Throwable) {

            t.printStackTrace()

        }

    })

}

} My CoinModel

data class CoinModel(

var currency: String?="",

var price: Double? = 0.0,

var name: String?="",

var logo_url: String? = "",

var rank: String = "",

) My CoinAdapter

class CoinAdapter(var context: Context, var cryptoList: ArrayList<CoinModel>):RecyclerView.Adapter<CoinViewHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoinViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.currency_item,parent,false)
    return CoinViewHolder(view,)

}

override fun onBindViewHolder(holder: CoinViewHolder, position: Int) {

    holder.bind(cryptoList[position])





}

override fun getItemCount(): Int {
    return cryptoList.count()
}

} And finally My Interface :

interface CryptoAPI {

@GET("ticker?key=mykey")

fun getData():Call<List<CoinModel>>

}

Upvotes: 2

Views: 2016

Answers (3)

Mert
Mert

Reputation: 1005

Coil can be used for that. Add below dependencies to your build.gradle(:app)

    implementation("io.coil-kt:coil:1.2.0")
    implementation("io.coil-kt:coil-svg:1.2.0")

Create a method for that:

fun ImageView.loadUrl(url: String) {

        val imageLoader = ImageLoader.Builder(this.context)
            .componentRegistry { add(SvgDecoder([email protected])) }
            .build()

        val request = ImageRequest.Builder(this.context)
            //.crossfade(true)
            //.crossfade(500)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .data(url)
            .target(this)
            .build()

        imageLoader.enqueue(request)
    }

And finally call that method where you wanna load your image, in your case your adapter's onBindViewHolder:

yourImageView.loadUrl(cryptoList[position].image)

Upvotes: 1

gauravD
gauravD

Reputation: 89

Use Coil Svg have inbuilt loaders and SVG decoder works well with Compose UI as well

Upvotes: 0

Waqar Ahmed
Waqar Ahmed

Reputation: 399

I have found a solution to display the svg in imageview. I was facing the same issue then I use the following lib. It's working fine for me to display the SVG image in android Imageview from API and local files

Sharp lib for SVG

Upvotes: 1

Related Questions