android - 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 它没有调用
解决方案
如果您在下载后创建了数据库,google-services.json
并且在非默认/美国区域中创建了它,则需要在代码中为您的数据指定 URL,如下所示:
private var database: FirebaseDatabase = Firebase.database("URL of your database")
推荐阅读
- python - USB端口号可以用作客户端服务器模型的端口吗?
- opacity - iText 背景不透明度
- python - 将 pandas 行中的值重新格式化为关联列
- sql - 适当的排名
- sql-server - 允许用户运行预构建的 sql 脚本
- node.js - mongodb - 按顺序计算缺失索引的最有效方法
- database - 访问:创建没有表格的表单
- android - 改变正弦波的幅度以适应 AudioTrack.write(array: FloatArray) 方法
- python - 如何调整图像大小以放入 tf.train.Example
- java - Java Spring-boot 和内存 db H2。db 不在 h2 web 控制台中