繁体   English   中英

Android Kotlin Firebase 如何同时检索两个图像并将它们添加到位图数组中?

[英]Android Kotlin Firebase How to retrieve two image at the same time and add them into a bitmap array?

我目前正在开发一款纸牌配对游戏,我需要从数据库中检索两张图像并将它们添加到位图数组中。 我目前拥有的代码在检索图像时出现错误。 代码是:

val aDatabase = FirebaseStorage.getInstance().getReference("all/$imageID1.jpg")
val sDatabase = FirebaseStorage.getInstance().getReference("all/$imageID2.jpg")

try {
    val localfile = File.createTempFile("tempfile", ".jpg")
    aDatabase.getFile(localfile).addOnSuccessListener {
        val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
        bitmapArray.add(bitmap)
    }.addOnFailureListener {
        Log.w("myapplication", "ERROR RETRIEVING IMAGE")
        Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
    }
} catch (e: Exception) {
    e.printStackTrace()
}

try {
    val localfile = File.createTempFile("tempfile1", ".jpg")
    sDatabase.getFile(localfile).addOnSuccessListener {
        val bitmap = BitmapFactory.decodeFile(localfile.absolutePath)
        bitmapArray.add(bitmap)
    }.addOnFailureListener {
        Log.w("myapplication", "ERROR RETRIEVING IMAGE")
        Toast.makeText(this, "ERROR RETRIEVING IMAGE", Toast.LENGTH_SHORT).show()
    }
} catch (e: java.lang.Exception) {
    e.printStackTrace()
}


        ///    DUPLICATE
bitmapArray.addAll(bitmapArray);
        ///SHUFFLE
bitmapArray.shuffle()

button1 = findViewById<ImageButton>(R.id.imageButton1)
button2 = findViewById<ImageButton>(R.id.imageButton2)
button3 = findViewById<ImageButton>(R.id.imageButton3)
button4 = findViewById<ImageButton>(R.id.imageButton4)
buttons = listOf<ImageButton>(button1, button2, button3, button4)

buttons.forEachIndexed { index, button ->
   button.setOnClickListener(View.OnClickListener {
      button.setImageBitmap(bitmapArray[index])
            })

当我尝试使用 onClick 将图像添加到 ImageButton 时,它只是给我一个错误,提示 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0。我想要创建的是一个 2x2 的卡片匹配游戏,因此我从 FireBase 存储获取 2 个图像。

到目前为止,我已经尝试了在 stackoverflow 上可以找到的所有内容,但没有解决我的问题。 提前致谢。

您正在从addOnSuccessListener bitmapArray 这是异步发生的。 当您按下按钮时,数组可能不包含给定索引处的条目,这可能是因为下载未完成或因addOnFailureListener中的错误而结束。

您必须正确处理状态并且至少在访问它之前检查bitmapArray 此外,数组中似乎只有两个图像,但有四个按钮试图根据索引进行访问——这总是会导致四个按钮中的两个出现错误。

查看 Firebase 文档和 Firebase 用户界面: https ://firebase.google.com/docs/storage/android/download-files#downloading_images_with_firebaseui

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM