Current user to string - java

I faced a problem with showing data. Before I used current users UID as a key but now I'm using the custom key and I don't know how to call this key as a string in my code.
My code this part ( child(user.getUid() )
FirebaseUser userUID;
userUID = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference NameRef = database.getReference().child("No server").child(userUID.getUid()).child("name");
final DatabaseReference LastNameRef = database.getReference().child("No server").child(userUID.getUid()).child("lastName");
final DatabaseReference EmailRef = database.getReference().child("No server").child(userUID.getUid()).child("email");
What changed
I want make user a string "dan ned".
Edit:
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference NameRef = database.getReference().child("No server").child(user.getUid()).child("name");
final DatabaseReference LastNameRef = database.getReference().child("No server").child(user.getUid()).child("lastName");
final DatabaseReference EmailRef = database.getReference().child("No server").child(user.getUid()).child("email");
NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strName = dataSnapshot.getValue(String.class);
textName.setText(strName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LastNameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strLastName = dataSnapshot.getValue(String.class);
textLastName.setText(strLastName);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EmailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String strEmail = dataSnapshot.getValue(String.class);
textEmail.setText(strEmail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

There is no need to attach three listeners in order to read those three values. You can use only one, as you can see in the following lines of code:
String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("No server").child(name);
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String key = snapshot.getKey();
Log.d("TAG", key); //It will print "dan ned"
String email = snapshot.child("email").getValue(String.class);
Log.d("TAG", email); //It will print "DanilNed#gmail.com"
String lastName = snapshot.child("lastName").getValue(String.class);
Log.d("TAG", lastName); //It will print "Ned"
String name = snapshot.child("name").getValue(String.class);
Log.d("TAG", name); //It will print "Dan"
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});

Related

I want to retrieve a current user's ID from firebase and write it in another node, but it just keeps denying

So basically I made a String mojID which is equal to firebase's current user, I want to pass it as a child in a node but it says it is a null pointer exception and I have already used it in another parts of a code which does not return the fault.
I am attaching some of my code.
final DatabaseReference chatRef1 = FirebaseDatabase.getInstance().getReference("ChatLista");
chatRef1.child(mojID);
chatRef1.child(userID);
chatRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
chatRef1.child("id").setValue(userID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
final DatabaseReference chatRef2 = FirebaseDatabase.getInstance().getReference("ChatLista");
chatRef2.child(userID);
chatRef2.child(mojID);
chatRef2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
chatRef2.child("id").setValue(mojID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Then there is function that takes the ID:
private void ProvjeriStatus(){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null){
//user ulogovan
mojID = (String)user.getUid();
}
//ako nije vraca na login
else {
startActivity(new Intent(this,login.class));
finish();
}
}
I even tried casting it as you can see it and it just says I don't need a cast, because it is already a String? Then why does it return null? The only explanation I have come up with is that it is an object not a string and by that .child wants a string as a argument not an object.
You can add UserId via FirebaseUser.. You can refer Below code .. maybe it will help
you
FirebaseUser currentFirebaseUser;
DatabaseReference databaseReference;
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Users").child(currentFirebaseUser.getUid()).child("User
Id").setValue(currentFirebaseUser.getUid());
If you want to retrieve UserId from database Refer Below code..
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue() == null)) {
databaseReference.child("Users").child(currentFirebaseUser.getUid())
.child("UserId").setValue(currentFirebaseUser.getUid());
} else {
String Id= (String) dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue();
}

Data retrieving error while i want to get all child from a certain Key

I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83

How to retrieve all data from Android Firebase database databaseRef->userID->uniqueKey

This is the Firebase database:
ExchangeItemsData: -> reference
lhmuj6n3g6Su1rv7XJLq5tV62yr2 -> userId
-LQQ7scByWcswW2VIPM5 -> UniqueKey inserted by .push().getKey();
// below is the data under the uniquekey
exchangeProductName:
"Pen"
imageUrl:
"https://firebasestoragse.googleapdfis.codfm/v04df/b/dbin..."
phoneNo:
5465464
productDesc:
"Used"
productName:
"GelPen"
userID:
"lhmuj6n3g6Su1rv7XJLq5tV62yr2"
I need to show all data of every user in this ExchangeItemsData reference. I've tried many ways but i failed. If anyone can help me out here it would be so nice of you.
Thanks in advance.
To get all those values that belong to all users, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("ExchangeItemsData");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String phoneNo = ds.child("phoneNo").getValue(String.class);
String productDesc = ds.child("productDesc").getValue(String.class);
String productName = ds.child("productName").getValue(String.class);
String userID = ds.child("userID").getValue(String.class);
Log.d(TAG, productName);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be all the product names of all products of all users.
Try this code to retrieve values from your database
public class Demo extends Activity{
FirebaseAuth mAuth;
String currentUId;
DatabaseReference usersDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mAuth=FirebaseAuth.getInstance();
currentUId=mAuth.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ExchangeItemsData");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
for (DataSnapshot userId : dataSnapshot.getChildren()) {
if(!userId.getKey().equals(currentUId)) {
usersDb.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.hasChildren()){
for (DataSnapshot userKey : dataSnapshot1.getChildren()) {
String exchangeProductName = dataSnapshot1.child(userKey).child("exchangeProductName").getValue().toString();
String imageUrl = dataSnapshot1.child(userKey).child("imageUrl").getValue().toString();
String phoneNo = dataSnapshot1.child(userKey).child("phoneNo").getValue().toString();
String productDesc = dataSnapshot1.child(userKey).child("productDesc").getValue().toString();
String productName = dataSnapshot1.child(userKey).child("productName").getValue().toString();
String userID = dataSnapshot1.child(userKey).child("userID").getValue().toString();
//From here do whatever you want to do with those values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
}
}
}

How can i get this id?

I did't want to make it key and value , I have tried a lot to find a solution, but I can't
And this my code when I tried to get it by key and value
mFriendID = (DatabaseReference) FirebaseDatabase.getInstance().getReference().child("friends").child(current_user).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fri_id = dataSnapshot.child("fri_id").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get the highlighted key, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("friends").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Reading Firebase data returns null Android

public void RetreiveNewQuestions(){
Random random = new Random();
int questionInt1;
questionInt1 = random.nextInt(2-1) + 1;
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance().getReference().child("questions").child("animal").child("1").child("question").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String question1 = dataSnapshot.getValue(String.class);
question[0] = question1;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This method is supposed to read questions randomly, but first for testing purposes I tried to see if it can read one question, but did not work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
questionRef = FirebaseDatabase.getInstance().getReference("questions");
category = "animal";
RetreiveNewQuestions();
String quizData[][] = {
//Format, {Question, right answer, option1, option2, option3}
{question[0], "Log", "Tree", "Knee"," Bee"},
{ "Potato", "Rar", "Laugh", "Test","Minute"}
};
What my data looks like in Firebase
If you want to get only the first question, then please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("questions").child("animal").child("1");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String question = dataSnapshot.child("questions").getValue(String.class);
Log.d("TAG", question);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
If you want to get all the questions, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalRef = rootRef.child("question").child("animal");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String question = ds.child("question").getValue(String.class);
Log.d("TAG", question);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);

Categories