I'm building an app and I have Firestore server, when specific button pressed I wanted to get data from firebase and save it to the Shared Preference but it's no seem to work.
db.collection("Groups1").document("${codeEntered}").get().addOnSuccessListener {doc ->
if(doc.exists()){
val groups = sharedPreferences.getStringSet("groupCodes", HashSet<String>())
if(groups?.contains(codeEntered)!!){
Toast.makeText(getApplicationContext(), "You're Already in ${codeEntered}.", Toast.LENGTH_LONG).show()
}else {
Toast.makeText(getApplicationContext(), "You Enter ${codeEntered} Group!", Toast.LENGTH_LONG).show()
groups?.plusAssign(codeEntered)
editSharedPreferences.putStringSet("groupCodes", groups)
val data = doc.data.hashCode()
//Add Set The Group In FireStore
db.collection("Groups1").document(codeEntered).get().addOnSuccessListener {doc ->
var data = doc.getData() as MutableMap<String, Any>
data["${sharedPreferences.getInt("mainId", 0)}"] = 0
db.collection("Groups1").document(codeEntered).set(data)
editSharedPreferences.apply()
}
getData(object : MyCallback {
override fun onCallback(value: HashMap<String, Int>) {
listView.adapter = adapterListView(MainActivity.appContext, value, sizeOfListMain, sharedPreferences.getInt("mainColor", 0)) }
})
var codeGroup = sharedPreferences.getStringSet("groupCodes", HashSet<String>()) as HashSet<String>
}
}else{
Toast.makeText(getApplicationContext(), "${codeEntered} is Not Exists.", Toast.LENGTH_LONG).show()
}
}
Related
I am trying to make extract all the data in the database
private fun addRecord(donorDao:DonorDao){
val Id:String=binding?.etDonorId?.text.toString()
val bloodGr=binding?.etDonorBloodgroup?.text.toString()
if(Id.isNotEmpty() && bloodGr.isNotEmpty()) {
var mDonorList:ArrayList<String>?=null
lifecycleScope.launch {
donorDao.fetchAllDonor().collect {
var Donorlist = ArrayList(it)
for(item in Donorlist){
mDonorList?.add(item.id)
}
}
}
if (checkduplicateId(mDonorList!!,Id)) {
lifecycleScope.launch {
donorDao.insert(DonorEntity(id = binding?.etDonorId?.text.toString(), bloodGroup = bloodGr))
Toast.makeText(
applicationContext,
"Record saved successfully",
Toast.LENGTH_SHORT
).show()
}
}else {
Toast.makeText(applicationContext, "Duplicate Id!!", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this,"input is empty",Toast.LENGTH_SHORT).show()
}
}
private fun checkduplicateId(mDonorList:ArrayList<String>,Id:String):Boolean{
var i=true
for(item in mDonorList!!){
if(item==Id){
i=false
break
}
i=true
}
return i
}
but in this code my Donor List is null I do not know where I am going wrong
Is there any other way so that I can extract all the data in database in the array list?
please help me
When you write mDonorList?.add(item.id) it's equivalent to writing
if(mDonorList != null){
mDonorList.add(item.id)
}
and in your case, you initialized mDonorList to null.
You should initialize it with var mDonorList : ArrayList<String> = emptyList()
As creating a form that stored the candidate's basic info along with a pic, as I click on upload btn data which is entered in edit text does not match data stored in firebase.
upload activity
binding.btnUpload.setOnClickListener {
showProgressBar()
val name= binding.etName.toString()
val fathers_name =binding.etFatherName.toString()
val gender=binding.etGender.toString()
val dob=binding.etDob.toString()
val time_place = binding.etTimePlace.toString()
val qualification = binding.etQualification.toString()
val job = binding.etJob.toString()
val Height = binding.etHeight.toString()
val fathers_qualification = binding.etFatherQualification.toString()
val requirement = binding.etRequirement.toString()
val address = binding.etAddress.toString()
val contact=binding.etContact.toString()
// val imageUrl = imageUri.toString()
val candidate= Candidates(name,fathers_name,gender,dob,time_place,
qualification,job,Height,fathers_qualification,requirement,address, contact)
database.child( System.currentTimeMillis().toString()).setValue(candidate).addOnCompleteListener{
if (it.isSuccessful){
uploadProfilePic()
}else{
hideProgressBar()
Toast.makeText(this, "Failed to upload profile", Toast.LENGTH_SHORT).show()
}
Toast.makeText(this, "Successfully saved", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
}
}
}
private fun uploadProfilePic() {
storageRef= FirebaseStorage.getInstance().getReference("candidates")
storageRef.putFile(imageUri).addOnSuccessListener {
Toast.makeText(this, "profile picture uploaded", Toast.LENGTH_SHORT).show()
hideProgressBar()
}.addOnFailureListener {
hideProgressBar()
Toast.makeText(this, "failed to upload the profile pic", Toast.LENGTH_SHORT).show()
}
}
As entered basic details, but it showing some wired data into database.
When you call this:
val name= binding.etName.toString()
The name variable becomes the string representation of the EditText object itself, not of the text value that the user entered.
To get the actual value, use
val name = binding.etName.getText().toString()
I want to retrieve specific child values like (phonenumber, firstname, familyname) from Firebase real time database
but there is a unique key for each user
and this is the tree:
I've tried this:
var loginRef = rootRef.child("users").orderByChild("phoneNumber").equalTo(phone).addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get data object and use the values to update the UI
val phoneNumber = dataSnapshot.getValue<User>()!!.phoneNumber
// ...
Toast.makeText(applicationContext, "phone number is: $phoneNumber", Toast.LENGTH_LONG).show()
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Data failed, log a message
Log.w(TAG, "LoginData:onCancelled", databaseError.toException())
// ...
Toast.makeText(applicationContext, "error", Toast.LENGTH_LONG).show()
}
})
and I have a simple model called User to handle the data (I know the passwords should be hashed here)
#IgnoreExtraProperties
data class User(
var firstName: String? = "",
var fatherName: String? = "",
var familyName: String? = "",
var phoneNumber: String? = "",
var password: String? = ""
) {
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
"firstName" to firstName,
"fatherName" to fatherName,
"familyName" to familyName,
"phoneNumber" to phoneNumber,
"password" to password
)
}
}
but dataSnapshot.getValue<User>()!!.phoneNumber will never work, since the first node retrieved in this query is the unique key
what I need is something like dataSnapshot.child("unique-key/phoneNumber").value for each child i want to use, but a way easier and more efficient than making .addChildEventListener for each node
Let's firstly give some notes one the code:
first thing you need to be aware of is here:
dataSnapshot.getValue<User>()!!.phoneNumber
as it might be null if phoneNumber doesn't exist and will throw an error.
secondly, assuming you made some null handling it will still retrieve you empty string, because what you sent to model is just the unique key, and of course you can't handle it with this model.
The easiest way to solve this and get the children of retrieved node is by using for loop according to this solution: https://stackoverflow.com/a/38652274/10324295
you need to make for loop puts each item into an array list, try this code:
val userList: MutableList<User?> = ArrayList()
var loginRef = rootRef.child("users").orderByChild("phoneNumber").equalTo(phone).addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
userList.clear()
for (userSnapshot in dataSnapshot.children) {
val user: User? = userSnapshot.getValue(User::class.java)
userList.add(user)
// Get Data object and use the values to update the UI
// ...
Toast.makeText(applicationContext, "hi: ${user!!.phoneNumber}", Toast.LENGTH_LONG).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Data failed, log a message
Log.w(TAG, "LoginData:onCancelled", databaseError.toException())
// ...
Toast.makeText(applicationContext, "error", Toast.LENGTH_LONG).show()
}
})
var loginRef = rootRef.child("users").orderByChild("phoneNumber").equalTo(phone).addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// retreive all children firstly by foreach
dataSnapshot.children.forEach { data ->
val userModel = data.getValue(User::class.java)
val phoneNumber = userModel!!.phoneNumber
Toast.makeText(applicationContext, "phone number is: $phoneNumber",
Toast.LENGTH_LONG).show()
}
// ...
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Data failed, log a message
Log.w(TAG, "LoginData:onCancelled", databaseError.toException())
// ...
Toast.makeText(applicationContext, "error",
Toast.LENGTH_LONG).show()
}
})
I'd like a better way to loop through the keyList and if a key starts with the one of the comparator to grab that comparator string and add it to a Map as a header like so MutableMap>..the list being all the key items that match the comparator..
keysList: List<String>
val comparators = listOf("error", "customer", "custom", "feature")
So far I am doing it this way
private fun addToMap(key: String, attributeMap: MutableMap<String, MutableList<String>>) {
val list: MutableList<String> = attributeMap[getHeader(key)] ?: mutableListOf()
list.add(key)
attributeMap[getHeader(key)] = list
}
private fun getHeader(key: String): String {
val compareMap = mapOf("error" to "Error Attributes", "customer" to "Customer Attributes",
"custom" to "Customer Attributes", "feature" to "Feature Attributes", "request.header" to "Request Header Attributes",
"request.parameter" to "Request Parameter Attributes", "request" to "Other Request Attributes")
val defaultKeys = listOf("error.expected", "error.class", "error.message", "host", "httpResponseCode", "transactionName", "transactionUiName") // contains
for ((k, v) in compareMap) {
return if (key.startsWith(k)) {
v
} else if (key in defaultKeys) {
"Error Attributes"
} else {
"Custom Attributes"
}
}
return "Custom Attributes"
}
You could use the .any function like this:
if (comparators.any { key.startsWith(it) })
// add to map
I'm creating an app using Kotlin on Android Studio.
In the app, users will be allowed to add an image, username, and a phone number
to proceed to other activities. The mentioned info should be saved in the app Cloud Firestore (Firebase).
However, while coding the functions for firestore, data is not saved to the database
Can anyone help please?
When I built my app, this is what it showed:
Open the picture
This is my first post on stackoverflow, so let me know if you want to know any addtional infos.
I would appreciate any help from you, guys.
This is my code:
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()
}
}
}
I also imported the needed libraries, and defined a firestore variable
private lateinit var mFirestore: FirebaseFirestore
mFirestore = FirebaseFirestore.getInstance()