我的Firebase数据库无法从我的Android Kotlin应用程序写入

时间:2019-08-01 18:16:54

标签: android firebase firebase-realtime-database kotlin

即使从此kotlin代码成功调用了“ setValue”,我也无法写入Firebase数据库:

class InsertActivity : AppCompatActivity() {

    // get the database reference
    private var firebaseDatabase: FirebaseDatabase? = null
    private var databaseReference: DatabaseReference? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_insert)

        firebaseDatabase = FirebaseDatabase.getInstance()
        databaseReference = firebaseDatabase!!.reference.child("traveldeals")


    }



    private fun saveDeal() {
        val title = txtTitle.text.toString().trim()
        val description = txtDescription.text.toString().trim()
        val price = txtPrice.text.toString().trim()

        val travelDeal = TravelDeal(title, description, price, "")

        // save data into firebase
        databaseReference!!.push().setValue(travelDeal)
            .addOnSuccessListener {
                Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()

            }
            .addOnFailureListener { ex : Exception ->
                Log.d("TAG", ex.toString())

            }

    }
}

我已经添加了需要的gradle依赖项,并且还按照指示在firebase控制台中添加了身份验证凭据,我在应用程序中没有看到任何错误,但是没有创建数据库,并且还使数据库可写和可读。 / p>

我看到了:

  

2019-08-01 19:05:23.206 5065-5065 / com.connect.systems.ng.travelmantics I / FirebaseInitProvider:FirebaseApp初始化成功

在我的android studio logcat中。

2 个答案:

答案 0 :(得分:0)

您要先设置值,然后再设置。

从文档中

databaseReference!!.setValue(user)
        .addOnSuccessListener {
            // Write was successful!
            // ...
        }
        .addOnFailureListener {
            // Write failed
            // ...
        }

所以您的代码应类似于:

databaseReference!!.setValue(travelDeal)
            .addOnSuccessListener {
                Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()

            }
            .addOnFailureListener { ex : Exception ->
                Log.d("TAG", ex.toString())

            }

这应该很好。

答案 1 :(得分:0)

我发现我的班级TravelDeal没有被正确设置的问题是这样声明的:

class TravelDeal() {

    var id : String? = null
    var title : String? = null
    var description : String? = null
    var price : String? = null
    var imageUrl : String? = null

    // The this sets the above fields to the constructor parameters
    constructor(title: String, description: String, price: String, imageUrl: String?) : this()

}

然后使用@AnasMehar提供的链接将其更改为:

@IgnoreExtraProperties
class TravelDeal(
    var title: String? = "",
    var description: String? = "",
    var price: String? = "",
    var imageUrl: String? = ""
)