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);
Related
I am trying to create child inside child -LoVaDPuBRr4K2JSkc_j , but how?
Code :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseDocument = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
To create a child in -LoVaDPuBRr4K2JSkc_j, you can do:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").child("newProperty").setValue("new value");
If you want to generate a new child with an auto-generated key, it'd be:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").push().setValue("new value");
Both of these assume that you know the -LoVaDPuBRr4K2JSkc_j value in your code. This is required to be a able to add a child, as writing to a location in the database requires that you know the full path to that location.
You'll not want to hardcode this key of course, so there are two common options to have the key:
Pass it along your app from the moment when you loaded the data.
Use some other value of the node that allows you to perform a query on the database to look up the key.
The simplest solution to add a new property inside your -LoVaDPuBRr4K2JSkc_j object would be use that pushed id in your reference like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child(uid).child("Document").child("-LoVaDPuBRr4K2JSkc_j");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("newProperty").setValue("newValue");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
Edit:
Accodring to your comment, if you have more than one key, then you should use a query. The following code will do the trick:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child(uid).child("Document").orderByChild("inspectorName").equalTo("Test");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().child("newProperty").setValue("newValue");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
My code and its work :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseProduct = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
String id = databaseProduct.push().getKey();
final String productID = databaseProduct.child(id).child("Product").push().getKey();
final Items items = new Items(productID, dates, nameInspector, locate, product, priceProduct, amount, code);
databaseProduct.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getDocumentKey : dataSnapshot.getChildren()) {
String getDocumentID = getDocumentKey.getKey();
String sameDocumentID = getDocumentKey.child("documentID").getValue().toString();
if (getDocumentID.contentEquals(sameDocumentID)) {
databaseProduct.child(getDocumentID).child("Product").child(productID).setValue(items);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
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
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);
I have this code, how can i only get the name value which is logged?I only need to get the name's user logged, thx!
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usuariosRef = rootRef.child("Usuarios");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usuariosRef.addListenerForSingleValueEvent(eventListener);
this gets all names and i only want to get the name's user logged.
It is retrieving all of the names because you are iterating through all of the users. To just get the current user's name, just use the uid of the user. To get the uid of the current user, do this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then you can use this uid to get the current user only.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usuariosRef = rootRef.child("Usuarios");
DatabaseReference current_userRef = usuariosRef.child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = datasnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
current_UserRef.addListenerForSingleValueEvent(eventListener);
Hope this helps!
To display all the users within your database, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usuariosRef = rootRef.child("Usuarios");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usuariosRef.addListenerForSingleValueEvent(eventListener);
The output will be all the names of your logged in users:
Eric
Julian Ramos
//and so on
To get the details only of a single user, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Usuarios").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshotds.child("name").getValue(String.class);
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
So you can now display all your users from your database, or only the logged-in user.