Android app, putBytes to Firebase not working - android

Im (doing tutorial on YT) trying to put my image to firebase,
As far as I can see, I can't connect to the database, but I don't know where the problem is and what I am doing wrong
but when I try I have something like this in logcat:
2021-11-01 06:57:40.660 32702-32702/pl.edu.pb.mymemory E/CreateActivity: Exception with Firebase storage
com.google.firebase.storage.StorageException: The operation retry limit has been exceeded.
at com.google.firebase.storage.UploadTask.snapStateImpl(UploadTask.java:524)
at com.google.firebase.storage.UploadTask.snapStateImpl(UploadTask.java:50)
at com.google.firebase.storage.StorageTask.snapState(StorageTask.java:343)
at com.google.firebase.storage.StorageTask.getFinalResult(StorageTask.java:453)
at com.google.firebase.storage.StorageTask.getResult(StorageTask.java:273)
at com.google.firebase.storage.StorageTask.getResult(StorageTask.java:41)
There is my function:
private fun saveDataToFirebase() {
val customGameName = etGameName.text.toString()
Log.i(TAG, "Save data to Firebase")
var didEncounteredError = false
val uploadedImageUrls = mutableListOf<String>()
for ((index,photoUri) in chosenImageUris.withIndex()) {
//downgrading the quality of the image
val imageByteArray = getImageByteArray(photoUri)
val filePath = "images/$customGameName/${System.currentTimeMillis()}-${index}.jpg"
val photoReference = storage.reference.child(filePath)
Log.i(TAG, "Trying to upload: ${photoReference}")
//wait until it succeeds or fails
photoReference.putBytes(imageByteArray)
.continueWithTask { photoUploadTask ->
Log.i(TAG, "Uploaded bytes: ${photoUploadTask.result?.bytesTransferred}")
photoReference.downloadUrl
}.addOnCompleteListener { downloadUrlTask ->
if (!downloadUrlTask.isSuccessful) {
Log.e(TAG, "Exception with Firebase storage", downloadUrlTask.exception)
Toast.makeText(this, "Failed to upload image", Toast.LENGTH_SHORT).show()
didEncounteredError = true
return#addOnCompleteListener
}
if(didEncounteredError){
return#addOnCompleteListener
}
val downloadUrl = downloadUrlTask.result.toString()
uploadedImageUrls.add(downloadUrl)
Log.i(TAG, "Finished uploading $photoUri, num uploaded ${uploadedImageUrls.size}")
if(uploadedImageUrls.size == chosenImageUris.size) {
handleAllImagesUploaded(customGameName, uploadedImageUrls)
}
}
}
}
My repository on git

In my case it was wrong date on phone.
Fixing date resolved an issue

Related

How can I upload the sensor data Json file to AWS s3 bucket at specific time using kotlin android studio

I need to send my sensor data collected in a JSON file to the AWS cloud server at a particular time in the day automatically.
Here is the code I am using to upload the file manually
private fun uploadFile() {
val exampleFile = File(applicationContext.filesDir, "light.json")
val randomNumber = (1..999999999999999).random()
try {
val writer = BufferedWriter(FileWriter(exampleFile))
writer.append(jsonArray.toString())
writer.close()
} catch (exception: Exception) {
Log.e("MyAmplifyApp", "Upload failed", exception)
}
Amplify.Storage.uploadFile(
"Light-Sensor/light$randomNumber.json",
exampleFile,
{ result: StorageUploadFileResult ->
Log.i(
"MyAmplifyApp",
"Successfully uploaded: " + result.key
)
Toast.makeText(this, "File has Successfully Uploaded:" , Toast.LENGTH_SHORT).show()
}
) { storageFailure: StorageException? ->
Log.e(
"MyAmplifyApp",
"Upload failed",
storageFailure
)
Toast.makeText(this, "Upload failed", Toast.LENGTH_SHORT).show()
}
}
}

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

Data is corrupted while storing it into database

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

After Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList ") upload codes excute before for iterator's .addOnCompleteListener [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
After Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList ") upload codes excute before for iterator's .addOnCompleteListener lead to var downloadImagesUriList: MutableList<String> = mutableListOf() is empty.
How to solve this problem?
var downloadImagesUriList: MutableList<String> = mutableListOf()
//Upload images button
upload_imgs_button.setOnClickListener {
Log.d(TAG, "uploadImgsPath: $uploadImgsPath");
//Upload images to firebase storage
if (uploadImgsPath != null) {
for (uriForUpload in imagesList) {
val imgNameUUID = UUID.randomUUID().toString()
val withAppendedPath =
Uri.withAppendedPath(uriForUpload, imgNameUUID).toString()
var imgFileRef = uploadImgsPath!!.child(withAppendedPath)
imgFileRef.putFile(uriForUpload)
.continueWithTask {
if (!it.isSuccessful) {
it.exception?.let {
throw it
}
}
imgFileRef.downloadUrl
}.addOnCompleteListener {
if (it.isSuccessful) {
var uriForDownload = it.result.toString()
Log.d(TAG, "uriForDownload:$uriForDownload ");
downloadImagesUriList.add(uriForDownload)
}
}
}
//The process will run here before downloadImagesUriList.add(uriForDownload) was excuted.
//How to solve this problem?
Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList ");
var uploadedImages = UploadedImages(
categoryDesignID, user!!.uid,
downloadImagesUriList, Timestamp.now()
)
//Save uploaded images path info to firestore
firestore.collection("uploadedImages").add(uploadedImages)
.addOnSuccessListener {
Toast.makeText(context, "Upload successful", Toast.LENGTH_LONG)
.show()
}
} else {
Toast.makeText(context,"Please choose a category",Toast.LENGTH_LONG).show()
}
Firebase APIs, like most modern cloud APIs, are asynchronous, since they interact with a (potentially time-consuming) server. Instead of blocking your main thread while the cloud interaction happens, the clients allow your main code to continue, and then call back once the cloud API has completed its work.
In your code that means that the Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList "); runs before the imgFileRef.downloadUrl. This explains why nothing is written to the database by add(uploadedImages): the download URLs haven't been determined yet, because the upload is still in progress.
To solve this problem, all code that requires the download URL of an upload, must be inside the completion listener of that upload.
The simplest way to do this, is to add a new URL each time the upload of that file completes:
for (uriForUpload in imagesList) {
val imgNameUUID = UUID.randomUUID().toString()
val withAppendedPath =
Uri.withAppendedPath(uriForUpload, imgNameUUID).toString()
var imgFileRef = uploadImgsPath!!.child(withAppendedPath)
imgFileRef.putFile(uriForUpload)
.continueWithTask {
if (!it.isSuccessful) {
it.exception?.let {
throw it
}
}
imgFileRef.downloadUrl
}.addOnCompleteListener {
if (it.isSuccessful) {
var uriForDownload = it.result.toString()
Log.d(TAG, "uriForDownload:$uriForDownload ");
downloadImagesUriList.add(uriForDownload)
Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList ");
var uploadedImages = UploadedImages(
categoryDesignID, user!!.uid,
downloadImagesUriList, Timestamp.now()
)
//Save uploaded images path info to firestore
firestore.collection("uploadedImages").add(uploadedImages)
}
}
}
The above will create a new document each time an upload completes. You'll either want to update the same document after each file completes or wait until the last file has uploaded before creating the document. There are many ways to do either, but a simple way is to simply keep a counter of how many files have completed uploading:
var uploadedCount = 0
for (uriForUpload in imagesList) {
...
}.addOnCompleteListener {
if (it.isSuccessful) {
var uriForDownload = it.result.toString()
Log.d(TAG, "uriForDownload:$uriForDownload ");
downloadImagesUriList.add(uriForDownload)
if (uploadedCount++ >= imagesList.size) {
Log.d(TAG, "downloadImgsUriArrayList:$downloadImagesUriList ");
var uploadedImages = UploadedImages(
categoryDesignID, user!!.uid,
downloadImagesUriList, Timestamp.now()
)
//Save uploaded images path info to firestore
firestore.collection("uploadedImages").add(uploadedImages)
}
...
}

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