I'm having a hard time getting an image URL from firebase storage, I got the photo URL from the database, but as I know, Glide can't get a picture from the link like this: com.google.firebase.storage.UploadTask#62873ce
Here are my Storage and database references:
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (UploadTask.TaskSnapshot) -> Unit) {
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
mStorage.child("users/$uid/photo").downloadUrl.addOnCompleteListener { task ->
if (it.isSuccessful) {
onSuccess(it.result!!)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
private fun DatabaseReference.updateUserPhoto(uid: String, photoUrl: String,
onSuccess: () -> Unit){
child("users/$uid/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
here is the function:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) {
val uid = mAuth.currentUser!!.uid
mStorage.uploadUserPhoto(uid, mImageUri) {
val photoUrl = it.task.toString()
mDatabase.updateUserPhoto(uid, photoUrl) {
mUser = mUser.copy(photo = photoUrl)
profile_image.loadUserPhoto(mUser.photo)
}
}
}
}
I tried changing
val photoUrl = it.task.toString()
to
val photoUrl = it.downloadUrl.toString()
but it highlights 'downloadUrl' as unresolved reference
Full code:
package com.example.homeactivity.activities
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.example.homeactivity.R
import com.example.homeactivity.models.User
import com.example.homeactivity.views.PasswordDialog
import com.google.firebase.auth.AuthCredential
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import kotlinx.android.synthetic.main.activity_edit_profile.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class EditProfileActivity : AppCompatActivity(), PasswordDialog.Listener {
private lateinit var mImageUri: Uri
private lateinit var mStorage: StorageReference
private val TAG = "EditProfileActivity"
private lateinit var mUser: com.example.homeactivity.models.User
private lateinit var mAuth: FirebaseAuth
private lateinit var mDatabase: DatabaseReference
private lateinit var mPendingUser: com.example.homeactivity.models.User
private val TAKE_PICTURE_REQUEST_CODE = 1
val simpleDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_profile)
Log.d(TAG, "onCreate")
close_image.setOnClickListener { finish() }
save_image.setOnClickListener { updateProfile() }
change_photo_text.setOnClickListener { takeCameraPicture() }
mAuth = FirebaseAuth.getInstance()
mDatabase = FirebaseDatabase.getInstance().reference
mStorage = FirebaseStorage.getInstance().reference
mDatabase.child("users").child(mAuth.currentUser!!.uid)
.addListenerForSingleValueEvent(ValueEventListenerAdapter {
mUser = it.getValue(com.example.homeactivity.models.User::class.java)!!
name_input.setText(mUser.name, TextView.BufferType.EDITABLE)
username_input.setText(mUser.username, TextView.BufferType.EDITABLE)
website_input.setText(mUser.website, TextView.BufferType.EDITABLE)
bio_input.setText(mUser.bio, TextView.BufferType.EDITABLE)
email_input.setText(mUser.email, TextView.BufferType.EDITABLE)
phone_input.setText(mUser.phone?.toString(), TextView.BufferType.EDITABLE)
profile_image.loadUserPhoto(mUser.photo)
})
}
private fun takeCameraPicture() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(packageManager) != null) {
val imageFile = createImageFile()
mImageUri = FileProvider.getUriForFile(
this,
"com.example.homeactivity.fileprovider",
imageFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri)
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE)
}
}
private fun createImageFile(): File {
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${simpleDateFormat.format(Date())}_",
".jpg",
storageDir
)
}
#SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) {
val uid = mAuth.currentUser!!.uid
mStorage.uploadUserPhoto(uid, mImageUri) {
val photoUrl = it.task.toString()
mDatabase.updateUserPhoto(uid, photoUrl) {
mUser = mUser.copy(photo = photoUrl)
profile_image.loadUserPhoto(mUser.photo)
}
}
}
}
private fun updateProfile() {
mPendingUser = readInputs()
val error = validate(mPendingUser)
if (error == null) {
if (mPendingUser.email == mUser.email) {
updateUser(mPendingUser)
} else {
PasswordDialog().show(supportFragmentManager, "password_dialog")
}
} else {
showToast(error)
}
}
private fun readInputs(): User {
return User(
name = name_input.text.toString(),
username = username_input.text.toString(),
email = email_input.text.toString(),
website = website_input.text.toStringOrNull(),
bio = bio_input.text.toStringOrNull(),
phone = phone_input.text.toStringOrNull()
)
}
override fun onPasswordConfirm(password: String) {
if (password.isNotEmpty()) {
val credential = EmailAuthProvider.getCredential(mUser.email, password)
mAuth.currentUser!!.reauthenticate(credential) {
mAuth.currentUser!!.updateEmail(mPendingUser.email) {
updateUser(mPendingUser)
}
}
} else {
showToast("You must enter your password")
}
}
private fun updateUser(user: com.example.homeactivity.models.User) {
val updatesMap = mutableMapOf<String, Any?>()
if (user.name != mUser.name) updatesMap["name"] = user.name
if (user.username != mUser.username) updatesMap["username"] = user.username
if (user.website != mUser.website) updatesMap["website"] = user.website
if (user.bio != mUser.bio) updatesMap["bio"] = user.bio
if (user.email != mUser.email) updatesMap["email"] = user.email
if (user.phone != mUser.phone) updatesMap["phone"] = user.phone
mDatabase.updateUser(mAuth.currentUser!!.uid, updatesMap) {
showToast("Profile saved")
finish()
}
}
private fun validate(user: com.example.homeactivity.models.User): String? =
when {
user.name.isEmpty() -> "Please enter name"
user.username.isEmpty() -> "Please enter username"
user.email.isEmpty() -> "Please enter email"
else -> null
}
private fun FirebaseUser.updateEmail(email: String, onSuccess: () -> Unit) {
updateEmail(email).addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (UploadTask.TaskSnapshot) -> Unit) {
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
mStorage.child("users/$uid/photo").downloadUrl.addOnCompleteListener { task ->
if (it.isSuccessful) {
onSuccess(it.result!!)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
private fun DatabaseReference.updateUserPhoto(uid: String, photoUrl: String,
onSuccess: () -> Unit){
child("users/$uid/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun DatabaseReference.updateUser(
uid: String, updates: Map<String, Any?>,
onSuccess: () -> Unit
) {
child("users").child(uid).updateChildren(updates)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun FirebaseUser.reauthenticate(credential: AuthCredential, onSuccess: () -> Unit) {
reauthenticate(credential).addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
}
Change your uploadUserPhoto method like this
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (String) -> Unit) {
val uTask = mStorage.child("users/$uid/photo").putFile(mImageUri)
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { task ->
mStorage.child("users/$uid/photo").downloadUrl
}.addOnCompleteListener{
if (it.isSuccessful && it.result != null) {
onSuccess(it.result!!.toString)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
In your onActivityResult use url like
val photoUrl = it
Related
I am trying to get a users profile pic to be displayed beside their booking on a card in my recyclerview. The profile pic is displaying in my nav drawer, a default one for non-google users, or the profile pic of the Google user. However imageUri appears empty when I call it and the images are not being stored in my firebase storage bucket. I have linked my firebase and implemented the relevant SDK.
Here is my model.
#Parcelize
data class BookModel(
// var id : Long = 0,
var uid: String? = "",
var name: String = "N/A",
var phoneNumber: String = "N/A",
var email: String? = "N/A",
var date: String = "",
var bike: Int = 0,
var profilepic: String = "",
/*var lat: Double = 0.0,
var longitude: Double = 0.0,
var zoom: Float = 0f,*/
var pickup: String = "",
var dropoff: String = "",
var price: Double = 20.0,
/*var amount: Int = 0*/
) : Parcelable
{
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
// "id" to id,
"uid" to uid,
"name" to name,
"phoneNumber" to phoneNumber,
"email" to email,
"date" to date,
"bike" to bike,
"profilepic" to profilepic,
"pickup" to pickup,
"dropoff" to dropoff,
"price" to price
)
}
}
#Parcelize
data class Location(
var lat: Double = 0.0,
var longitude: Double = 0.0,
var zoom: Float = 0f,
var depot: String = "Waterford"
) : Parcelable
Here is my FirebaseImageManager
package com.wit.mad2bikeshop.firebase
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.utils.customTransformation
import timber.log.Timber
import java.io.ByteArrayOutputStream
import com.squareup.picasso.Target
object FirebaseImageManager {
var storage = FirebaseStorage.getInstance().reference
var imageUri = MutableLiveData<Uri>()
fun checkStorageForExistingProfilePic(userid: String) {
val imageRef = storage.child("photos").child("${userid}.jpg")
val defaultImageRef = storage.child("ic_book_nav_header.png")
imageRef.metadata.addOnSuccessListener { //File Exists
imageRef.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
//File Doesn't Exist
}.addOnFailureListener {
imageUri.value = Uri.EMPTY
}
}
fun uploadImageToFirebase(userid: String, bitmap: Bitmap, updating : Boolean) {
// Get the data from an ImageView as bytes
val imageRef = storage.child("photos").child("${userid}.jpg")
//val bitmap = (imageView as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
lateinit var uploadTask: UploadTask
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
imageRef.metadata.addOnSuccessListener { //File Exists
if(updating) // Update existing Image
{
uploadTask = imageRef.putBytes(data)
uploadTask.addOnSuccessListener { ut ->
ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
}
}
}.addOnFailureListener { //File Doesn't Exist
uploadTask = imageRef.putBytes(data)
uploadTask.addOnSuccessListener { ut ->
ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
}
}
}
fun updateUserImage(userid: String, imageUri : Uri?, imageView: ImageView, updating : Boolean) {
Picasso.get().load(imageUri)
.resize(200, 200)
.transform(customTransformation())
.memoryPolicy(MemoryPolicy.NO_CACHE)
.centerCrop()
.into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?,
from: Picasso.LoadedFrom?
) {
Timber.i("DX onBitmapLoaded $bitmap")
uploadImageToFirebase(userid, bitmap!!,updating)
imageView.setImageBitmap(bitmap)
}
override fun onBitmapFailed(e: java.lang.Exception?,
errorDrawable: Drawable?) {
Timber.i("DX onBitmapFailed $e")
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
})
}
fun updateDefaultImage(userid: String, resource: Int, imageView: ImageView) {
Picasso.get().load(resource)
.into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?,
from: Picasso.LoadedFrom?
) {
Timber.i("DX onBitmapLoaded $bitmap")
uploadImageToFirebase(userid, bitmap!!,false)
imageView.setImageBitmap(bitmap)
}
override fun onBitmapFailed(e: java.lang.Exception?,
errorDrawable: Drawable?) {
Timber.i("DX onBitmapFailed $e")
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
})
}
}
My FirebaseAuthManager...
package com.wit.mad2bikeshop.firebase
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.wit.mad2bikeshop.R
import timber.log.Timber
class FirebaseAuthManager(application: Application) {
private var application: Application? = null
var firebaseAuth: FirebaseAuth? = null
var liveFirebaseUser = MutableLiveData<FirebaseUser>()
var loggedOut = MutableLiveData<Boolean>()
var errorStatus = MutableLiveData<Boolean>()
var googleSignInClient = MutableLiveData<GoogleSignInClient>()
init {
this.application = application
firebaseAuth = FirebaseAuth.getInstance()
if (firebaseAuth!!.currentUser != null) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
loggedOut.postValue(false)
errorStatus.postValue(false)
FirebaseImageManager.checkStorageForExistingProfilePic(
firebaseAuth!!.currentUser!!.uid)
}
configureGoogleSignIn()
}
fun login(email: String?, password: String?) {
firebaseAuth!!.signInWithEmailAndPassword(email!!, password!!)
.addOnCompleteListener(application!!.mainExecutor, { task ->
if (task.isSuccessful) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
errorStatus.postValue(false)
} else {
Timber.i("Login Failure: $task.exception!!.message")
errorStatus.postValue(true)
}
})
}
fun register(email: String?, password: String?) {
firebaseAuth!!.createUserWithEmailAndPassword(email!!, password!!)
.addOnCompleteListener(application!!.mainExecutor, { task ->
if (task.isSuccessful) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
errorStatus.postValue(false)
} else {
Timber.i("Registration Failure: $task.exception!!.message")
errorStatus.postValue(true)
}
})
}
fun logOut() {
firebaseAuth!!.signOut()
Timber.i( "firebaseAuth Signed out")
googleSignInClient.value!!.signOut()
Timber.i( "googleSignInClient Signed out")
loggedOut.postValue(true)
errorStatus.postValue(false)
}
private fun configureGoogleSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(application!!.getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient.value = GoogleSignIn.getClient(application!!.applicationContext,gso)
}
fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Timber.i( "DonationX firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
firebaseAuth!!.signInWithCredential(credential)
.addOnCompleteListener(application!!.mainExecutor) { task ->
if (task.isSuccessful) {
// Sign in success, update with the signed-in user's information
Timber.i( "signInWithCredential:success")
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
} else {
// If sign in fails, display a message to the user.
Timber.i( "signInWithCredential:failure $task.exception")
errorStatus.postValue(true)
}
}
}
}
My Home activity
package com.wit.mad2bikeshop.ui.home
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.*
import com.google.firebase.auth.FirebaseUser
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.R
import com.wit.mad2bikeshop.databinding.HomeBinding
import com.wit.mad2bikeshop.databinding.NavHeaderBinding
import com.wit.mad2bikeshop.firebase.FirebaseImageManager
import com.wit.mad2bikeshop.ui.auth.LoggedInViewModel
import com.wit.mad2bikeshop.ui.auth.Login
import com.wit.mad2bikeshop.utils.customTransformation
import timber.log.Timber
class Home : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var homeBinding: HomeBinding
private lateinit var navHeaderBinding: NavHeaderBinding
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var loggedInViewModel: LoggedInViewModel
private lateinit var headerView : View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
homeBinding = HomeBinding.inflate(layoutInflater)
setContentView(homeBinding.root)
drawerLayout = homeBinding.drawerLayout
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.bookFragment, R.id.bookingListFragment
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
val navView = homeBinding.navView
navView.setupWithNavController(navController)
initNavHeader()
}
public override fun onStart() {
super.onStart()
loggedInViewModel = ViewModelProvider(this).get(LoggedInViewModel::class.java)
loggedInViewModel.liveFirebaseUser.observe(this, Observer { firebaseUser ->
if (firebaseUser != null)
updateNavHeader(firebaseUser)
})
loggedInViewModel.loggedOut.observe(this, Observer { loggedout ->
if (loggedout) {
startActivity(Intent(this, Login::class.java))
}
})
}
private fun initNavHeader() {
Timber.i("DX Init Nav Header")
headerView = homeBinding.navView.getHeaderView(0)
navHeaderBinding = NavHeaderBinding.bind(headerView)
}
private fun updateNavHeader(currentUser: FirebaseUser) {
FirebaseImageManager.imageUri.observe(this, { result ->
if(result == Uri.EMPTY) {
Timber.i("DX NO Existing imageUri")
if (currentUser.photoUrl != null) {
//if you're a google user
FirebaseImageManager.updateUserImage(
currentUser.uid,
currentUser.photoUrl,
navHeaderBinding.navHeaderImage,
false)
}
else
{
Timber.i("DX Loading Existing Default imageUri")
FirebaseImageManager.updateDefaultImage(
currentUser.uid,
R.drawable.ic_book_nav_header,
navHeaderBinding.navHeaderImage)
}
}
else // load existing image from firebase
{
Timber.i("DX Loading Existing imageUri")
FirebaseImageManager.updateUserImage(
currentUser.uid,
FirebaseImageManager.imageUri.value,
navHeaderBinding.navHeaderImage, false)
}
})
navHeaderBinding.navHeaderEmail.text = currentUser.email
if(currentUser.displayName != null)
navHeaderBinding.navHeaderName.text = currentUser.displayName
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
fun signOut(item: MenuItem) {
loggedInViewModel.logOut()
//Launch Login activity and clear the back stack to stop navigating back to the Home activity
val intent = Intent(this, Login::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
My BookViewModel
package com.wit.mad2bikeshop.ui.book
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseUser
import com.wit.mad2bikeshop.firebase.FirebaseDBManager
import com.wit.mad2bikeshop.firebase.FirebaseImageManager
import com.wit.mad2bikeshop.model.BookManager
import com.wit.mad2bikeshop.model.BookModel
class BookViewModel : ViewModel() {
private val status = MutableLiveData<Boolean>()
val observableStatus: LiveData<Boolean>
get() = status
fun addBook(firebaseUser: MutableLiveData<FirebaseUser>,
booking: BookModel) {
status.value = try {
booking.profilepic = FirebaseImageManager.imageUri.value.toString()
FirebaseDBManager.create(firebaseUser,booking)
true
} catch (e: IllegalArgumentException) {
false
}
}
// fun updateBook(booking: BookModel){
// status.value = try {
// BookManager.update(booking)
// true
// } catch (e: IllegalArgumentException) {
// false
// }
// }
}
My BookAdapter
package com.wit.mad2bikeshop.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.R
import com.wit.mad2bikeshop.databinding.CardBookBinding
import com.wit.mad2bikeshop.model.BookModel
import com.wit.mad2bikeshop.utils.customTransformation
interface BookListener {
// fun onDeleteBooking(booking: BookModel)
// fun onUpdateBooking(booking: BookModel)
fun onBookingClick(booking: BookModel)
}
class BookAdapter constructor(
private var bookings: ArrayList<BookModel>,
private val listener: BookListener,
private val readOnly: Boolean)
: RecyclerView.Adapter<BookAdapter.MainHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHolder {
val binding = CardBookBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return MainHolder(binding, readOnly)
}
override fun onBindViewHolder(holder: MainHolder, position: Int) {
val booking = bookings[holder.adapterPosition]
holder.bind(booking, listener)
}
fun removeAt(position: Int) {
bookings.removeAt(position)
notifyItemRemoved(position)
}
override fun getItemCount(): Int = bookings.size
inner class MainHolder(val binding: CardBookBinding,private val readOnly : Boolean) :
RecyclerView.ViewHolder(binding.root) {
val readOnlyRow = readOnly
fun bind(booking: BookModel, listener: BookListener) {
binding.root.tag = booking
binding.booking = booking
binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round)
Picasso.get().load(booking.profilepic.toUri())
.resize(200, 200)
.transform(customTransformation())
.centerCrop()
.into(binding.imageIcon)
//
// binding.name.text = booking.name
// binding.phoneNumber.text = booking.phoneNumber
// binding.date.text = booking.date
binding.root.setOnClickListener { listener.onBookingClick(booking) }
// binding.buttonDelete.setOnClickListener { listener.onDeleteBooking(booking) }
// binding.buttonUpdate.setOnClickListener { listener.onUpdateBooking(booking) }
binding.executePendingBindings()
/* binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round)*/
}
}
}
I believe the problem stems from the (FirebaseImageManager.imageUri.value.toString()) on my BookAdapter, as if I run a Timber.I statement it doesn't return anything at all. If I run Timber.i(FirebaseImageManager.imageUri.value.toString()+ "test"), it only returns test.
Here is a link to the full project https://github.com/foxxxxxxx7/MAD2bikeshop
Apologies if I wasn't clear enough, I am a novice.
I figured it out, I had to modify my rules on the firebase storage.
I've recently started programming in Kotlin and cannot seem to add a profile picture to a user when registering it.
According to the code here, I can access to the gallery and retrieve the image information. The picture will appear on screen, but after registering the user the image url will not appear anywhere.
class RegisterUser : AppCompatActivity() {
private val database = FirebaseDatabase.getInstance()
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
private val UserCreation = database.getReference("Usuarios")
private val pickImage = 100
private var imageUri: Uri? = null
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_user)
Goback.setOnClickListener {
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
}
RegisterConfirm.setOnClickListener {
val SetUser = SetUser.text.toString()
val SetPass = setPass.text.toString()
val SetEmail = SetEmail.text.toString()
if (SetUser.isEmpty() && SetPass.isEmpty() && SetEmail.isEmpty()) {
Toast.makeText(this, "Faltan Campos", Toast.LENGTH_SHORT).show()
} else {
RegisterUserv2(SetEmail, SetPass, SetUser)
}
}
selectPP.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, pickImage)
}
}
var selectedPhotoUri: Uri? = null
//guardar la foto de perfil
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == pickImage) {
val selectedPhotoUri = data?.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
userimg.setBackgroundDrawable(bitmapDrawable)
}
}
private fun RegisterUserv2(email: String, password: String, user: String) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
uploadimage()
UltrasaveUsuario(Usuarios(auth.currentUser!!.uid, user, password, email))
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
} else {
Toast.makeText(this, "Registro ERROR", Toast.LENGTH_LONG).show()
}
}
}
private fun UltrasaveUsuario(usuario: Usuarios) {
val mensajeFirebase = UserCreation.push()
usuario.id = mensajeFirebase.key ?: ""
mensajeFirebase.setValue(usuario)
}
private fun uploadimage(imageurl: String){
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename/")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener{
}
}
}
}
Since you are using firebase I will show you how to save firebase storage.
private fun uploadImage() {
if (mSelectedImageFileUri != null) {
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.putFile(mSelectedImageFileUri!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { url ->
}
}.addOnFailureListener {
//error
}
} else {
}
}
then you will take this picture using the user id to take .
firebase>storage to view the image
getImage
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.downloadUrl.addOnSuccessListener {
Picasso.get().load(it).into(globalprofileImage)
}
Build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
https://www.youtube.com/watch?v=nNYLQcmB7AU&t=449s&ab_channel=SmallAcademy
Here I'm trying to upload an image from the local storage to the firebase storage.
I'm uploading the image using its URI
package com.example.demochat
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.storage.FirebaseStorage
import java.util.*
class RegisterActivity : AppCompatActivity() {
private lateinit var username: EditText
private lateinit var email: EditText
private lateinit var password: EditText
private lateinit var register: Button
private lateinit var haveAccount: TextView
private lateinit var imageInsert: Button
private lateinit var imageView: ImageView
private val tag: String = "RegisterActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
username = findViewById(R.id.editTextUsername)
email = findViewById(R.id.editTextTextEmailAddress)
password = findViewById(R.id.editTextTextPassword)
register = findViewById(R.id.buttonRegister)
haveAccount = findViewById(R.id.textViewAlready_have_an_account)
imageInsert = findViewById(R.id.buttonInsertImage)
imageView = findViewById(R.id.imageViewImageInsert)
imageInsert.setOnClickListener {
selectImage()
}
register.setOnClickListener {
performRegister()
}
haveAccount.setOnClickListener {
val intent = Intent(this#RegisterActivity, LoginActivity::class.java)
startActivity(intent)
}
}
private var selectedPhotoUri: Uri? = null
private fun selectImage() {
Log.d(tag, "clicked image button")
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, 100)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == RESULT_OK && data != null && data.data != null) {
Toast.makeText(this#RegisterActivity, "clicked image selected", Toast.LENGTH_SHORT)
.show()
val selectedPhotoUri = data.data
Toast.makeText(this#RegisterActivity, "$selectedPhotoUri", Toast.LENGTH_SHORT).show()
imageView.setImageURI(selectedPhotoUri)
}
}
private fun performRegister() {
if (email.text.isEmpty() || password.text.isEmpty()) {
Toast.makeText(this, "Fill the above details", Toast.LENGTH_SHORT).show()
return
}
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email.text.toString(), password.text.toString())
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
Log.d(tag, "uid = ${it.result?.user?.uid}")
uploadImageToFirebase()
}
.addOnFailureListener {
Toast.makeText(this, "${it.message}", Toast.LENGTH_SHORT).show()
Log.d(tag, "${it.message}")
}
}
private fun uploadImageToFirebase() {
if (selectedPhotoUri == null) return
val fileName = UUID.randomUUID().toString() + ".jpg"
val refStorage = FirebaseStorage.getInstance().reference.child("/images/$fileName")
refStorage.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
Log.d(tag, "image uploaded")
}
.addOnFailureListener {
Log.d("RegisterActivity", "${it.message}")
}
}
}
following is the rules for the firebase stroage
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
firebase authentication part is working fine, users are added successfully. But I'm unable to upload an image. I have included internet permissions in the manifest file.
And I'm not getting any error message
So, please help
Here:
val selectedPhotoUri = data.data
you are not reassigning the global property selectedPhotoUri, but creating a new one.
Then, here:
if (selectedPhotoUri == null) return
you are checking with the global property which is always null.
I have integrated mesibo chat and tried to integrate the mesibo push-notification but not receiving the notification. I had set up all the things related push notification and already success integrate with the backend also.
Not sure why i can't receive notification from mesibo related new chat and new call.
This is my code:
package com.project.bucynapp.ui.message
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.mesibo.api.Mesibo.*
import com.mesibo.calls.api.MesiboCall
import com.project.bucynapp.R
import com.project.bucynapp.models.*
import com.project.bucynapp.ui.message.adapter.ChatListAdapter
import com.project.bucynapp.ui.message.presenter.ChatListPresenter
import com.project.bucynapp.ui.message.view.ChatListView
import com.project.bucynapp.utils.*
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_chat_list.*
import kotlinx.android.synthetic.main.app_bar.toolbar
import kotlinx.android.synthetic.main.app_bar_chat_list.*
import kotlinx.android.synthetic.main.loading_view.*
class ChatListActivity : AppCompatActivity(), View.OnClickListener, ChatListView,
MessageListener, ConnectionListener, SyncListener {
private lateinit var presenter: ChatListPresenter
private lateinit var chatListAdapter: ChatListAdapter
private var chatList: MutableList<ChatModel> = mutableListOf()
private val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
private lateinit var readSession: ReadDbSession
private var userMesibo: MesiboAccountData? = null
var userProfile: UserProfile? = null
private var imageProfile: String? = null
private var nameProfile: String? = null
private var userId: Int = 0
private var email: String? = null
companion object {
private const val USER_ID = "user_id"
private const val IMAGE_PROFILE = "img_profile"
private const val NAME_PROFILE = "name_profile"
private val TAG = ChatListActivity::class.java.canonicalName
fun startActivity(
context: Context,
userId: Int?,
imageProfile: String,
nameProfile: String
) {
Intent(context, ChatListActivity::class.java).apply {
putExtra(USER_ID, userId)
putExtra(IMAGE_PROFILE, imageProfile)
putExtra(NAME_PROFILE, nameProfile)
context.startActivity(this)
}
}
}
private val message: String
get() = edtSendChat.text.toString()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_list)
initToolbar()
userMesibo = ApplicationPrefs.get(Constant.MESIBO_USER)
presenter = ChatListPresenter(this)
userId = intent.getIntExtra(USER_ID, 0)
imageProfile = intent.getStringExtra(IMAGE_PROFILE)
nameProfile = intent.getStringExtra(NAME_PROFILE)
chatListAdapter = ChatListAdapter(chatList)
rvChatList.adapter = chatListAdapter
rvChatList.layoutManager = layoutManager
rvChatList.addItemDecoration(DefaultItemDecoration(spacing = 10.dp, includeEdge = true))
tvName.text = nameProfile
Picasso.get().load(imageProfile)
.error(R.drawable.com_facebook_profile_picture_blank_square)
.placeholder(R.drawable.com_facebook_profile_picture_blank_square).into(imgProfile)
presenter.getEmailUser(userId)
}
private fun initToolbar() {
setSupportActionBar(toolbar)
val backArrow = ContextCompat.getDrawable(this, R.drawable.ic_back_black)
supportActionBar?.setHomeAsUpIndicator(backArrow)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
tvSeeProfile.setOnClickListener(this)
imgCalling.setOnClickListener(this)
imgVideoCall.setOnClickListener(this)
imgSendChat.setOnClickListener(this)
tilChat.setStartIconOnClickListener {
NotMatchActivity.startActivity(this)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun getChatListSuccess(response: MutableList<DataAttributes>) {
}
override fun getChatListFailed(message: String) {
}
override fun successPost(response: SuccessModel?) {
}
override fun failedPost(message: String) {
shortToast(message)
}
override fun onGetEmailUser(data: UserEmailResponse?) {
email = data?.email
startMesibo()
email?.let { loadFromDb(it) }
}
override fun onLoading(isShow: Boolean) {
if (isShow) {
rvChatList.gone()
loadingView.visible()
} else {
rvChatList.visible()
loadingView.gone()
}
}
override fun onNoData(msg: String?) {
shortToast(msg.toString())
}
override fun onBadRequest(msg: String?) {
shortToast(msg.toString())
}
override fun onUnauthorized(msg: String?) {
shortToast(msg.toString())
badToken()
}
override fun onClick(v: View?) {
when (v) {
imgSendChat -> if (message.isNotBlank()) onSendMessage()
tvSeeProfile -> {
UserProfileActivity.startActivity(this, userId)
}
imgCalling -> MesiboCall.getInstance().callUi(this, email, false)
imgVideoCall -> MesiboCall.getInstance().callUi(this, email, true)
}
}
override fun Mesibo_onMessage(p0: MessageParams?, p1: ByteArray?): Boolean {
val type: Int = if (p0?.isIncoming == true) 0 else 1
val msg = String(p1!!)
chatList.add(
ChatModel(
id = p0!!.mid,
msg = msg,
date = p0.ts,
type = type,
status = p0.status
)
)
chatListAdapter.notifyItemInserted(chatList.size)
layoutManager.scrollToPositionWithOffset(chatList.size - 1, 0)
return true
}
override fun Mesibo_onMessageStatus(p0: MessageParams?) {
chatList.find { p0?.mid == it.id }?.status = p0?.status
chatListAdapter.notifyDataSetChanged()
Log.i("TAG", "Mesibo_onMessageStatus: ${p0?.status}}")
}
override fun Mesibo_onActivity(p0: MessageParams?, p1: Int) {
Log.i("TAG", "Mesibo_onActivity: $p1")
when (p1) {
ACTIVITY_ONLINE -> {
imgDotOnline.visible()
imgDotOffline.gone()
Log.i(TAG, "MESIBO_ACTIVITY: activity on")
}
ACTIVITY_TYPING -> Log.i(TAG, "MESIBO_ACTIVITY: user typing")
else -> {
imgDotOnline.gone()
imgDotOffline.visible()
Log.i(TAG, "Mesibo_onActivity: $p1")
}
}
}
override fun Mesibo_onLocation(p0: MessageParams?, p1: Location?) {}
override fun Mesibo_onFile(p0: MessageParams?, p1: FileInfo?) {}
override fun Mesibo_onConnectionStatus(p0: Int) {
when (p0) {
STATUS_ONLINE -> {
setPushToken(ApplicationPrefs.tokenFcm)
tvConnectionStatus.gone()
Log.d(TAG, "MESIBO_CONNECTION_STATUS: online")
}
STATUS_OFFLINE -> {
tvConnectionStatus.gone()
Log.d(TAG, "MESIBO_CONNECTION_STATUS: offline")
}
STATUS_CONNECTING -> {
tvConnectionStatus.visible()
tvConnectionStatus.text = getString(R.string.connecting)
Log.d(TAG, "MESIBO_CONNECTION_STATUS: offline")
}
STATUS_CONNECTFAILURE, STATUS_NONETWORK -> {
tvConnectionStatus.visible()
tvConnectionStatus.text = getString(R.string.mesibo_connect_fail_msg)
}
else -> {
Log.d(TAG, "MESIBO_CONNECTION_STATUS: $p0")
Log.d(TAG, "MESIBO_TOKEN: ${userMesibo?.token}")
}
}
}
override fun Mesibo_onSync(p0: Int) {
if (p0 <= 0) return
readSession.read(p0)
}
private fun onSendMessage() {
val p = MessageParams()
p.profile = userProfile
p.peer = email
p.mid = random()
p.flag = FLAG_DELIVERYRECEIPT or FLAG_READRECEIPT
sendMessage(p, p.mid, message)
chatList.add(
ChatModel(
id = p.mid,
msg = edtSendChat.text.toString(),
date = getTimestamp(),
type = 1,
status = 0
)
)
chatListAdapter.notifyItemInserted(chatList.lastIndex)
layoutManager.scrollToPositionWithOffset(chatList.size - 1, 0)
edtSendChat.text?.clear()
}
private fun loadFromDb(address: String) {
setAppInForeground(this, ChatListActivity.hashCode(), true)
readSession = ReadDbSession(address, this)
readSession.enableReadReceipt(true)
readSession.enableCalls(false)
readSession.enableIncomingCalls(false)
readSession.enableMissedCalls(false)
readSession.enableOutgoingCalls(false)
readSession.enableFifo(true)
readSession.read(500)
}
private fun startMesibo() {
addListener(this)
setSecureConnection(true)
setAccessToken(userMesibo?.token)
setDatabase("db_mesibo", 0)
start()
userProfile = UserProfile()
userProfile?.address = email
setUserProfile(userProfile, true)
}
}
Any clue about how to resolve and debug?
this is my env:
Mesibo AP = 2.7.0
Build tools = 29.0.0
compile SDK versions = 30
appid = com.project.bucynapp
Thanks!
Have you tried the custom scripts or mesibo webhook to debug the issue? Have you referred to the Troubleshooting section in the mesibo push-notification document?
https://mesibo.com/documentation/api/push-notifications/
Unless you post logs and steps you have taken, we have no clue what is happening.
I'm trying to build an Instagram-like app, an issue occurs when I try to save taken photo to user's folder "images" on Firebase database. It keeps saving something like "com.google.firebase.storage.UploadTask#62873ce"
Instead of link like this:
"https://firebasestorage.googleapis.com/v0/b/gramgram-1b3f9.appspot.com/o/users%2F7q3pqR6GnHMx7NSdgoBqZETkrS32%2Fphoto?alt=media&token=bbcbe556-1de5-4176-aba2-599f829e65"
here is my Share Activity.kt
class ShareActivity : BaseActivity(2) {
private val TAG = "ShareActivity"
private lateinit var mCamera: CameraHelper
private lateinit var mFirebase: FirebaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_share)
Log.d(TAG, "onCreate")
mFirebase =FirebaseHelper(this)
mCamera = CameraHelper(this)
mCamera.takeCameraPicture()
back_image.setOnClickListener{finish()}
share_text.setOnClickListener{share()}
}
#SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == mCamera.REQUEST_CODE){
if (resultCode == RESULT_OK){
GlideApp.with(this).load(mCamera.imageUri).centerCrop().into(post_image)
} else{
finish()
}
}
}
private fun share(){
val imageUri = mCamera.imageUri
if (imageUri != null){
val uid = mFirebase.auth.currentUser!!.uid
mFirebase.storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).putFile(imageUri).addOnCompleteListener {
if (it.isSuccessful){
mFirebase.database.child("images").child(uid).push()
.setValue(it.toString())
.addOnCompleteListener{
if (it.isSuccessful){
startActivity(Intent(this,
ProfileActivity::class.java))
finish()
} else {
showToast(it.exception!!.message!!)
}
}
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
here are my uploadUserPhoto and updateUsePhoto functions in FirebaseHelper.kt
fun uploadUserPhoto(photo: Uri, onSuccess: (String) -> Unit) {
val uTask = storage.child("users/${auth.currentUser!!.uid}/photo").putFile(photo)
storage.child("users/${auth.currentUser!!.uid}/photo").putFile(photo)
.addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { _ ->
storage.child("users/${auth.currentUser!!.uid}/photo").downloadUrl
}.addOnCompleteListener{
if (it.isSuccessful && it.result != null) {
onSuccess(it.result.toString())
} else {
activity.showToast(it.exception!!.message!!)
}
}
}
}
}
fun updateUserPhoto( photoUrl: String, onSuccess: () -> Unit){
database.child("users/${auth.currentUser!!.uid}/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
activity.showToast(it.exception!!.message!!)
}
}
}
I am not sure how to set my private fun share() to upload correct URL to User's "images" folder
and here is my CameraHelper.kt
class CameraHelper(private val activity: Activity){
var imageUri: Uri? = null
val REQUEST_CODE = 1
private val simpleDateFormat = SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.US
)
fun takeCameraPicture() {
val intent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(activity.packageManager) != null) {
val imageFile = createImageFile()
imageUri = FileProvider.getUriForFile(
activity,
"com.example.homeactivity.fileprovider",
imageFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
activity.startActivityForResult(intent, REQUEST_CODE)
}
}
private fun createImageFile(): File {
val storageDir: File? = activity.getExternalFilesDir(
Environment.DIRECTORY_PICTURES
)
return File.createTempFile(
"JPEG_${simpleDateFormat.format(Date())}_",
".jpg",
storageDir
)
}
}
You're not using the result from putFile(imageUri) correctly. You have:
putFile(imageUri).addOnCompleteListener {
if (it.isSuccessful){
mFirebase.database.child("images").child(uid).push()
.setValue(it.toString())
That it.toString() is not the URL. it is the UploadTask object returned by putFile(). You can't just turn that into a string - it's a Task that you need to observe to get the result.
You seem to be fetching a download URL correctly in uploadUserPhoto using downloadUrl to fetch the URL to write. You're going to have to do it that way instead.
See also the documentation and this question.
I managed to solve it.
In case anyone needs it, here is working function share():
private fun share(){
val imageUri = mCamera.imageUri
if (imageUri != null){
val uid = mFirebase.auth.currentUser!!.uid
val uTask = mFirebase.storage.child("users").child(uid).child("images").child(imageUri.lastPathSegment!!).putFile(imageUri)
mFirebase.storage.child("users").child(uid).child("images").child(imageUri.lastPathSegment!!).putFile(imageUri)
.addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { _ ->
mFirebase.storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).downloadUrl
}.addOnCompleteListener {
if (it.isSuccessful && it.result != null)
mFirebase.database.child("images").child(uid).push()
.setValue(it.result.toString())
.addOnCompleteListener {
if (it.isSuccessful) {
startActivity(
Intent(
this,
ProfileActivity::class.java
)
)
finish()
} else {
showToast(it.exception!!.message!!)
}
}
}
} else {
showToast(it.exception!!.message!!)
}
}
}
}