我打开列表项,在fetchData()
中获取数据,然后希望通过调用addTarget()
方法来更新当前项(name
和description
)。相反,我创建了一个新的。
问:如何更新当前版本?
class TargetEditFragment : Fragment() {
private var nameEditText: TextInputEditText? = null
private var descriptionEditText: TextInputEditText? = null
private var button: Button? = null
private var databaseReference: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.getString(KEY_TARGET_GUID, "")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_target_add, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
databaseReference = FirebaseDatabase.getInstance().getReference("targets")
setupViews()
fetchData(guid = arguments?.getString(KEY_TARGET_GUID, "") ?: "")
}
private fun setupViews() {
nameEditText = view?.findViewById(R.id.nameEditText)
descriptionEditText = view?.findViewById(R.id.descriptionEditText)
button = view?.findViewById(R.id.addNote)
button?.setOnClickListener { addTarget() }
}
private fun addTarget() {
val name = nameEditText?.text.toString().trim()
val description = descriptionEditText?.text.toString().trim()
if (!TextUtils.isEmpty(name)) {
val id: String = databaseReference?.push()?.key.toString()
val target = Target(guid = id, name = name, description = description)
databaseReference?.child(id)?.setValue(target)
} else Log.d("some", "Enter a name")
}
private fun fetchData(guid: String) {
// Attach a listener to read the data at the target id
databaseReference?.child(guid)?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val data = dataSnapshot.value as HashMap<String, String>
val name = data["name"] ?: ""
val description = data["description"] ?: ""
if (name.isEmpty()) Log.d("some", "nameIsEmpty")
else {
updateViewsContent(name = name, description = description)
}
}
override fun onCancelled(p0: DatabaseError) {
Log.d("some", "onCancelled")
}
})
}
private fun updateViewsContent(name: String?, description: String?) {
nameEditText?.text = Editable.Factory.getInstance().newEditable(name)
descriptionEditText?.text = Editable.Factory.getInstance().newEditable(description)
}
companion object {
fun newInstance(guid: String): TargetEditFragment =
TargetEditFragment().apply {
arguments = Bundle().apply { putString(KEY_TARGET_GUID, guid) }
}
}
}
答案 0 :(得分:1)
无法使用push()
方法更新元素,因为每次调用此方法时,都会生成一个新的唯一键。为了执行更新,您需要知道要更新的元素的键,并在参考中使用它。有关更多信息,请参见以下帖子中的答案: