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

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

Related

How to fetch data Firestore subcollection Kotlin?

I want to get data from Firebase Firestore subcollection for recyclerView. But I dont know if I write codes correctly or no. I also checked another variant with another collection without any subcollection and I see there I succesfully get data from Firestore. But with subcollection part which is i uploaded it with image below I can not fetch data and my recyclerView is empty.How can i fix that? Thanks in advance
Here is my Firebase Firestore collection
Here is my Firebase Firestore subcollection
And my codes
class Posts : AppCompatActivity(), RecAdapterPosts.ClickListener {
var modalList : ArrayList<ModalImageList> = ArrayList()
private lateinit var binding: PostsBinding
private lateinit var auth: FirebaseAuth
private var userAdapter = RecAdapterPosts(modalList, this)
private var db = Firebase.firestore
private var database: FirebaseFirestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = PostsBinding.inflate(layoutInflater)
val view = (binding.root)
setContentView(view)
auth = FirebaseAuth.getInstance()
database = FirebaseFirestore.getInstance()
gridPosts.adapter = userAdapter
gridPosts.layoutManager = GridLayoutManager(this,2)
get_information()
}
private fun get_information() {
val cu = auth.currentUser!!.uid
database.collection("İmagesPosts",).document(cu!!).collection("ImagesList").orderBy("date",
Query.Direction.DESCENDING
).addSnapshotListener { snaphot, exception ->
if (exception != null) {
Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG)
.show()
} else {
if (snaphot != null) {
if (!snaphot.isEmpty) {
val documents = snaphot.documents
modalList.clear()
for (document in documents) {
val imgUrl = document.get("downloadUs") as String
val imgName = document.get("imgName") as String
val download_post = ModalImageList(
imgUrl,
imgName,
)
modalList.add(download_post)
}
}
userAdapter.notifyDataSetChanged()
}
}
}
}

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

Combining Firebase Authentication with Realtime Database

I have created an app in Android Studio (Kotlin) that registers users:
User Interface
An email/password user is created (Authentication) along with a corresponding database record (Realtime Database):
Datbase Structure
I have the login procedure working and I'm able to display the logged-in user's email address on MainActivity, BUT, I don't know how to display the user's name and favourite colour (from the database).
Can anyone help?
Thanks in advance for your time.
RegisterActivity.kt
class RegisterActivity : AppCompatActivity() {
private lateinit var mAuth : FirebaseAuth
private lateinit var viewModel: UserViewModel
public val USER: String = "user"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
mAuth = FirebaseAuth.getInstance()
viewModel = ViewModelProvider(this).get(UserViewModel::class.java)
register_button.setOnClickListener {
val email = register_email.text.toString().trim()
val password = register_password.text.toString().trim()
val name = register_name.text.toString().trim()
val colour = register_colour.text.toString().trim()
mAuth.createUserWithEmailAndPassword(email, password)
val user = User()
user.email = email
user.name = name
user.colour = colour
viewModel.addUser(user)
}
}
}
LoginActivity.kt
class LoginActivity : AppCompatActivity() {
private lateinit var mAuth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
login_button.setOnClickListener {
val email = login_email.text.toString().trim()
val password = login_password.text.toString().trim()
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
//Login Success
val intent = Intent (this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK
}
startActivity(intent)
}else{
//Login Failure
task.exception?.message?.let {
toast(it)
}
}
}
}
}
}
MainActivity.kt (to display User details)
class MainActivity : AppCompatActivity() {
private val currentUser = FirebaseAuth.getInstance().currentUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
currentUser?.let { user ->
main_email.setText(user.email)
main_name.setText("Don't Know")
main_colour.setText("Don't Know")
}
}
}
Edit 3
LoginActivity.kt
class LoginActivity : AppCompatActivity() {
private lateinit var mAuth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
login_button.setOnClickListener {
val email = login_email.text.toString().trim()
val password = login_password.text.toString().trim()
loginUser (email, password)
}
}
private fun loginUser(email: String, password: String) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
//Login Success
val intent = Intent(this,MainActivity::class.java)
intent.putExtra("username",user.displayName)
intent.putExtra("email",user.email)
startActivity(intent)
}else{
//Login Failure
task.exception?.message?.let {
toast(it)
}
}
}
}
override fun onStart() {
super.onStart()
mAuth.currentUser?.let {
login()
}
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
//I have commented out the line below because it may not be required...
// private val currentUser = FirebaseAuth.getInstance().currentUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//I have commented out the lines below because they may not be required...
//currentUser?.let { user ->
//main_email.setText(user.email)
//main_name.setText("Don't Know")
//main_colour.setText("Don't Know")
//}
}
}
ERROR 1 : Overload resolution ambiguity on putExtra
ERROR 2 : Unresolved Reference on user.
When you launch at your login stage
mAuth.signInWithEmailAndPassword(email, password)
It has a callback that will be completed and successful when the user has been logged in, inside that callback, you are already logged in and that user now corresponds to one unique user ID, you can access that user ID by doing
val user = FirebaseAuth().getInstance().currentUser.uid
Then, here you can fetch that user data and pass it as an extra or bundle to your MainActivity, so the login process will take the time to log the user, fetch its data and send it to the MainActivity, this way you are not delaying any more time the user at your MainActivity
You can see that the user has been created once that successful callback is launch, and then in the Firebase console you can check for that user in the authentication tab
Edit
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
//Login Success, here you can get currentUser
val user = FirebaseAuth().getInstance().currentUser
login(user.displayName,user.email)
}else{
//Login Failure
task.exception?.message?.let {
toast(it)
}
}
}
Then, just add these two parameters to the login() method and just do a putExtra with those values and send those values as an extra to the main activity, so you are not fetching in your mainactivity and just sending the values from the login
Keep in mind that after .addonCompleteListener() the result is your current logged in user, so from here, you can get the currentUser information or the currentUser id
Edit 2
Inside the onComplete , just pass the data to the MainActivity
val intent = Intent(this,MainActivity::class.java)
intent.putExtra("username",user.displayName)
intent.putExtra("email",user.email)
startActivity(intent)
Then in your MainActivity get this extras
val extras = getIntent().extras
val userName: String?
val email: String?
if (extras != null) {
userName = extras.getString("userame")
email = extras.getString("email")
}
Then you already have the data from login into your MainActivity
Edit 3
To change the color, just change it from the MainActivity
your_text_view.setTextColor(ContextCompat.getColor(this,R.color.yourColor)
Please read this

Categories

Resources