So I'm working on Android Tv I'm want to retrieve image using Retrofit API then keep it in array and and display image change by time.
I be able to retrieve data using Retrofit but I have problem trying to display data I retrieve it from Retrofit , I'm trying to convert it with Picasso but also have some problem with that. I'm new to Kotlin and Android so can you guide me through this
Here is my code
class MainActivity : FragmentActivity() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var rf = Retrofit.Builder()
.baseUrl(RetrofitInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
var API = rf.create(RetrofitInterface::class.java)
var call:Call<List<Post?>?>? = API.posts
call?.enqueue(object:Callback<List<Post?>?>{
override fun onResponse(call: Call<List<Post?>?>, response: Response<List<Post?>?>) {
var postList : List<Post>? = response.body() as List<Post>
var post = arrayOfNulls<String>(postList!!.size)
for(i in postList!!.indices)
post[i] = postList!![i]!!.url
var adapter = ArrayAdapter<String>(applicationContext,android.R.layout.simple_dropdown_item_1line,post)
// val ListView = findViewById<ListView>(R.id.listview)
// val ImageView = findViewById<ImageView>(R.id.imageView)
// ListView.adapter = adapter
setUI(adapter)
//
}
override fun onFailure(call: Call<List<Post?>?>, t: Throwable) {
TODO("Not yet implemented")
}
})
}
fun setUI(adapter: ArrayAdapter<String>) {
// link with imageView
val ImageView = findViewById<ImageView>(R.id.imageView)
// local image
// var imgResId= arrayOf(R.drawable.image1, R.drawable.image2,R.drawable.image4)
var imgResId = arrayOf(adapter)
object : Runnable {
var updateInterval = 3000 //= 3 second
var currentIndex = -1
override fun run() {
currentIndex += 1;
if(currentIndex == imgResId.size){
currentIndex = 0;
}
ImageView.setImageResource(imgResId[currentIndex])
ImageView.postDelayed(this, updateInterval.toLong())
}
}.run()
}
}
in fun setUI()
I'm be able to display image using local image but having problem with Retrofit
Thank you
ImageView.setImageResource(imgResId[currentIndex]) from url you have to Set this Using Picaso or Glide i suggest you to use Glide
fun loadImage(
activity: Context?, ivUser: ImageView, thumbnailImage: String?,
originalImage: String?
) {
activity?.let {
Glide.with(it).load(originalImage)
.apply(RequestOptions().placeholder(R.drawable.ic_profilepic_placeholder))
.thumbnail(Glide.with(activity).load(thumbnailImage))
.into(ivUser)
}
}
ImageView.loadImage(your image url)