I am trying to use Firebase in my android application. I am following documentation for Saving and retrieving,
But the Sample database(Dragon) which is used in tutorial has different structure than my database.
This is my code for Pushing the data to firebase
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
User userName = new User(socialNum, name, datofBirth, mob1, mob2, healthCondition);
Firebase usersRef = myFirebaseRef.child(name);
Map<String, User> users = new HashMap<String, User>();
users.put(name, userName);
myFirebaseRef.push().setValue(users);
which create database format like this
{
"android" : {
"saving-data" : {
"fireblog" : {
"-JiRtkpIFLVFNgmNBpMj" : {
"Name" : {
"birthDate" : "100",
"fullName" : "Name",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
},
"-JiRv0RmHwWVHSOiZXiN" : {
"mast" : {
"birthDate" : "100",
"fullName" : "mast",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
}
}
}
}
}
I want to Retrieve data from firebase such that, if I put "full Name" in my apps search box, it should retrieve that specific node, so that I can populate that information in Listview.
This is How I am trying to retrieve,
final String Find = find.getText().toString(); //Get text for search edit text box
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
Query queryRef = myFirebaseRef.orderByChild("fullName");
// System.out.println(dataSnapshot.getKey() + "is" + value.get("socialNumber"));
System.out.println(Find);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChild) {
System.out.println(dataSnapshot.getValue());
Map<String,Object> value = (Map<String, Object>) dataSnapshot.getValue();
String name1 = String.valueOf(value.get("fullName"));
//System.out.println(dataSnapshot.getKey() + "is" + value.get("fullName").toString());
if (name1.equals(Find)){
System.out.println("Name" + value.get("fullName"));
}
else{
System.out.println("its is null");
}
}
but It returns all the nodes,
02-19 12:18:02.053 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ name
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {Name={socialNumber=100, birthDate=100, fullName=Name, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {mast={socialNumber=100, birthDate=100, fullName=mast, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
How can i Retrieve specific node so that If I enter fullName = mast, it should retrieve only second node with all the fields in that node.
You're creating a query in this line:
Query queryRef = myFirebaseRef.orderByChild("fullName");
Like that the query orders the child nodes by their fullName value. But it doesn't yet limit what child nodes are returned.
To limit the nodes, you also have to filter. e.g.:
Query queryRef = myFirebaseRef.orderByChild("fullName").equalTo("gooner");
You can also get a range of nodes, by filtering with startAt and/or endAt instead of equalTo.
As Kato commented:
It looks like there is a superfluous level of children. The data is structured as saving-data/fireblog/<record id>/fluff/...actual data... and the fluff layer needs to be removed for those queries to work. You can't query children of children.
If you want to get value of specif node or child node like this
Here if you want to get child node(address) value. You can get it in this way
FirebaseDatabase database;
DatabaseReference myRef;
myRef = database.getReference();
final DatabaseReference orders_Reference = myRef.child("Order");
orders_Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(data.getKey().equals("address")){
String orderNumber = data.getValue().toString();
Log.d("Specific Node Value" , orderNumber);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is another way to retrieve single value from firebase database using Hashmap.
ArrayList<HashMap<String,String>> AllUserscourselist;
String SelectedCourseUserUId;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("User_course_Details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// emergencyContactsList = new ArrayList<>();
AllUserscourselist = new ArrayList<HashMap<String, String>>();
if(dataSnapshot.exists())
{
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
for (DataSnapshot courseUID : postSnapShot.getChildren()){
UsercourseDetails usercourseDetails = courseUID.getValue(UsercourseDetails.class);
HashMap<String, String> map = new HashMap<String, String>();
String user_id = postSnapShot.getKey();
String course_id = usercourseDetails.getcourse_id();
String course_type = usercourseDetails.getcourse_type();
String course_brand = usercourseDetails.course_brand;
String course_number_plate_url = usercourseDetails.course_number_plate_url;
map.put("user_id", user_id);
map.put("course_id", course_id);
map.put("course_type", course_type);
map.put("course_brand", course_brand);
map.put("course_number_plate_url", course_number_plate_url);
AllUserscourselist.add(map);
}
// AllUserscourselist.add(new UsercourseDetails(usercourseDetails.getcourse_type(),usercourseDetails.getcourse_brand(),usercourseDetails.getcourse_number_plate_url(),usercourseDetails.getcourse_id()));
}
Log.e("AllUserscourselist",""+AllUserscourselist);
courseIdList = new ArrayList<String>();
for (int i = 0; i < AllUserscourselist.size(); i++) {
String course_id_list;
course_id_list = AllUserscourselist.get(i).get("course_id")+" "+ AllUserscourselist.get(i).get("user_id");
courseIdList.add(course_id_list);
}
if(courseIdList.size()>0 && courseIdList!=null) {
for (int i = 0; i < courseIdList.size(); i++) { //used
String arr[] = courseIdList.get(i).split(" ");
if (arr[0].equals(coursenumber)) {
SelectedcourseUserUId = arr[1];
getUserEmergencyContacts(SelectedcourseUserUId);
break;
}
}
}
}else{
// NavigationActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_in_left);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Instead of getting all the nodes and then iterating it to get nodes based on value,
just trigger the query provided by firebase.
private void readAllRequestedFormFromFirebaseDb(){
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("App_DB");
DatabaseReference childRef = ref.child("AllRequest");
Query queryRef =
childRef.orderByChild("fullName").equalTo("Jay");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// getting list
for(DataSnapshot dataSnapshot: snapshot.getChildren()){
QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
queryFormModelArrayList.add(post);
/*the above list will have record only
with the provided fullName as Jay*/
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb: "+databaseError );
}
});
}
Click here and find the beautifully written post about this topic
Related
Here is my code. I tried to retrieve it in the log then display it if it
is retrieved. But I think it doesn't seem the right way. And hoping someone could correct me, on how to easily retrieve all the items and values in firebase.
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
.child("FirstRoot");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
//
// Map<String,Object> map = (Map<String,Object>) dataSnapshot.getValue();
// Object material = map.get("item");
// Object value = map.get("value");
// int v = Integer.parseInt(String.valueOf(value));
String material = String.valueOf(dataSnapshot.child("item").getValue());
Log.d("Item:", material);
// String item = dataSnapshot.child("item").getValue().toString();;
//// Float valuee = Float.parseFloat(dataSnapshot.child("valuee").getValue().toString());
// entries.add(new PieEntry(13f, item));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Kotlin
If you want to read data from firebase cloud firestore you want to simple write this code.
// Get a Instance from FirebaseFirestore.
val db= FirebaseFirestore.getInstance()
//Get the user current Id.
val uId = auth.currentUser!!.uid
//Instead of XYZ you have to write your collection name and Id in
//document.
db.collection("XYZ").document(uId)
.get()
.addOnCompleteListener {
if (it.isSuccessful){
//When it is successful you have to do what you want as I have given example that you can understand better through this way you can get userName and you can set into your textView and you can read as many data as you can this is one example.
val documentSnapShot = it.result
val firstName = documentSnapShot.getString("first_name")
tv_Set_ProfileName.text =firstName
}
}
Although it is not so clear from the question where you want to store the data retrieved from firebase .This may work..Have a try....
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
.child("FirstRoot");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
final String data1 = (Objects.requireNonNull(dataSnapshot.child("data1").getValue())).toString();
final String data2 = (Objects.requireNonNull(dataSnapshot.child("data2").getValue())).toString();
final String data3 = (Objects.requireNonNull(dataSnapshot.child("data3").getValue())).toString();
final String data4 = (Objects.requireNonNull(dataSnapshot.child("data4").getValue())).toString();
model_class model = new model_class(data1,data2,data3,data4);
//do whatever you want with your data
entries.add(new PieEntry(13f, data1));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
}
I need to update few nodes in firebase data which is posted from the server end.Need to update the node "is_done" to 0/1 from the device end.I have tried with different solutions but all became futile i.e it is adding a different node outside the "schedule" node.
Code snippet I have tried
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference();
Query query = reference.child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
That's because your database reference still points to the root of your tree. You should assign the desired path to that reference.
Also: You don't need Queries in order to access data directly. You can simply attach a listener to the Database Reference.
private void updatemultiplefirebasedata() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference reference = firebaseDatabase.getReference().child("schedule").child("22-12-2017").child("route").child("1").child("kid").child("21");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
Log.d("Keys",String.valueOf(d.getKey())); //returning all the keys
HashMap<String, Object> result = new HashMap<>();
result.put("is_done", "0");
reference.child(String.valueOf(d.getKey())).updateChildren(result); //update according to keys
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this :
reference.child(d.getKey()).updateChildren(result);
remove String.valueOf from child because your key is integer and you are passing it as string so instead of pointing it to same child it will create new key with String "1"
I want to be able to retrieve everything that is currently held in a Firebase child folder. I write to the database like so;
private void commitPost() {
final String commentInput = commentText.getText().toString().trim();
commentProgress.setMessage("Posting");
commentProgress.show();
String uniqueId = UUID.randomUUID().toString();
commentDB.child(postID).child("Comments").child(uniqueId).setValue(commentInput);
commentProgress.dismiss();
finish();
}
I want to be able to read all values that are currently held in the child folder and then eventually display them in a ListView.
Database JSON;
"Engagement" : {
"-Kne46iBe6ooNFKTv_8w" : {
"Comments" : {
"c323835c-290c-44f3-8070-f9febf698ec9" : "none now!",
"stg15QKZFhNmTCYrgL5PtQ4wxJf2" : "testing"
},
"Likers" : {
"stg15QKZFhNmTCYrgL5PtQ4wxJf2" : "email#email.com"
}
To get the data only from a particular node, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference engagementRef = rootRef.child("Engagement").child("-Kne46iBe6ooNFKTv_8w").child("Comments");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = ds.getValue(String.class);
Log.d("TAG", value + ", ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
engagementRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
none now!, testing,
This is my firebase data Structure.
Now what basically I want to do is, first there is the Id:"cbn". I have pushed the Location with push().setValue(gpsData). Now based on this id = "cbn", I want to add new Latitude and Longitude in the Location child exactly like shown in the figure above by using "push(). Till now my code is:
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
if (busExists) {
// busId = "cbn"
mDatabase.child(busId).child("Location").push().setValue(gpsData);
}
I know I cannot reference busId as child but how can I access that particular node and push my new data to it.
Any Help?
For new question:
public class Users {
private String bus_id;
private HashMap<String, String> coord = new HashMap<>();
public Users() {
}
public String getBus_id() {
return bus_id;
}
public void setBus_id(String bus_id) {
this.bus_id = bus_id;
}
public HashMap<String, String> getCoord() {
return coord;
}
public void setCoord(HashMap<String, String> coord) {
this.coord = coord;
}
}
I implemented it this way:
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Users bus = new Users();
bus.setBus_id(ds.getValue(Users.class).getBus_id());
Log.e("bus id: ", bus.getBus_id()+""); // I got NULL
busList.add(bus.getBus_id());
arrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You'll need to fire a query to get the push ID of cbn and then add the location from there:
Query query = ref.child("Users").orderByChild("Id").equalTo("cbn");
query.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot user: snapshot.getChildren()) {
user.getRef().child("Location").push().setValue(...);
The loop in onDataChange() is needed, since there may be multiple child nodes matching the query. If there can only be one child with a specific Id, consider storing the users under that Id.
Users
cbd
Locations:...
With this structure you can add a new location without first querying:
ref.child("Users/cbn/Location").push().setValue(...);
I want to get the last key of the book node and incremented by a his value++.
I tried this:
myRefVal=databaseBook.getReference("books");
Query lastQuery = myRefVal.limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
idBook = dataSnapshot.getKey();
int counter = 1;
counter = counter + 1;
idBook = idBook + counter;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
At beginning I had justBook 1 ,after click on addbook button I had book2 but when I tried to add a 3rd time a book the previous book2 values crash and the new ones tackes places on Book2.
I'm using idBook to create node book in Firebase Database
myRefBook.child(idBook).setValue(bookInfos);
Instead of using methods to create keys, I used the push method of firebase that allows you to create random key Node:
private void createBook(String nom_livre,String cat_selected, String type_annonce_selected ) {
bookInfos=new Book(nom_livre,cat_selected,type_annonce_selected);
myRefBook.push().setValue(bookInfos);
}
And I used orderByKey() and dataSnap.getKey() to get the last key displayed:
ref.orderByKey().limitToFirst(2).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<String>();
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
keyId = dataSnap.getKey();
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
//Do what you want with the key Node
}} });