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) {
}
});
}
}
}
}
}
}
}
Related
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!
}
}
});
I have a problem, when I want get value from firebase, getValue() return null
DataSnapshot appleSnapshot and DataSnapshot dataSnapshot - in console I see Key and Value correctly in Firebase too
Database Structure
Debugging
DataSnapshot setting - return Key but don't return Value (null)
String settingKey - return correctly String Key
String settingValue - return null
Why i cant get Value from my deeper childs?
private void readData(final ValidateJoinInterface validateJoinInterface, final String name, final String password, final String user) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
DataSnapshot setting = appleSnapshot.child(name).child("Settings").child("Password");
String settingKey = (String) appleSnapshot.child(name).child("Settings").child("Password").getKey();
String settingValue = (String) appleSnapshot.child(name).child("Settings").child("Password").getValue();
}
validateJoinInterface.validateJoin(correctName, correctPassword, correctUserId);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DTAG", "onCancelled", databaseError.toException());
}
});
}
Assuming that the name varaible holds a String value like in your example Aa and also assuming that Aa is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference settingsRef = rootRef.child(name).child("Settings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String password = dataSnapshot.child("Password").getValue(String.class);
Log.d("TAG", name + " / " + password);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
settingsRef.addListenerForSingleValueEvent(valueEventListener);
The output will be: Aa / Aaa.
You can getting any value like :
FirebaseDatabase.getInstance().getReference().child(name).child("Settings").child("Password")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG,"KEY - "+messageSnapshot.getKey() + "VALUE - "+messageSnapshot.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Crashlytics.logException(databaseError.toException());
sendMessageListener.onSendMessageFailure(databaseError.getMessage());
}
});
The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});
This is my Firebase realtime database structure:
How to get these data in a List to pass the data to the Model Class.
When I tried by generation data like below and it works.
listCourse = new ArrayList<>();
listCourse.add(new CourseModel("UserID", "CourseCode", "CourseName"));
listCourse.add(new CourseModel("122345", "TMN1234","System Programming"));
I just want get the data from firebase in this format..
You can retrieve list by this method.
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.i("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
CourseModel course = postSnapshot.getValue(CourseModel.class);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
Please refer this documentation: https://firebase.google.com/docs/database/android/lists-of-data
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
I figured it out.. this is working for me..
To Access Child you can to create reference.!
DatabaseReference userRef= FirebaseDatabase.getInstance().getReference("users");
DatabaseReference userChildRef= userRef.child(childId);
DatabaseReference userCourseRef= userChildRef.child("courses");
DatabaseReference userCourseIdRef= userCourseRef.child(courseId);
userCourseIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
Tol solve this, there are to ways. First would be to get the data as objects of CourseModel class like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<CourseModel> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
CourseModel courseModel = ds.getValue(CourseModel.class);
list.add(courseModel);
}
//Do what you need to do with the list of CourseModel objects
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);
The second one, would be to get the courseName as a String like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String courseName = ds.child("CourseName").getValue(String.class);
list.add(courseName);
}
//Do what you need to do with the list of strings
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);
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);