Firebasestorage Collect Data and Save in to Firebasestorage



现在我可以从gallery&camera中选择图像,也可以裁剪它。但是当我点击保存按钮时,我不能将图像保存到firebase。

这是我的activity.kt&xml

这是AccountSettingsActivity.kt

`package com.example.pureeducationapp
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.canhub.cropper.*
import com.example.pureeducationapp.Model.User
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.OnCompleteListener
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.StorageTask
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_account_settings.*
import kotlin.collections.HashMap

class AccountSettingsActivity : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private var checker = ""
private var imageUri: Uri? = null
private var myUrl = ""
private var storageProfilePicRef: StorageReference? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_settings)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
storageProfilePicRef = FirebaseStorage.getInstance().reference.child("Profile Pictures")

change_image_text_btn.setOnClickListener {
checker = "clicked"
launchCropImage()
}
logout_btn.setOnClickListener {
FirebaseAuth.getInstance().signOut()
val intent = Intent(this@AccountSettingsActivity, SignInActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
save_inFor_profile_btn.setOnClickListener {
if (checker == "clicked") {
uploadImageAndUpdateInfo()
} else {
updateUserInfoOnly()
}
}

userInfo()

}
private val cropImage = registerForActivityResult(CropImageContract()) { result ->
if (result.isSuccessful) {
val uriContent = result.uriContent
Log.d("uriContent", uriContent.toString()) // getting called
profile_image_view_profile_frag.setImageURI(uriContent)
} else {
val exception = result.error
}

}
private fun launchCropImage() {
cropImage.launch(
options {
setGuidelines(CropImageView.Guidelines.ON)
}
)
}
private fun updateUserInfoOnly() {
when {
full_name_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please insert full name first.",
Toast.LENGTH_LONG
).show()
username_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please insert username first.",
Toast.LENGTH_LONG
).show()
bio_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please tell about yourself first.",
Toast.LENGTH_LONG
).show()
else -> {
val userRef = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["fullname"] = full_name_profile_frag.text.toString()
userMap["username"] = username_profile_frag.text.toString()
userMap["bio"] = bio_profile_frag.text.toString()
userRef.child(firebaseUser.uid).updateChildren(userMap)
Toast.makeText(this, "Account Information has been updated.", Toast.LENGTH_LONG)
.show()
val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
private fun userInfo() {
val userRef =
FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.uid)
userRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val user = snapshot.getValue<User>(User::class.java)
Picasso.get().load(user!!.getImage()).placeholder(R.drawable.profile)
.into(profile_image_view_profile_frag)
username_profile_frag.setText(user!!.getUsername())
full_name_profile_frag.setText(user!!.getFullname())
bio_profile_frag.setText(user!!.getBio())
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun uploadImageAndUpdateInfo() {
when {
imageUri == null -> Toast.makeText(
this,
"Please select your image first.",
Toast.LENGTH_LONG
).show()
full_name_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please insert full name first.",
Toast.LENGTH_LONG
).show()
username_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please insert username first.",
Toast.LENGTH_LONG
).show()
bio_profile_frag.text.toString() == "" -> Toast.makeText(
this,
"Please tell about yourself first.",
Toast.LENGTH_LONG
).show()
else -> {
val fileref = storageProfilePicRef!!.child(firebaseUser!!.uid + ".jpg")
val uploadTask: StorageTask<*>
uploadTask = fileref.putFile(imageUri!!)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return@Continuation fileref.downloadUrl
}).addOnCompleteListener(OnCompleteListener<Uri> { task ->
if (task.isSuccessful) {
val downloadUrl = task.result
myUrl = downloadUrl.toString()
val ref = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["fullname"] = full_name_profile_frag.text.toString()
userMap["username"] = username_profile_frag.text.toString()
userMap["bio"] = bio_profile_frag.text.toString()
userMap["image"] = myUrl
ref.child(firebaseUser.uid).updateChildren(userMap)
Toast.makeText(
this,
"Account Information has been updated.",
Toast.LENGTH_LONG
).show()
val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
})
}

}
}
}`

这是ActivityAccountSettings.XML

`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AccountSettingsActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/app_bar_layout_notifications"
android:background="@android:color/white">
<androidx.appcompat.widget.Toolbar
android:id="@+id/notifications_toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:background="@android:color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/close_profile_btn"
android:layout_width="20dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:src="@drawable/close"
/>
<ImageView
android:id="@+id/save_inFor_profile_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginEnd="15dp"
android:layout_alignParentEnd="true"
android:src="@drawable/save_edited_info"
/>
</RelativeLayout>

</androidx.appcompat.widget.Toolbar>


</com.google.android.material.appbar.AppBarLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image_view_profile_frag"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true"
android:src="@drawable/profile"
android:layout_below="@id/app_bar_layout_notifications"
/>
<TextView
android:id="@+id/change_image_text_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="@color/colorPrimary"
android:layout_below="@+id/profile_image_view_profile_frag"
/>
<EditText
android:id="@+id/full_name_profile_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/change_image_text_btn"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="16dp"
android:inputType="text"
android:hint="Fullname"
/>
<EditText
android:id="@+id/username_profile_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/full_name_profile_frag"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="16dp"
android:inputType="text"
android:hint="Username"
/>
<EditText
android:id="@+id/bio_profile_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/username_profile_frag"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="16dp"
android:inputType="text"
android:hint="About me"
/>
<TextView
android:id="@+id/delete_account_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="@+id/bio_profile_frag"
android:text="Delete Account ?"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="@color/red"

/>
<Button
android:id="@+id/logout_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="@color/colorPrimary"
android:text="Log out"
android:textColor="@color/white"
android:textSize="24sp"
android:textStyle="bold" />

</RelativeLayout>`

结果如下[https://media.giphy.com/media/fd31Toh3KDIhyo9sv1/giphy.gif]

似乎没有收集数据图像对吗?(如果我没有误解的话)。

如何解决这个问题?

当点击保存按钮时如何收集数据图像并将其保存到firebase存储?

问好我该如何解决这个问题?请帮助。

所以如果我理解正确的话,你可以成功地获得图像并裁剪它,所以你的firestore上传方法不起作用。这是我的工作示例,我不使用StorageTask,它更简单:

else -> {
val fileref = storageProfilePicRef!!.child(firebaseUser!!.uid + ".jpg")
fileref.putFile(imageFileURI!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { uri ->
val downloadUrl = uri.toString()
val ref = FirebaseDatabase.getInstance().reference.child("Users")
val userMap = HashMap<String, Any>()
userMap["fullname"] = full_name_profile_frag.text.toString()
userMap["username"] = username_profile_frag.text.toString()
userMap["bio"] = bio_profile_frag.text.toString()
userMap["image"] = downloadUrl
ref.child(firebaseUser.uid).updateChildren(userMap)
Toast.makeText(
this,
"Account Information has been updated.",
Toast.LENGTH_LONG
).show()
val intent = Intent(this@AccountSettingsActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
}
.addOnFailureListener { exception ->
Log.e(
this.javaClass.simpleName,
exception.message,
exception
)
}       
}

最新更新