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()
}
}
}
}
Related
I got this in firebase:
private fun uploadToFireBase(imageUri: Uri) {
binding.progressBar.visibility = View.VISIBLE
val fileRef : StorageReference = storageReference.child("${System.currentTimeMillis()}.${getFileExtension(imageUri)}")
fileRef.putFile(imageUri).addOnSuccessListener {
fileRef.downloadUrl.addOnSuccessListener {
binding.progressBar.visibility = View.VISIBLE
val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
binding.HackLocationET.text.toString(), imageUri.toString()
)
val hackathonModelId : String? = root.push().key
root.child("HackathonsUsers").child(firebaseAuth.currentUser!!.uid).child(hackathonModelId.toString()).setValue(hackathonModel)
root.child("AllHackathons").child(hackathonModelId.toString()).setValue(hackathonModel)
Toast.makeText(this, "Hackathon Uploaded Successfully", Toast.LENGTH_SHORT).show()
val intent = Intent(this , MainActivity::class.java)
startActivity(intent)
finish()
}
}.addOnProgressListener {
binding.progressBar.visibility = View.VISIBLE
}.addOnFailureListener{
binding.progressBar.visibility = View.INVISIBLE
binding.postHackBT.visibility= View.VISIBLE
Toast.makeText(this, "Uploading Failed", Toast.LENGTH_SHORT).show()
}
}
private fun getFileExtension(imageUri: Uri): String? {
val cr : ContentResolver = contentResolver
val mime : MimeTypeMap = MimeTypeMap.getSingleton()
return mime.getExtensionFromMimeType(cr.getType(imageUri))
}
how to fix this error and get a link in correct form not in this form (content://com.android.providers.media.documents/document/image%3A428613)?
You're creating your model with:
val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
binding.HackLocationET.text.toString(), imageUri.toString()
)
That last argument is imageUri.toString(), which is the path to the image on your local Android device, and not the download URL that you told Firebase to generate for you.
To get the latter:
fileRef.downloadUrl.addOnSuccessListener { task ->
binding.progressBar.visibility = View.VISIBLE
if (task.isSuccessful) {
val downloadUri = task.result
val hackathonModel = HackathonModel(binding.HackTitleET.text.toString() , binding.HackUrlET.text.toString() ,
binding.HackLocationET.text.toString(), downloadUri.toString()
)
...
Also see the Firebase documentation on getting the download URL after uploading a file.
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
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()
The doWork() method returns the Result before completing the task, resulting in blocking the main thread.
Some of the answers to this question are: To make the thread wait until the task is completed.
I feel there could be a better way to handle it.
class CloudWorker(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
val fireStore = FirebaseFirestore.getInstance()
#SuppressLint("LogNotTimber")
override fun doWork(): Result {
Log.i("thred_dowork"," :"+Thread.currentThread().name)
val appContext = applicationContext
val dataString = inputData.getString(KEY_NOTE_DATA)
val data = Gson().fromJson(dataString, NoteData::class.java)
makeStatusNotification("Uploading Notes", appContext)
Log.i("uri:"," ${data.uri}")
val resolver = appContext.contentResolver
appContext.grantUriPermission(appContext.packageName,
Uri.parse(data.uri),
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
val f = File(data.uri, "profile.jpg")
val picture = BitmapFactory.decodeStream(FileInputStream(f))
// Create a storage reference from our app
val storage = Firebase.storage
// Create a storage reference from our app
val storageRef = storage.reference
val baos = ByteArrayOutputStream()
picture.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val imageDataX: ByteArray = baos.toByteArray()
var pathX = "images/"+System.currentTimeMillis().toString()+".jpg"
val mountainImagesRef = storageRef.child(pathX)
val uploadTask = mountainImagesRef.putBytes(imageDataX)
uploadTask.addOnSuccessListener {
Log.i("sync_","Image uploaded"+ it.metadata!!.path+" : "+it.metadata!!.name)
data.uri= it.metadata!!.path
fireStore.collection("notes")
.add(data)
.addOnSuccessListener {
Log.i("sync_","Sync Succes")
if(isStopped)
Log.i("sync_","Worker Stopped")
else
saveUrl()
}.addOnFailureListener {
Log.i("sync_","Sync Succes")
}
}.addOnFailureListener{
Log.e("sync_","Image not uploaded"+it.toString())
}
Timber.i("sync_data: $dataString")
Log.i("sync_","Called before firestore"+dataString)
return Result.success()
}
private fun saveUrl() {
Log.i("sync_","sleeping for 10 sec. thread_ "+Thread.currentThread().name)
sleep(15000)
if(isStopped)
Log.i("sync_","Worker Stopped")
else
Log.i("sync_","Worker not stopped")
Log.i("sync_","Wake up after 10 sec")
fireStore.collection("employee")
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result!!) {
Log.d("sync_employ", document.id + " => " + document.data)
}
} else {
Log.w("sync_", "Error getting documents.", task.exception)
}
}
}
}
Here I am doing firebase operation.
uploading image to firebase file storage
After successful upload, uploading content to the database.
On successful upload, retrieving some data from the database.
Your suggestions are most welcome here.
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()