I'm trying to create a Firebase Realtime database project in which the data stored is either type A or type B, etc. This is how it looks like on the console:
Firebase Database
The user can then add more posts, of which are saved to the database then displayed on a ListView.
My Code
final DatabaseReference room = FirebaseDatabase.getInstance().getReference().getRoot();
chatRoomAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, chatList);
lvChatRoom.setAdapter(chatRoomAdapter);
btnAddChatRoomMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strChatRoomName = etChatRoom.getText().toString();
etChatRoom.setText("");
Map<String, Object> chatMap = new HashMap<>();
chatMap.put(strChatRoomName + " -TYPEA", "");
room.updateChildren(chatMap);
}
});
room.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
Set<String> set = new HashSet<>();
while (iterator.hasNext()) {
set.add(((DataSnapshot) iterator.next()).getKey());
}
chatList.clear();
chatList.addAll(set);
chatRoomAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I only want to show for instance, TYPEA (on the database), without displaying the rest. How can I achieve this?
If you want to display only the value of the property TYPEA, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("fruit-TYPEA");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String fruitTYPEA = dataSnapshot.getValue(String.class);
Log.d("TAG", fruitTYPEA);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output will be: orange.
Related
I want to fetch the all uid's of the doctor whose category is "abc"(example) and then store those retrieved uid's into an array list.
I want same results as displayed by the below sql query:
select uid from doctors where category = "abc";
Code for next activity is written below
private void loadDoctors() {
ArrayList<String> uid = getIntent().getStringArrayListExtra("doctor_list");
for (int i =0;i<uid.size();i++){
DatabaseReference doctors = FirebaseDatabase.getInstance().getReference("Doctors").child(uid.get(i));
Adapter = new FirebaseRecyclerAdapter<DoctorModel, DoctorViewHolder>(
DoctorModel.class,
R.layout.doctors_home,
DoctorViewHolder.class,
doctors
) {
#Override
protected void populateViewHolder(final DoctorViewHolder viewHolder, final DoctorModel model, int position) {
viewHolder.doctor_name.setText(model.getName());
Glide.with(Doctors.this).load(model.getProfileimage()).into(viewHolder.doctor_image);
viewHolder.qualification.setText(model.getQualification());
viewHolder.rating.setText(model.getRating());
}
};
Adapter.notifyDataSetChanged();
doctors_list.setAdapter(Adapter);
}
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference doctorsRef = rootRef.child("Doctors");
Query categoryQuery = doctorsRef.orderByChild("category").equalTo("Cardiology");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> uidList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
uidList.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
categoryQuery.addListenerForSingleValueEvent(valueEventListener);
At the end, you'll have a list full of uids. One more thing to note, because Firebease API is asynchronous, you will be able to use that list only inside onDataChange() method.
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 am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!
I want to retrieve data for a specific child, how I can write the code? I try a lot, but it did not work:"([ like in my database here how to get the tasks for specific child like lubna and gets all it's child?
Initialize class variables:
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
private DatabaseReference lubnaRef = mDatabase.child("tasks/Lubna");
And then for testing purposes I am assuming you are calling this in your onCreate method of your activity, you'd add the following assuming you do not have a data model for it:
lubnaRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//These are all of your children.
Map<String, Object> lubna = (Map<String, Object>) dataSnapshot.getValue();
for (String childKey: lubna.keySet()) {
//childKey is your "-LQka.. and so on"
//Your current object holds all the variables in your picture.
Map<String, Object> currentLubnaObject = (Map<String, Object>) lubna.get(childKey);
//You can access each variable like so: String variableName = (String) currentLubnaObject.get("INSERT_VARIABLE_HERE"); //data, description, taskid, time, title
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference lubnaRef = rootRef.child("tasks").child("Lubna");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String title = ds.child("title").getValue(String.class);
Log.d(TAG, title);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
lubnaRef.addListenerForSingleValueEvent(valueEventListener);
In the same way you get the title, you can also get the other values. The output in your logcat will be:
Homework
//and so on
I want to retrieve from firebase database and I already have setup my model to put content in place. I succeeded to retrieve data from one single node but I am unable to do so where I need data from 2 nodes which I want to show it in say Recycler View. However, where I get the success is completely different fragment.
First, I will show you my code for retrieving data from just one node and it is working for me.
Here's the code which is working for one node in different fragment.
Working-Fragment
private void updateArrayList() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_posts))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
data.add(dataSnapshot.getValue(Userpost.class));
adapter.notifyDataSetChanged();
}
Above Code works perfectly.
Now Non-Working Code which doesn't pull anything.
private void updateArrayList() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_posts)).child("profile_photo")
.child(getString(R.string.dbname_user_account_settings))
.child("profile_photo");
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
data.add(dataSnapshot.getValue(Userpost.class));
adapter.notifyDataSetChanged();
}
This is a snapshot for firebase database
Firebase Database Snapshot
I made the question as clear as possible on my end.
Thank you all in advance.
To get those values from a specific post, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postIdRef = rootRef.child("posts").child(postId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String pheading = dataSnapshot.child("pheading").getValue(String.class);
String user_id = dataSnapshot.child("user_id").getValue(String.class);
Log.d("TAG", pheading + " / " + user_id);
DatabaseReference ref = rootRef.child("user_account_settings").child(user_id);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot ds) {
String profile_photo = ds.child("profile_photo").getValue(String.class);
Log.d("TAG", profile_photo);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postIdRef.addListenerForSingleValueEvent(eventListener);
In which postId is the id of the post from which you want to extract the data.