Loading image from DB in Activity OnCreate() with kotlin coroutines Android

Viewed 155

Trying to set background image from SQLite with Room in OnCreate():

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 ...
 //Some "findById" etc
 ...
    CoroutineScope(IO).launch {
        val curPicture = AppDatabase.INSTANCE!!.imageDao().getImage(GameState.curLocation.picId!!)
        withContext(Main) {
            val bmp = BitmapFactory.decodeByteArray(curPicture.image, 0, curPicture.image!!.size)
            backgroundPicture.setImageBitmap(Bitmap.createScaledBitmap(bmp, backgroundPicture.width, backgroundPicture.height, false))
        }
    }

But ImageView remains empty. I'm loading 5 images in 5 different ImageViews with 5 different coroutines at the same time and sometimes few of them become visible. I'm trying to use the same code from button, it works normal then. I understand that the problem is somewhere in the Activity lifecycle, but I don't know where exactly. How to do it right but without LiveData?

1 Answers

I also get these types of issues in the past, it is due to careless assigning of something to a function that does the same functionality but with a small difference like the input method.

So, I started to use the Glide library every time I want to load an image. Just use the following code:

Gradle Implementation

implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

Glide Code

Glide
    .with(context)
    .load(place your image here as bitmap or path)
    .centerCrop()
    .into(holder.message)
Related