Reading Firebase data returns null Android - java

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

Related

Current user to string

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

null String when retrieving data from Firebase

weird problem:
This code:
xNames[index] = String.valueOf(currentAttendance.getXName());
OUTPUT: "null"
but this code works fine:
xValues[index] = currentAttendance.getxValues();
OUTPUT: 7
any help thank you guys,,,, thank you , I LOVE YOU
this is my snippet code:
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.getChildrenCount();
int[] xValues = new int[count];
int[] yValues = new int[count];
String[] xNames = new String[count];
int index = 0;
for (DataSnapshot myDatabases : dataSnapshot.getChildren()) {
CurrentAttendance cA = myDatabases.getValue(CurrentAttendance.class);
if (cA != null) {
xNames[index] = String.valueOf(cA.getXName());
xValues[index] = cA.getUserCount();
}
if (cA != null) {
yValues[index] = cA.getCurrentAttendance();
}
index++
}
}
}
Database structure:
To solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Attendance").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String xname = dataSnapshot.child("xname").getValue(String.class);
Log.d(TAG, xname);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Vaianaa
To get all the user names, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference attendanceRef = rootRef.child("Attendance");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String xname = ds.child("xname").getValue(String.class);
Log.d(TAG, xname);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
attendanceRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
Vaianaa
Newton

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

Firebase Data retrieval in array

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

Categories