How can I get the last key in Firebase Android? - android

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

Related

How to Simply retrieve all the items and values in Firebase using Android Studio

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
}
}

Android Firebase, Get position of key in node

I want to get data according to user's ranking. First order by user's points and get users position in node. But I can't think of the way to implement this.
First This is my firebase 'users' node
Maybe It will be like 'databaseRef.child("users").orderByChild("points")...'
I don't know from here.
ps. It's not get nth item. It's 'where is the item' ( item's nth )
Thank you!
This can be done by adding a ctr in you dataSnapshot loop
myRef = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = myRef.orderByChild("points");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = dataSnapshot.getChildrenCount();
int i = 0;
// loop through dataSnapshot
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String nickName = childSnapshot.child("nickName").getValue(String.class);
if (nickName.equals(mUser.getNickName()) {
//when nickName would match
int userPlace = total - i;
int points = childSnapshot.child("points").getValue(Interger.class);
//do something here
break;
} else {
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Kindly read
Retrieving Data.
How Data is Ordered
The callback function receives a DataSnapshot, which is a snapshot of
the data. A snapshot is a picture of the data at a particular database
reference at a single point in time. Calling val() / getValue() on a
snapshot returns the a language-specific object representation of the
data. If no data exists at the reference's location, the snapshot's
value is null.
If you want to get all points then check this LOGIC.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("products");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Integer> points = new ArrayList<>();
for (Map.Entry<String, Object> entry : products.entrySet()){
Map singleUser = (Map) entry.getValue();
points.add((Integer) singleUser.get("points"));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
I solve this problem. Android_K.Doe's answer is right. I add some code in his code. Because Firebase database does not give descending query.
final Query query = databaseReference.child("users").orderByChild("points");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
int all = (int) dataSnapshot.getChildrenCount();
Log.d(TAG, "all: " + all);
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String nickName = ds.child("nickName").getValue(String.class);
if (nickName.equals(user.getNickName())) {
Log.d(TAG, "nickName: " + user.getNickName());
int userPlace = i;
Log.d(TAG, "position: " + userPlace);
myInfoRankingNumTxt.setText(Integer.toString(all - (i)) + "위");
break;
} else {
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Update Values within Push firebase android

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

How to retrieve user details by user id inside for loop?

I have structured my firebase database like this:
And this is the way how i would structure my tables in database with SQL if i want to fetch user details by passing id as parameter.
But this is not working as i expected.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String taskName = snapshot.child("name").getValue(String.class);
final String assignedUserId = snapshot.child("assignedUserId").getValue(String.class);
final String categoryId = snapshot.child("categoryId").getValue(String.class);
final Boolean completed = snapshot.child("completed").getValue(Boolean.class);
final String priority = snapshot.child("priority").getValue(String.class);
User user = getUser(assignedUserId);
ProjectTask projectTask
= new ProjectTask(snapshot.getKey(), dataSnapshot.getKey(), taskName, assignedUserId, priority, completed, categoryId, user);
mProjectTaskList.add(projectTask);
}
for (Category category : mCategories) {
mProjectTasksSection = getTasksWithSection(category);
if (mProjectTasksSection.size() > 0) {
mSectionedRecyclerViewAdapter.addSection(new ProjectTaskListAdapter(R.layout.lst_todo_item_v2, mProjectTasksSection,
category, getActivity()));
}
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerProjectTasks.setLayoutManager(linearLayoutManager);
recyclerProjectTasks.setItemAnimator(new DefaultItemAnimator());
recyclerProjectTasks.setAdapter(mSectionedRecyclerViewAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here i have fetched all tasks and now i just need one more parameter and that is user details, but i really don't know how to get it. I'm not really sure if this is the right way. Maybe it would be easier if i store user name instead of user id. Below i will post my code trying to fetch user details by id:
private User getUser(String keyId) {
DatabaseReference databaseReference = AppController.getInstance().getDatabase()
.getReference().child("users").child(keyId);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return null;
}
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
//pass name here that you want to
// if(postSnapshot.getKey().equals("name".equalsIgnoreCase(nameStr)))
//compare
if(postSnapshot.getKey().equals("name"))
{
final String taskName = snapshot.child("name").getValue(String.class);
//taskName =postSnapshot.getValue().toString();
}
}
Please see this post.
Your DatabaseReference is correct but you don't need to use getChildren() method on the 'dataSnapshot`. Just remove the second iteration. You code should look like this:
public void onDataChange(final DataSnapshot dataSnapshot) {
final String taskName = snapshot.child("name").getValue(String.class);
final String assignedUserId = snapshot.child("assignedUserId").getValue(String.class);
final String categoryId = snapshot.child("categoryId").getValue(String.class);
final Boolean completed = snapshot.child("completed").getValue(Boolean.class);
final String priority = snapshot.child("priority").getValue(String.class);
User user = getUser(assignedUserId);
ProjectTask projectTask = new ProjectTask(snapshot.getKey(), dataSnapshot.getKey(), taskName, assignedUserId, priority, completed, categoryId, user);
mProjectTaskList.add(projectTask);
}
Hope it helps.

How to retrieve specific node from firebase database in android

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

Categories

Resources