Data is corrupted while storing it into database - android

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()

Related

How to extract the data list from the database in room database

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()

Firebase Storage HTTP Error Code : No content provider

so I'm trying to upload image to Firebase Storage but it gives me this error: HTTP result code exception, code is -1300 and it's because I give no content provider which I think I do, here's the code:
binding.btnUploadPost.setOnClickListener {
if (loggedEmail != null) {
val formatter = SimpleDateFormat("yyyy_MM_dd__HH__mm_ss", Locale.getDefault())
val now = Date()
val fileName = formatter.format(now)
val database = FirebaseFirestore.getInstance()
val storage = FirebaseStorage.getInstance().getReference("posts/$fileName")
storage.putFile(Uri.parse(binding.ivAddPost.resources.toString())).addOnCompleteListener { task ->
if (task.isSuccessful) {
database.collection("posts").document(fileName).set(
hashMapOf(
"postId" to fileName.toString(),
"publisher" to loggedEmail
)
)
Toast.makeText(root.context, "Post Uploaded Successfully!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(binding.btnSelectPost.context, "Error Uploading Post!" + task.exception , Toast.LENGTH_SHORT).show()
}
}
}
}

Send Data From Firestore To Shared Preferences Kotlin in Android Studio

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()
}
}

How to read child of child data from firebase in android / kotlin

I am trying to read data from my firebase realtime database to a TextView. But every time it shows null in TextView. I want to read single user data. I want to read data when user give input.
My Data Structure look like this..
{
"Date": {
"04-10-2019": {
"-LqR-e2UJLJCccqfgGi1":{
address: Dhaka
date: 04-10-2019
name: Mark
phoneNo: 017#######
serialNo: -LqR-e2UJLJCccqfgGi1
type: New
},
},
"05-10-2019": {
"-LqU-e2UJLJCDcqfgGi9":{
address: Dhaka
date: 04-10-2019
name: Tony
phoneNo: 017#######
serialNo: -LqU-e2UJLJCDcqfgGi9
type: OLd
},
}
}
The code that I am trying.
class Info(
val serialNo: String? = "",
val name: String = "",
val address: String = "",
val phoneNo: String = "",
val date: String = "",
var type: String = ""
)
private fun saveInfo() {
// Edit Text Field
val name = editTextName.text.toString().trim()
if (name.isEmpty()) {
editTextName.error = "Please Enter Your Name"
return
}
val address = editTextAddress.text.toString().trim()
if (address.isEmpty()) {
editTextAddress.error = "Please Enter Your Address"
return
}
val phoneNo = editTextPhoneNo.text.toString().trim()
if (phoneNo.isEmpty()) {
editTextPhoneNo.error = "Please Enter Your Phone Number"
return
}
val date = dateText.text.toString().trim()
//Radio Button
var type = ""
when {
checkboxNew.isChecked -> type += "New"
checkboxOld.isChecked -> type += "Old"
radioGroup.checkedRadioButtonId <= 0 -> {
Toast.makeText(applicationContext, "Please Check New or Old", Toast.LENGTH_LONG)
.show()
return
}
}
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
val formatted = current.format(formatter)
val myRef = FirebaseDatabase.getInstance().getReference("Date").child(formatted)
myRef.orderByChild(formatted).startAt("28-09-2019").endAt("31-12-2070")
val patientId = myRef.push().key
val patient = Info(patientId, name, address, phoneNo, date, type)
myRef.child((patientId).toString()).setValue(patient).addOnCompleteListener {
Toast.makeText(applicationContext, "Info saved Successfully", Toast.LENGTH_LONG).show()
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (data in dataSnapshot.children) {
val user = data.child(formatted).value.toString()
dataText.text = user
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
I want to show the data into a textview when the user give input and hit a button.
If you are trying to read the date attribute from the database then change this :
val user = data.child(formatted).value.toString()
Into this:
val user = data.child("date").value.toString()
Inside the child() you need to pass the name of the attribute.

Adding data to the database

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()

Categories

Resources