My firebase cannot upload to the realtime database? Android Kotlin - android

I'm trying to create a firebase app from android kotlin. I've already set up and connected the firebase to my app. But I cannot upload the data to the database? When I click the button it just won't upload and its like skipping the code to upload it. Here's my code:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.buttonSave.setOnClickListener {
saveData()
}
}
private fun saveData() {
val name = binding.etNama.text.toString().trim()
val address = binding.etAlamat.text.toString().trim()
if (name.isEmpty()) {
binding.etNama.error = "Isi nama"
return
}
if (address.isEmpty()) {
binding.etAlamat.error = "Isi alamat"
return
}
val ref = FirebaseDatabase.getInstance().getReference("mahasiswa")
val mhsId = ref.push().key
val mhs = Mahasiswa(mhsId,name,address)
if (mhsId!=null){
ref.child(mhsId).setValue(mhs).addOnCompleteListener {
Toast.makeText(applicationContext,"Data berhasil ditambahkan",Toast.LENGTH_SHORT).show()
}
}
}
}
My firebase database just stays null here
Database Screenshot
Here's the security rules:
Security Rules Screenshot
Can anyone help me? Cause I can't figure this out.

i think the problem is how you update your data. When i create a node usually i do like in the code that i post.
Try the following code snippet. I think it can help you
FirebaseDatabase.getInstance().reference.child("mahasiswa").setValue(mhs)
.addOnCompleteListener{
Toast.makeText(this, "Data save correctly!", Toast.LENGTH_LONG).show()
}
.addOnSuccessListener {
Toast.makeText(this, "Data PUSH ONLINE correctly!", Toast.LENGTH_LONG).show()
}.addOnFailureListener {
Log.d("Error", "error: " + it.message)
}

Related

Storing data of currently signned user in Firebase Firestore in Kotlin?

I am new to Android. I create sign-in and sign-up functionality. But I want to store the data of the user,(before going to the signing screen) when the user is signing up in the FireBase FireStore (based on the current user id). I have the user id, but I don't know the way to do it. The code is attached below. I am glad, If someone could help.
package com.example.firebase
import android.content.Intent
import android.os.Binder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.firebase.databinding.ActivitySignUpBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
class Sign_Up_Activity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var firebasefirestore: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
firebasefirestore = FirebaseFirestore.getInstance()
binding.signUpButton.setOnClickListener {
val email = binding.emailEt.text.toString()
val password = binding.passET.text.toString()
val confirmPass = binding.confirmPassEt.text.toString()
if (email.isNotEmpty() && password.isNotEmpty() && confirmPass.isNotEmpty()) {
if (password.equals(confirmPass)) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val userid:String= firebaseAuth.currentUser!!.uid
firebasefirestore.collection("user").document(userid).get()
Log.d("User id",userid)
val intent = Intent(this, Sign_In_Activity::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(),
Toast.LENGTH_SHORT)
.show()
}
}
} else {
Toast.makeText(this, "Password is not matching",
Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Empty Fields are not Allowed",
Toast.LENGTH_SHORT).show()
}
}
}
}
When you're using the following line of code:
firebasefirestore.collection("user").document(userid).get()
You aren't setting the user to Firestore, you're only reading it. If you want to add the data to the database, you have to use set() like in the following lines of code:
val db = Firebase.firestore
val user = mapOf("email" to firebaseAuth.currentUser!!.email)
val userRef = db.collection("user")
userRef.document(userid).set(user)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
If you're interested in implementing Firebase authentication with Google, then please check the following article:
How to authenticate to Firebase using Google One Tap in Jetpack Compose?
If you want by chance to implement the anonymous authentication, then please check:
How to handle Firebase Authentication in clean architecture using Jetpack Compose?

How to read asynchronous data from real-time database using android Kotlin?

Here is my code to read asynchronous data from a real-time database using android Kotlin:
class suDetails : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_su_details)
su_image.setOnClickListener {
readData(object : MyCallback {
override fun onCallback(imageUrl: String?) {
if (imageUrl != null) {
val imageViewer = Intent(baseContext, suDetails::class.java)
imageViewer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
imageViewer.putExtra("su_image", imageUrl)
startActivity(imageViewer)
}
}
})
}
}
fun readData(myCallback: MyCallback) {
val su_resource =intent
val su_res = su_resource.getStringExtra("su_userid")
val suRef = FirebaseDatabase.getInstance().getReference().child("Users").child(su_res!!)
suRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()){
su_layout.visibility = View.VISIBLE
val userData = dataSnapshot.getValue(profile_model::class.java)
val imageUrl = userData!!.getImageUrl()
Picasso.get().load(imageUrl).placeholder(R.drawable.ic_baseline_image_200).into(su_image)
su_name.text = userData.getnameOfsu()
Toast.makeText(baseContext, imageUrl, Toast.LENGTH_LONG).show()
myCallback.onCallback(imageUrl)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
interface MyCallback {
fun onCallback(value: String?)
}
}
I have referred to other questions to read asynchronous data from a real-time database but when I tried the solution I am not able to show any data in my ImageView and textView. I am getting only the blank screen.
The New code after the answer of Tyler V:
class suDetails : AppCompatActivity() {
private var currentImageUrl: String = ""
private var su_res: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_su_details)
su_res = intent.getStringExtra("su_userid").toString()
// get views
val su_name = findViewById<TextView>(R.id.su_name)
val su_image = findViewById<ImageView>(R.id.su_image)
// onClick launches another activity - if the image
// hasn't loaded yet nothing happens
su_image.setOnClickListener { viewCurrentImage() }
// start the async loading right away - once it is loaded the
// su_layout view will be visible and the view data
// will be populated. It might be good to show a progress bar
// while it's loading
readData()
}
fun readData() {
println("LOG: called readData")
Toast.makeText(baseContext, su_res, Toast.LENGTH_LONG).show()
println("LOG: getting data for ${su_res}")
val suRef = FirebaseDatabase.getInstance()
.getReference()
.child("Users")
.child(su_res)
suRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
println("LOG: data snapshot exists")
su_layout.visibility = View.VISIBLE
val userData = dataSnapshot.getValue(profile_model::class.java)
currentImageUrl = userData?.getImageUrl() ?: ""
su_name.text = userData?.getnameOfsu() ?: ""
println("LOG: Got user data ${currentImageUrl}")
if (currentImageUrl.isNotEmpty()) {
Picasso.get()
.load(currentImageUrl)
.placeholder(R.drawable.ic_baseline_image_200)
.into(su_image)
}
} else {
println("LOG: user not found in database")
}
}
override fun onCancelled(error: DatabaseError) {
println("LOG: cancelled")
}
})
}
private fun viewCurrentImage() {
if (currentImageUrl.isEmpty()) return
Toast.makeText(baseContext, currentImageUrl, Toast.LENGTH_LONG).show()
val imageViewer = Intent(baseContext, ImageViewer::class.java)
imageViewer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
imageViewer.putExtra("su_image", currentImageUrl)
startActivity(imageViewer)
}
}
The top answer to this related question shows you how to make callbacks, but that doesn't really answer the question of how to use the async data, and isn't really helpful or relevant to this type of problem.
I don't see anything specifically wrong with your callback - but it silently swallows a number of possible error cases (e.g. if the user doesn't exist). The example below has some print statements that should help determine better what is happening.
A cleaner approach than the extra callback interface is to make a separate method to handle the async result. Here is a cleaned up example of how that might look - with some pseudo-code where parts of your example were missing. To help debug, you should get in the habit of using log or print statements if you don't understand what parts of the code are running, or if something doesn't look the way you expect it to.
private var currentImageUrl: String = ""
private var userId: String = ""
private lateinit var su_name: TextView
private lateinit var su_image : ImageView
private lateinit var su_layout : ConstraintLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_su_details)
// get views
su_name = findViewById<TextView>(R.id.su_name)
su_image = findViewById<ImageView>(R.id.su_image)
su_layout = findViewById<ConstraintLayout>(R.id.su_layout)
su_layout.visibility = View.INVISIBLE
// get user id from intent
userId = intent.getStringExtra("su_userid").orEmpty()
// TODO: Handle what to do if userId is empty here!
if( userId.isEmpty() ) {
finish()
}
// onClick launches another activity - if the image
// hasn't loaded yet nothing happens
su_image.setOnClickListener { viewCurrentImage() }
// start the async loading right away - once it is loaded the
// su_layout view will be visible and the view data
// will be populated. It might be good to show a progress bar
// while it's loading
startLoading()
}
private fun startLoading() {
println("LOG: getting data for ${userId}")
val suRef = FirebaseDatabase.getInstance()
.getReference()
.child("Users")
.child(userId)
suRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()) {
println("LOG: data snapshot exists")
val userData = dataSnapshot.getValue(profile_model::class.java)
showData(userData)
}
else {
println("LOG: user not found in database")
}
}
override fun onCancelled(error: DatabaseError) {
println("LOG: cancelled")
}
})
}
private fun showData(userData: profile_model?) {
su_layout.visibility = View.VISIBLE
currentImageUrl = userData?.getImageUrl() ?: ""
su_name.text = userData?.getnameOfsu() ?: "Error"
println("LOG: Got user data ${currentImageUrl}")
if( currentImageUrl.isNotEmpty() ) {
Picasso.get()
.load(currentImageUrl)
.placeholder(R.drawable.ic_baseline_image_200)
.into(su_image)
}
}
private fun viewCurrentImage() {
if( currentImageUrl.isEmpty() ) return
val imageViewer = Intent(this, suDetails::class.java)
imageViewer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
imageViewer.putExtra("su_image", currentImageUrl)
startActivity(imageViewer)
}

Not being able to add user to my realtime firebase Database [duplicate]

This question already has answers here:
Firebase code not creating new user
(8 answers)
Closed last year.
I am trying to add a new user to my real-time database but getting "Failed Login" every time. I don't know where's the problem. "Loginfirebase" is my function for adding new users to the database, if a user is added successfully then I am calling "loadmain" function from where I am changing to other activity.
package com.example.tictactoe
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_room.*
class RoomActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_room)
login.setOnClickListener {
buLoginEvent()
}
}
fun buLoginEvent(){
val emailString = email.text.toString()
val passwordString = password.text.toString()
if(emailString.isNotEmpty() && passwordString.isNotEmpty()) {
LoginToFirebase(emailString, passwordString);
} else {
//show error message to user
Toast.makeText(this, "Email or Password cannot be empty!!", Toast.LENGTH_LONG).show()
}
}
fun LoginToFirebase(email:String, password:String){
var mAuth: FirebaseAuth = FirebaseAuth.getInstance()
var database = FirebaseDatabase.getInstance()
var myRef = database?.reference
var currentUser = mAuth!!.currentUser
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){
task->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Successful Login", Toast.LENGTH_LONG).show()
//saving in database
myRef.child("Users").child(splitString(currentUser!!.email.toString())).setValue(
currentUser!!.uid
)//creating current node iin realtime database
LoadMain()
}
else{
Toast.makeText(applicationContext,"Failed Login", Toast.LENGTH_LONG).show()
}
}
}
override fun onStart() {//2nd time when the application is started then call this method
super.onStart()
LoadMain()
}
fun LoadMain(){
var mAuth: FirebaseAuth = FirebaseAuth.getInstance()
var currentUser = mAuth!!.currentUser
if(currentUser!=null) {// doing this only when the user is not null
var intent = Intent(this, OnlineGameActivity::class.java)
intent.putExtra("email", currentUser!!.email)
intent.putExtra("uid", currentUser!!.uid)
startActivity(intent)
finish()
}
else{
}
}
fun splitString(str:String):String{
var split=str.split("#")
return split[0]
}
}
If a Task fails it contains an exception that tells you the cause of the failure, so you might want to write that to the logcat to find the root cause of your problem with:
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){
task->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Successful Login", Toast.LENGTH_LONG).show()
//saving in database
myRef.child("Users").child(splitString(currentUser!!.email.toString())).setValue(
currentUser!!.uid
)//creating current node iin realtime database
LoadMain()
}
else{
Toast.makeText(applicationContext,"Failed Login", Toast.LENGTH_LONG).show()
Log.e("FirebaseAuth", "Failed login", task.getException()); // 👈
}
}

Unable to write data on realtime database of firebase using kotlin

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val imageurl = imageurlset.text.toString()
val venue = venueset.text.toString()
val date = dateset.text.toString()
event_btn.setOnClickListener {
saveuserinfo(imageurl, venue, date) }
}
private fun saveuserinfo(imageurl: String, venue: String, date: String) {
val usersRef: DatabaseReference = FirebaseDatabase.getInstance().reference.child("event")
val adminRef: DatabaseReference = FirebaseDatabase.getInstance().reference.child("NewData")
val userMap = HashMap<String, Any>()
userMap["imageurl"] = imageurl
userMap["venue"] = venue
userMap["date"] = date
usersRef.child(date).setValue(userMap)
.addOnCompleteListener { task ->
adminRef.child(date).setValue(userMap)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
baseContext, "Success",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
baseContext, "error.",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
This is my mainActivity. I want to write data on realtime database using this code. I have already created database. I have url of my images. I am just unable to connect them with realtime database.
implementation platform('com.google.firebase:firebase-bom:29.0.3')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-database-ktx'
These are my dependencies.
{
"rules": {
".read": true,
".write": true
}
}
These are my rules for realtime database. Please help me with this.
I created another similar project and it worked out for me. I don't know the problem in my project but now my new project is working fine.

Can't retrieve data from firebase database to show inside my textbox

I tried to get the data from the firebase cloud database, but the data didn't show out.
This is the code I try to retrieve data
private fun updateUI(currentUser: FirebaseUser?){
if(currentUser!=null){
fstore.collection("users")
.document(auth.currentUser!!.uid)
.get()
.addOnCompleteListener { task->
task.result!!.get("name") == name.text.toString();
task.result!!.get("email") == email.text.toString();
Toast.makeText(baseContext, "Haha", Toast.LENGTH_LONG).show()
}
}else{
Toast.makeText(baseContext, "fail", Toast.LENGTH_LONG).show()
}
}
Calling UpdateUI() form activity
class MainActivity : AppCompatActivity() {
lateinit var name: TextView
lateinit var email: TextView
private lateinit var fstore: FirebaseFirestore
private lateinit var auth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
name = findViewById(R.id.name)
email = findViewById(R.id.email)
auth = FirebaseAuth.getInstance()
fstore = FirebaseFirestore.getInstance()
updateUI(auth.currentUser)
}
firebase cloud database:
android simulator after I tried:
Your document id assigning is wrong
.document(doucumentID) //Not user ID
//Here your document id is
//JXoTcqxIVENTSF2.....
//As I can see your firestore image
and you are assigning data in a wrong way to TextView
name.text = "value you want to assign"
So edit your code like this
private fun updateUI(currentUser: FirebaseUser?){
if(currentUser!=null){
fstore.collection("users")
.document("JXoTcqxIVENTSF2..")
//can not see full id in image so I use '....'
//replace it with full id from firestore
.get()
.addOnCompleteListener { task->
name.text = task.result!!.get("name").toString()
email.text = task.result!!.get("email").toString()
Toast.makeText(baseContext, "Haha", Toast.LENGTH_LONG).show()
}
}else{
Toast.makeText(baseContext, "fail", Toast.LENGTH_LONG).show()
}
}

Categories

Resources