首页 > 解决方案 > Firebase 数据库设置值不会更改值

问题描述

首先我是初学者

我正在尝试将一些数据上传到 firebase 及其对象集合,因此我将其转换为 JSON 格式并将其上传为字符串,就像在 SharedPreference 中保存数组一样(我的意思是将数组转换为字符串的想法)

以下是规则:

{
  "rules" :  {
    ".read" : true,
    ".write" :  true
    }
}

这是数据类:

data class Content(
        val books: List<Book>,
        val poems: List<Poem>,
        val proses:List<Prose>

我在这里创建了一个类来使用 firebase 管理所有进程:

class SdDataManager {

    // get database
    private var database: FirebaseDatabase = Firebase.database
    private var content: Content?
    
    companion object {
        private const val TAG = "SdDataManagerTag"
    }

    init {
        content = null
        
        // read data
        val contentReference = database.getReference("content")
        contentReference.addValueEventListener(object : ValueEventListener {

            override fun onDataChange(snapshot: DataSnapshot) {

                val gson = Gson()
                val json: Map<String, Any>? = snapshot.getValue<Map<String, Any>>()


                content = gson.fromJson(json.toString(), Content::class.java)
            }

            override fun onCancelled(error: DatabaseError) {
                Log.d(TAG, "Failed to read data error: " + error.toException())
            }

        })


    }
    
    // this function is only for testing

    fun test() {
        
        // creating content object
        
        // create test bitmap
        val conf = Bitmap.Config.ARGB_8888
        val bitmap = Bitmap.createBitmap(512, 512, conf)
        
        val chapters = listOf(Section("SEC_TITLE", "SEC_BODY"))
        val book = Book("BOOK_TITLE", chapters, bitmap)
        val books = listOf(book)
        val poem = Poem("POEM_TITLE", "POEM_BODY", bitmap)
        val poems = listOf(poem)
        val prose = Prose("PROSE_TITLE", "PROSE_BODY", bitmap)
        val proseList = listOf(prose)

        
        val testContent = Content(books, poems, proseList)
        updateContent(testContent)

    }
    

    fun getContent(): Content? {
        return content
    }

    fun updateContent(newContent: Content) {
        val gson = Gson()
        val json = gson.toJson(newContent)
        
        val contentReference = database.getReference("content")
        contentReference.setValue(json)
    }
}

现在我在这里使用 Junit4 测试这个类:

class SdDataManagerTest {

    private lateinit var sdDataManager: SdDataManager

    @Before
    fun initialize() {
        sdDataManager = SdDataManager()
    }

    @Test
    fun updateContent() {
        sdDataManager.test()
    }
}

当我创建 addOnSuccessListener 它没有调用

标签: androidfirebasekotlinfirebase-realtime-database

解决方案


如果您在下载后创建了数据库,google-services.json 并且在非默认/美国区域中创建了它,则需要在代码中为您的数据指定 URL,如下所示:

private var database: FirebaseDatabase = Firebase.database("URL of your database")

推荐阅读