android - 将数据添加到数据库
问题描述
我正在 Android Studio 上使用 Kotlin 创建一个应用程序。在应用程序中,用户将被允许添加图像、用户名和电话号码以继续进行其他活动。上述信息应保存在应用 Cloud Firestore (Firebase) 中。
但是,在为 firestore 编写函数时,数据不会保存到数据库中
有人可以帮忙吗?
当我构建我的应用程序时,它显示的是:
这是我在 stackoverflow 上的第一篇文章,所以如果您想知道任何其他信息,请告诉我。
伙计们,我将不胜感激。
这是我的代码:
setupBtn.setOnClickListener {
val username: String = setupName.text.toString()
val phoneNumber: String = setupPhoneNumber.text.toString()
if (!TextUtils.isEmpty(username) &&
!TextUtils.isEmpty(phoneNumber)) { //if fields are not empty, proceed. Else,
tell user to fill both fields
setupProgressBar.visibility = View.VISIBLE
val userID = mAuth.currentUser!!.uid // saves user ID
val imagePATH: StorageReference =
storageRef.child("profile_images").child(userID + ".jpg") //store the image
as the user ID
imagePATH.putFile(mainImageURI).addOnCompleteListener {
task ->
if (task.isSuccessful) {
//get the downloadURI of the image and store it
val downloadURI =
task.result.metadata!!.reference!!.downloadUrl.toString()
//A collection stores in the database that has a
1)name .. 2)phone number .. 3)image
val data = HashMap<String, Any>()
data.put("name", username)
data.put("phone number", phoneNumber)
data.put("image", downloadURI)
val docRef =
mFirestore.collection("Users").document(userID).set(data)
docRef.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "User Setting are
updated", Toast.LENGTH_LONG).show()
val intent = Intent(this,
PhotoBlog::class.java)
startActivity(intent)
finish()
} else {
val errorMessage: String? =
task.exception!!.message
Toast.makeText(this, "Database Error:
$errorMessage", Toast.LENGTH_LONG).show()
}
}
} else {
val errorMessage: String? =
task.exception!!.message
Toast.makeText(this, "Image Error:
$errorMessage", Toast.LENGTH_LONG).show()
}
setupProgressBar.visibility = View.INVISIBLE
}
} else {
Toast.makeText(this, "Please, fill both fields",
Toast.LENGTH_LONG).show()
}
}
}
我还导入了所需的库,并定义了一个 firestore 变量
private lateinit var mFirestore: FirebaseFirestore
mFirestore = FirebaseFirestore.getInstance()
解决方案
推荐阅读
- reactjs - 环境变量在生产中不起作用
- html - 由轮廓引起的空白
- android - 从firebase实时数据库中删除项目后,在回收站视图中保持位置不起作用
- mysql - 没有 PHP 的 MySQL 搜索数组
- node.js - 当我在 Iframe 中加载应用程序并点击网络服务器 URL(Hapi JS)时,请求对象中缺少 Cookie
- python - 色相和共享 x 轴不工作 Seaborn facet grid
- r - 多次复制 uniroot 函数
- c# - .net 5 webapi 与 cli
- css - 哪个 CSS 可以在移动响应视图上用较长的文本替换主菜单的文本(1 个符号)?
- php - 如何使用 API REST 在 wordpress 中发布帖子,内容中包含图像(并将其保存在本地),使用 PHP