How can I get data of logged in user from firebase database - java

I need help in this code.
How can I fetch logged in user data from firebase database?
These are my codes:
public void getUserInfo(){
mFirebaseDatabase = FirebaseDatabase.getInstance();
mUserDatabase = mFirebaseDatabase.getReference("users");
FirebaseUser user = mAuth.getCurrentUser();
mUserDatabase.child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( com.google.firebase.database.DataSnapshot datasnapshot) {
for (DataSnapshot dataSnapshot : datasnapshot.getChildren()) {
User user1 = dataSnapshot.getValue(User.class);
String firstname = user1.getFirstName();
String secondname = user1.getSecondName();
String email = user1.getEmail();
String enrollment = user1.getEnrollnumber();
String branch = user1.getBranch();
String college = user1.getCollege();
First_name.setText(firstname);
Second_name.setText(secondname);
tx_Email.setText(email);
Enroll_number.setText(enrollment);
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
/*
* You may print the error message.
**/
}
});
}
Any help would be appreciated!

As far as I can see, you're attaching a listener to the data of a single user. That means that you don't need to loop over dataSnapshot.getChildren() in onDataChange.
So:
public void onDataChange( com.google.firebase.database.DataSnapshot snapshot) {
User user1 = snapshot.getValue(User.class);
String firstname = user1.getFirstName();
String secondname = user1.getSecondName();
String email = user1.getEmail();
String enrollment = user1.getEnrollnumber();
String branch = user1.getBranch();
String college = user1.getCollege();
First_name.setText(firstname);
Second_name.setText(secondname);
tx_Email.setText(email);
Enroll_number.setText(enrollment);
}

try this, in my case my database in firebase is called "Users", with and userID is the id of each user, using this userID i filter the data of each user example (name, email...etc)
You need to write a for to iterate all fields and after that get the position that you need, example position[0] = name, position[1] = email...etc
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("Users").child(userID);
final List<String> lstItems= new ArrayList<String>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String values = (String) ds.getValue();
lstItems.add(values);
}
Log.d(TAG, "NAME: " + lstItems.get(0).toString());
Log.d(TAG, "EMAIL: " + lstItems.get(1).toString());
and to print them
email = lstItems.get(0).toString();
name = lstItems.get(1).toString();
I hope it helps you

Related

Get Children in JSON DataSnapshot

I'm trying to get the children from my JSON separately and pass them through an intent. Here is how my JSON is formatted:
"allDeeJays" : {
"-LeP1DB6Onzh4-UiN_0E" : {
"acct" : "Aaron A",
"djName" : "uhgvvvbbb"
}
},
Using the DataSnapshot, I have been able to get the djName values, but I am not getting the acct values, with the following code:
#Override
protected void onBindViewHolder(#NonNull ResultsViewHolder holder, final int position, #NonNull final DataSnapshot snapshot) {
// Here you convert the DataSnapshot to whatever data your ViewHolder needs
String s = "";
for(DataSnapshot ds : snapshot.getChildren())
{
s = ds.getValue(String.class);
DjProfile model = new DjProfile(s);
model.setDjName(s);
holder.setDjProfile(model);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("allDeeJays");
String acct = "";
String name = "";
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
Intent i = new Intent(getApplication(), AddSongRequest.class);
i.putExtra("DjName", name);
i.putExtra("UserAcct", acct);
startActivity(i);
}
});
}
};
Finally, my DjProfile class is defined as follows:
package com.example.android.heydj;
import com.google.firebase.database.Exclude;
import com.google.firebase.database.PropertyName;
public class DjProfile
{
String djName;
String key;
public DjProfile(String djName)
{
this.djName = djName;
}
public DjProfile(){}
public void setDjName(String djName)
{
this.djName = djName;
}
public String getdjName()
{
return djName;
}
}
Both variables are returning the same value, and when I run snapshot.getChildrenCount() it says that there are two children (which I assume are acct, and djName). Do I need to add additional getters and setters for the account name? Any help is greatly appreciated :)
Try like this and it's will return exact value for your keys
if(snapShot.getKey().equalsIgnoreCase("djName"))
name = ds.getValue(String.class);
if(snapShot.getKey().equalsIgnoreCase("acct"))
acct = ds.getValue(String.class);
or use
DjProfile model = snapShot.getValue(DjProfile.class);
instead of
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
You can resolve this by adding below line -
DjProfile profile = ds.getValue(DjProfile.class);
You can now pass this profile into an Intent.

How do you append to an array list in realtime database?

I have a database of users with their emails, role and list of contacts.
I have code to add contacts that when you input into the EditText, it checks through the database if the email exists and if it does, it appends the email into the contacts list. However, nothing gets added in my database.
public void searchContacts(final String emailInput){
final DatabaseReference users;
users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
if((userSnapshot.child("email").getValue(String.class).equals(emailInput))){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
}
}
}
Nothing is added, because you haven't create a list yet. To solve this, please use the following code:
public void searchContacts(final String emailInput){
DatabaseReference users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>(); //Create the list
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
String email = userSnapshot.child("email").getValue(String.class);
if(email.equals(emailInput)){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
list.add(email); //Add the email the list
}
}
//Do what you need to do with list
}
}
}

fetching data from firebase without using primary key of the table

I want to retrieve posts posted by currently loggedin user. But with current code all the posts are getting retrieved. How to retrieve expected data by using the uid from customer table?
post_id is primary key of Customer table not customerid(uid).
Get a reference of the current user and use it to query post posted by the user like this:
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
Query reference;
reference = FirebaseDatabase.getInstance().
getReference("customers").orderByChild("customerId").equalTo(user.getUid());
reference.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String
customerId =datas.child("customerId").getValue().toString();
String
customerName =datas.child("customerName").getValue().toString();
String
phone =datas.child("phone").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try like this ,
Step 1. Get the right child node , and query on it by getting the current logded user uid:-
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("customers").orderByChild("customerId").equalTo(currentLoginId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<Customers> customers = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
Customers user = dataSnapshotChild.getValue(Customer.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Retrieve data to text view from fire base without parent key

This is firebase database details
Here I want to search details using child without use parent key. According to this database, I want to get price and category using Name without using parent key ("kjhsfkgkrlhg"), ("get price, category where Name="super Creamcracker")
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemsRef = rootRef.child("Items");
Query query = itemsRef.orderByChild("Name").equalsTo("super Creamcracker");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
long price = ds.child("Price").getValue(Long.class);
Log.d("TAG", category + " / " + price);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
So the ds contains a list of results. Even if there is only a single result, the ds will contain a list of one result. So the output will be:
200g / 200
First, you make database reference first
DatabaseReference itemRef = FirebaseDatabase.getInstance().getReference("Items");
then,
String itemName = "super Creamcracker";
Query query = itemRef.orderByChild("Name").startAt(itemName).endAt(itemName+ "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//if you dont have class for item
String price = data.child("Price").getValue().toString();
String category = data.child("Category").getValue().toString();
//if you have class, lets say Item.java
Item item = data.getValue(Item.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase Database data collection

I am using Firebase database for my project. For the last few days I tried to retrieve data from database but without luck. I tried many tutorials and questions from Stack.. Database looks like this:
Database structure
My user class
I would like to retrieve information and store it in one of the strings..
My code is:
Every time I receive value Null or an Error. I am not sure If I am using correct reference("Users").
Is there is easy way to retrieve users name and store it into the string? Thanks
First you need to have same names for the fields in your database as in your model class. Looking at you model class, there are some things that you need to do. So, I'll provide a correct way to model your class.
public class UserModelClass {
private String name, sureName, date, phoneNumber;
public UserModelClass() {}
public UserModelClass(String name, String sureName, String date, String phoneNumber) {
this.name = name;
this.sureName = sureName;
this.date = date;
this.phoneNumber = phoneNumber;
}
public String getName() {return name;}
public String getSureName() {return sureName;}
public String getDate() {return date;}
public String getPhoneNumber() {return phoneNumber;}
}
In order to make it work, you need to remove all data from the database and add fresh one. There is a workaround when storing users in a Firebase database. Instead of using that that random key provided by the push() method, to use the uid. For that, I recommend you add the data as in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
UserModelClass umc = new UserModelClass("Jonas", "Simonaitis", "today", "123456789");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
uidRef.setValue(umc);
To read data, please use the following code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModelClass userModelClass = dataSnapshot.getValue(dataSnapshot.class);
String name = userModelClass.getName();
String sureName = userModelClass.getSureName();
String date = userModelClass.getDate();
String phoneNumber = userModelClass.getPhoneNumber();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In one of my tutorials I have explained step by step how to use the model classes when using Firebase.
First you have to do make these declarations:
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
in onCreate you need to make smth like this:
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase =FirebaseDatabase.getInstance().getReference().child("Users")
.child(current_uid);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("uName").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now you have the user name in "name"
First change userInformationActivity class variable names to match names in the database
example : name -> uName
surname -> uSurname
then
private void showData(DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
userInformationActivity user = dataSnapshot.getValue(userInformationActivity.class);
Log.d("user Name is : " + user.uName);
}
}

Categories