Unable to write data on realtime database of firebase using kotlin - android

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.

Related

Firebase Authentication is working but data is not storing in relatime database

My Authentication is working fine but I am not able to store and retrive data from realtime database. Below is the firebase rule(I am using locked mode and Usa server) and my signup Activity class. Please help me with this thing. I am taking database refernce and giving setValue method but still its not working. I have also tried different solution given on stackoverflow flow but still no luck.
Firebase Rule
{
"rules": {
".read": "true", // 2022-8-22
".write": "true"
}
}
SignUp Acitvity
class SignUpActivity : AppCompatActivity() {
private lateinit var mAuth : FirebaseAuth
private lateinit var mDBRef : DatabaseReference
private lateinit var binding: ActivitySignIntoBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignIntoBinding.inflate(layoutInflater)
setContentView(binding.root)
mAuth = FirebaseAuth.getInstance()
binding.edtSignUp.setOnClickListener{
val name = binding.edtName.text.toString()
val email = binding.edtEmail.text.toString()
val password = binding.edtPassword.text.toString()
signUp(name, email, password)
}
binding.tvLogin.setOnClickListener {
val intent = Intent(this, Login::class.java)
finish()
startActivity(intent)
}
}
private fun signUp(name: String, email: String, password: String) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
addUserToDatabase(name, email, mAuth.currentUser?.uid!!)
val intent = Intent(this#SignUpActivity, MainActivity::class.java)
startActivity(intent)
} else {
Toast.makeText(this#SignUpActivity, "Some Error Occurred. Try Again", Toast.LENGTH_LONG ).show()
}
}
}
private fun addUserToDatabase(name: String, email: String, uid: String) {
mDBRef = FirebaseDatabase.getInstance("https://chatapplication-ad542-default-rtdb.firebaseio.com/").getReference()
mDBRef.child("User").child(uid).push().setValue(User(name, email, uid))
}
}

My firebase cannot upload to the realtime database? Android Kotlin

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)
}

failed: DatabaseError: Permission denied Firebase the user is being created but database is not updating

This is account create activity : Here the user is being created but the unless i change the rules to read write rules to true the database is not getting updated.
I only want the users database who is authorized.
Please help
class CreateAccountActivity : AppCompatActivity() {
var mAuth: FirebaseAuth? = null
var mDatabase: DatabaseReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_account)
mAuth = FirebaseAuth.getInstance();
idbuttonsignup.setOnClickListener{
var email = idemail.text.toString().trim()
var password = idpassword.text.toString().trim()
var displayName = iddisplayname.text.toString().trim()
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password) || !TextUtils.isEmpty(displayName)){
createAccount(email,password,displayName)
}else{
Toast.makeText(this,"Please fill out all the fields", Toast.LENGTH_LONG).show()
}
}
}
private fun createAccount(email: String, password: String, displayName: String){
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener{
task: Task<AuthResult> ->
if(task.isSuccessful){
var currentUserID = mAuth!!.currentUser
var userID = currentUserID!!.uid
Toast.makeText(this,"Task is sucessfull", Toast.LENGTH_LONG).show()
mDatabase = FirebaseDatabase.getInstance().reference.child("Users").child(userID)
var userObject = HashMap<String, String>()
userObject.put("display_name",displayName)
userObject.put("status", "Hello there...")
userObject.put("image", "default")
userObject.put("thumb_image","default")
mDatabase!!.setValue(userObject).addOnCompleteListener{
task: Task<Void> ->
if(task.isSuccessful){
var dashboardIntentOkc = Intent(this, DashboardActivity::class.java)
dashboardIntentOkc.putExtra( "name", displayName)
startActivity(dashboardIntentOkc)
finish()
Toast.makeText(this,"User Created", Toast.LENGTH_LONG).show()
}else{
Toast.makeText(this,"User Not Created", Toast.LENGTH_LONG).show()
}
}
}
}
}
}
_______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ please help
Have you define the rules in the Firebase Database for read and write operations. Check the Firebase official page if not.
Get Started with Database Rules

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()
}
}

Display data from Firebase Realtime Database

Created next structure in my database, and now want to display data in my list
Tried to add next code in onViewCreated:
databaseReference = FirebaseDatabase.getInstance().reference
val wordsRef = databaseReference?.child("talk-6e3c0")?.child("words")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
topWordsList.clear()
for (wordsSnapshot in dataSnapshot.children) {
val topWord = wordsSnapshot.getValue(TopWord::class.java)
topWord?.let { topWordsList.add(it) }
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("some", "Error trying to get targets for ${databaseError.message}")
}
}
wordsRef?.addListenerForSingleValueEvent(valueEventListener)
Method onDataChanged was called, but i can't get name for example.
My model:
data class TopWord(
val name: String = "",
val description: String = ""
)
You aren't getting something because you are adding the name of your project as a child in the reference and there is no need for that. So please change the following line of code:
val wordsRef = databaseReference?.child("talk-6e3c0")?.child("words")
to
val wordsRef = databaseReference?.child("words")
I just removed the call to .child("talk-6e3c0")?.

Categories

Resources