Skip to content

Instantly share code, notes, and snippets.

@oyeraghib
Created July 26, 2022 15:05
Show Gist options
  • Save oyeraghib/a2e0daa8239eb0b8cc46974f958937ba to your computer and use it in GitHub Desktop.
Save oyeraghib/a2e0daa8239eb0b8cc46974f958937ba to your computer and use it in GitHub Desktop.
Firestore Only add if doesn't exists
class AddDeviceFragment : Fragment() {
private var _binding: FragmentAddDeviceBinding? = null
private val binding get() = _binding!!
//firestore instance
private lateinit var firestore: FirebaseFirestore
//auth instance
private lateinit var auth: FirebaseAuth
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentAddDeviceBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Initialising firestore and auth
firestore = FirebaseFirestore.getInstance()
auth = FirebaseAuth.getInstance()
binding.btnAddDevice.setOnClickListener {
val device = binding.etAddDevice.text.toString()
saveInFirestore(device)
}
}
// To fix: Unusual error of the toast being shown/not shown even if readFromFireStore() is false/true.
// Maybe can be some reference issue.
private fun saveInFirestore(device: String) {
//Firestore document reference
val docsRef = firestore.collection("Devices Registered").document(device)
val addDevice: MutableMap<String, String> = HashMap()
addDevice["UID"] = auth.uid!!
addDevice["Device Name"] = device
if (!verifyFirebase()) {
Timber.d("It already exists!!!!")
} else {
docsRef.set(addDevice)
.addOnSuccessListener {
Timber.d("New device saved with name : $device")
Toast.makeText(requireContext(), "New Device Saved", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Toast.makeText(requireContext(), "Not able to save Device", Toast.LENGTH_SHORT)
.show()
Timber.d("Unable to add device")
}
}
}
private fun verifyFirebase(): Boolean {
var valid = true
val device = binding.etAddDevice.text.toString()
val docRef = firestore.collection("Devices Registered").document(device)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Timber.d("Document data is : ${document.data}")
val response = document.getString("Device Name")
Timber.d(response)
if (response == device) {
Timber.d("Device already exists by name : $response")
valid = false
}
} else {
Timber.d("No such doc exists")
}
}
.addOnFailureListener {
Timber.d("Failed with exception : $it")
}
Timber.d("valid : $valid")
return valid
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment