Kotlin - Cant upload an image to firebase storage - android

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.

Related

Save User to Firebase Database in Kotlin | Android Studio

My problem is that I want save the uid, username and his profileImageUrl. All variables give the output that I need except "user" (I think).
This is the function to save the user to database:
private fun saveUserToFirebaseDatabase(profileImageUrl: String) {
val uid = FirebaseAuth.getInstance().uid ?: ""
val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")
val user = User(uid, username_edittext_register.text.toString(), profileImageUrl)
ref.setValue(user)
.addOnSuccessListener {
Log.d("RegisterActivity", "Finally we saved the user to Firebase Database")
val intent = Intent(this,LatestMessagesActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
.addOnFailureListener{
Log.d("RegisterActivity", "Failed to set value to database: ${it.message}")
}
Log.d("saveUserToDatabase","Task completed? User: $user")
}
This the class User:
class User(val uid: String,val username: String,val profileImageUrl: String) {
constructor() : this("", "", "")
}
This is the "whole" code:
package letsbuildthatapp.com
import android.app.Activity
import android.content.ContentValues.TAG
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import kotlinx.android.synthetic.main.activity_register.*
import java.util.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_text_view.setOnClickListener {
Log.d("RegisterActivity", "Try to show login activity")
//Launch the login activity somehow
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
selectphoto_button_register.setOnClickListener {
Log.d("RegisterActivity", "Try to show photo selector")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
var selectedPhotoUri: Uri? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
Log.d("RegisterActivity", "Photo was selected")
selectedPhotoUri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver,selectedPhotoUri)
select_photo_imageView_register.setImageBitmap(bitmap)
selectphoto_button_register.alpha = 0f
}
}
private fun performRegister() {
val username = username_edittext_register.text.toString()
val email = email_edittext_register.text.toString()
val password = password_edittext_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this,"Please enter text in email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Username: $username")
Log.d("RegisterActivity", "Email is: $email")
Log.d("RegisterActivity", "Password: $password")
// Firebase Authentication to create a user with email and password
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener{
if (!it.isSuccessful) return#addOnCompleteListener
//else if successful
Log.d("RegisterActivity", "Successfully created user with uid: ${it.result.user!!.uid}")
uploadImageToFirebaseStorage()
}
.addOnFailureListener{
Log.d("RegisterActivity","Failed to create user: ${it.message}")
Toast.makeText(this,"Failed to create user: ${it.message}", Toast.LENGTH_SHORT).show()
}
}
private fun uploadImageToFirebaseStorage() {
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
Log.d("RegisterActivity", "Successfully uploaded image: ${it.metadata?.path}")
ref.downloadUrl.addOnSuccessListener {
Log.d("RegisterActivity", "File Location: $it")
saveUserToFirebaseDatabase(it.toString())
}
}
.addOnFailureListener{
Log.d("RegisterActivity", "Failed")
Toast.makeText(this,"Failed: ${it.message}", Toast.LENGTH_SHORT).show()
}
}
private fun saveUserToFirebaseDatabase(profileImageUrl: String) {
val uid = FirebaseAuth.getInstance().uid ?: ""
val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")
val user = User(uid, username_edittext_register.text.toString(), profileImageUrl)
ref.setValue(user)
.addOnSuccessListener {
Log.d("RegisterActivity", "Finally we saved the user to Firebase Database")
val intent = Intent(this,LatestMessagesActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
.addOnFailureListener{
Log.d("RegisterActivity", "Failed to set value to database: ${it.message}")
}
Log.d("saveUserToDatabase","Task completed? User: $user")
}
}
class User(val uid: String,val username: String,val profileImageUrl: String) {
constructor() : this("", "", "")
}
This is the output of "user": letsbuildthatapp.com.User#41cb40
I found the Solution for this Problem. It's really simple and making me sad that I get now after a day.
val ref = FirebaseDatabase.getInstance(Type here the Url of the database!).getReference("/users/$uid")

Getting the below errors related to the tensorflow lite while building kotlin app

I am getting the following error as show in the screenshot,please help me to solve the error related to the tensorflow lite.
[i was following this tutorial on youtube][1]
Iam not getting why the error is occurring as the code in the tutorial runs well.
thankyou
Below is the code where I am getting the following error.
package com.example.machineleaarningapp
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.machineleaarningapp.databinding.ActivityMainBinding
import com.example.machineleaarningapp.ml.Birdmodel2
import java.io.IOException
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var imageView: ImageView
private lateinit var button: Button
private lateinit var tvOutput: TextView
private val GALLERY_REQUEST_CODE = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
imageView = binding.imageView
button = binding.btnCaptureImage
tvOutput = binding.tvOutput
val buttonLoad = binding.btnLoadImage
button.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED
) {
takePicturePreview.launch(null)
}
else {
requestPermission.launch(android.Manifest.permission.CAMERA)
}
}
buttonLoad.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
val mimeTypes = arrayOf("image/jpeg","image/png","image/jpg")
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
onresult.launch(intent)
}else {
requestPermission.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
//to redirct user to google search for the scientific name
tvOutput.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/search?q=${tvOutput.text}"))
startActivity(intent)
}
// to download image when longPress on ImageView
imageView.setOnLongClickListener {
requestPermissionLauncher.launch(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
return#setOnLongClickListener true
}
}
//request camera permission
private val requestPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()){granted->
if (granted){
takePicturePreview.launch(null)
}else {
Toast.makeText(this, "Permission Denied !! Try again", Toast.LENGTH_SHORT).show()
}
}
//launch camera and take picture
private val takePicturePreview = registerForActivityResult(ActivityResultContracts.TakePicturePreview()){bitmap->
if(bitmap != null){
imageView.setImageBitmap(bitmap)
outputGenerator(bitmap)
}
}
//to get image from gallery
private val onresult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
Log.i("TAG", "This is the result: ${result.data} ${result.resultCode}")
onResultReceived(GALLERY_REQUEST_CODE,result)
}
private fun onResultReceived(requestCode: Int, result: ActivityResult?){
when(requestCode){
GALLERY_REQUEST_CODE ->{
if (result?.resultCode == Activity.RESULT_OK){
result.data?.data?.let{uri ->
Log.i("TAG", "onResultReceived: $uri")
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri))
imageView.setImageBitmap(bitmap)
outputGenerator(bitmap)
}
}else {
Log.e("TAG", "onActivityResult: error in selecting image")
}
}
}
}
private fun outputGenerator(bitmap: Bitmap){
//declearing tensor flow lite model variable
val birdsModel = Birdmodel2.newInstance(this)
// converting bitmap into tensor flow image
val newBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val tfimage = TensorImage.fromBitmap(newBitmap)
//process the image using trained model and sort it in descending order
val outputs = birdsModel.process(tfimage)
.probabilityAsCategoryList.apply {
sortByDescending { it.score }
}
//getting result having high probability
val highProbabilityOutput = outputs[0]
//setting ouput text
tvOutput.text = highProbabilityOutput.label
Log.i("TAG", "outputGenerator: $highProbabilityOutput")
}
// to download image to device
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
isGranted: Boolean ->
if (isGranted){
AlertDialog.Builder(this).setTitle("Download Image?")
.setMessage("Do you want to download this image to your device?")
.setPositiveButton("Yes"){_, _ ->
val drawable:BitmapDrawable = imageView.drawable as BitmapDrawable
val bitmap = drawable.bitmap
downloadImage(bitmap)
}
.setNegativeButton("No") {dialog, _ ->
dialog.dismiss()
}
.show()
}else {
Toast.makeText(this, "Please allow permission to download image", Toast.LENGTH_LONG).show()
}
}
//fun that takes a bitmap and store to user's device
private fun downloadImage(mBitmap: Bitmap):Uri? {
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME,"Birds_Images"+ System.currentTimeMillis()/1000)
put(MediaStore.Images.Media.MIME_TYPE,"image/png")
}
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
if (uri != null){
contentResolver.insert(uri, contentValues)?.also {
contentResolver.openOutputStream(it).use { outputStream ->
if (!mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)){
throw IOException("Couldn't save the bitmap")
}
else{
Toast.makeText(applicationContext, "Image Saved", Toast.LENGTH_LONG).show()
}
}
return it
}
}
return null
}
}
```[These are the errors I am getting][2]
[1]: https://www.youtube.com/watch?v=hsSPb6V84zc&t=1034s
[2]: https://i.stack.imgur.com/GsmBW.png

Adding user profile picture in Kotlin

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

Kotlin - Firebase and Glide - get image url so glide can use it

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

Kotlin Unresolved Reference: with

I have already tried invalidating caches. Clean build and rebuild project also done.
But I still keep getting unresolved reference: with
I'm using the Picasso library and my other activities are working fine. Picasso library has been implemented in the gradle.
The language version is 1.2 Android Studio
Code:
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import chatonapp.project.com.chatonapp.R
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.*
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.Picasso
import com.theartofdev.edmodo.cropper.CropImage
import id.zelory.compressor.Compressor
import kotlinx.android.synthetic.main.activity_settings.*
import java.io.ByteArrayOutputStream
import java.io.File
class SettingsActivity : AppCompatActivity() {
var mDatabase: DatabaseReference? = null
var mCurrentUser: FirebaseUser? = null
var mStorageRef: StorageReference? = null
var GALLERY_ID: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
mCurrentUser = FirebaseAuth.getInstance().currentUser
mStorageRef = FirebaseStorage.getInstance().reference
var userId = mCurrentUser!!.uid
mDatabase = FirebaseDatabase.getInstance().reference
.child("Users")
.child(userId)
mDatabase!!.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot?) {
var displayName = dataSnapshot!!.child("display_name").value
var image = dataSnapshot!!.child("image").value.toString()
var userStatus = dataSnapshot!!.child("status").value
var thumbnail = dataSnapshot!!.child("thumb_image").value
settinsDisplayName.text = displayName.toString()
settingsStatusText.text = userStatus.toString()
if (!image!!.equals("default")) {
Picasso.with(applicationContext)
.load(image)
.placeholder(R.drawable.profile_img)
.into(settingsProfileID)
}
}
override fun onCancelled(databaseErrorSnapshot: DatabaseError?) {
}
})
settingsChangeStatus.setOnClickListener {
var intent = Intent(this, StatusActivity::class.java)
intent.putExtra("status", settingsStatusText.text.toString().trim())
startActivity(intent)
}
settingsChangeImgBtn.setOnClickListener {
var galleryIntent = Intent()
galleryIntent.type = "image/*"
galleryIntent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT_IMAGE"), GALLERY_ID)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == GALLERY_ID
&& resultCode == Activity.RESULT_OK) {
var image: Uri = data!!.data
CropImage.activity(image)
.setAspectRatio(1, 1)
.start(this)
}
if (requestCode === CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(data)
if (resultCode === Activity.RESULT_OK) {
val resultUri = result.uri
var userId = mCurrentUser!!.uid
var thumbFile = File(resultUri.path)
var thumbBitmap = Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(65)
.compressToBitmap(thumbFile)
var byteArray = ByteArrayOutputStream()
thumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
byteArray)
var thumbByteArray: ByteArray
thumbByteArray = byteArray.toByteArray()
var filePath = mStorageRef!!.child("chat_profile_images")
.child(userId + ".jpg")
//Create another directory for thumbimages ( smaller, compressed images)
var thumbFilePath = mStorageRef!!.child("chat_profile_images")
.child("thumbs")
.child(userId + ".jpg")
filePath.putFile(resultUri)
.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
if (task.isSuccessful) {
var donwloadUrl = task.result.downloadUrl.toString()
var uploadTask: UploadTask = thumbFilePath
.putBytes(thumbByteArray)
uploadTask.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
var thumbUrl = task.result.downloadUrl.toString()
if (task.isSuccessful) {
var updateObj = HashMap<String, Any>()
updateObj.put("image", donwloadUrl)
updateObj.put("thumb_image", thumbUrl)
mDatabase!!.updateChildren(updateObj)
.addOnCompleteListener {
task: Task<Void> ->
if (task.isSuccessful) {
Toast.makeText(this, "Profile Image Saved!",
Toast.LENGTH_LONG)
.show()
}else {
}
}
}else {
}
}
}
}
}else if (resultCode === CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
val error = result.error
Log.d("Error", error.toString())
}
}
}
}
The problem happens here: Picasso.with
if (!image!!.equals("default")) {
Picasso.with(applicationContext)
.load(image)
.placeholder(R.drawable.profile_img)
.into(settingsProfileID)
}
How can I resolve this?
I had the same problem tonight, After looking at the Picasso site I noticed that .with is not used anymore. .get() works fine. Try something like this.
Picasso.get()
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
My code looked like this
val thumbnailImage = holder.view.imageView_Video_Thumbnail
Picasso.get().load(movieTitle.imageUrl).into(thumbnailImage)
Hope that helps someone.

Categories

Resources