简体   繁体   English

将用户保存到 Firebase 数据库中的 Kotlin | Android工作室

[英]Save User to Firebase Database in Kotlin | Android Studio

My problem is that I want save the uid, username and his profileImageUrl.我的问题是我想保存 uid、用户名和他的 profileImageUrl。 All variables give the output that I need except "user" (I think).除了“用户”(我认为)之外,所有变量都给出了我需要的 output。

This is the function to save the user to database:这是 function 将用户保存到数据库:

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 用户:

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这是“用户”的 output: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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android 将数据保存到 firebase 数据库 - Android save data to firebase Database 用于 Android/Kotlin 应用程序中用户视图的 Firebase Analytics - Firebase Analytics for User View in Android/Kotlin App Firebase Android Studio 数据库查询 - Firebase Database Query in Android Studio Android Studio:让唯一的两个用户只能看到firebase实时数据库中的值,其他人看不到 - Android Studio: Make the only two user see only the value in firebase realtime database and the others will not Firebase 实时数据库通过 uid 检索数据并将其放入 Varable kotlin android - Firebase realtime database retrive data by uid and put it to Varable kotlin android 用户在 Kotlin Android 中从选定的书中离线保存数据 - Save data offline from a selected book by user in Kotlin Android 如何以有序的格式保存日期和时间 Firebase & Android Studio - How to save date and time in an orderly format Firebase & Android Studio 在 Android Studio 中使用 push() 在 Firebase 实时数据库中添加数据 - Adding data in Firebase realtime database using push() in Android Studio Recycler View 不更新来自 Firebase 数据库的消息:Android Studio - Recycler View not updating messages from Firebase Database: Android Studio 在 Firebase 数据库中保存 ArrayList - Save ArrayList in Firebase Database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM