I develop an android application for students attendance according to their seat numbers. If the student entered his seat number, it will be stored into real time database in fire-base.
Now, what I need to do is to retrieve the empty seat numbers to a list view according to students' information. for example: database has 50 seat numbers entered, but seat number (25) is not in the database then it will be retrieved to the list view.
In general how can I do that with fire-base real time database?
This is how database looks like for one student
You will need to mark seat empty in your db to later only fetch the empty seats. In current situation there is no way to put a query which can retrieve data only for absent students.
Your screenshot is limited so I suggest this structure.
{lectureId}/
seatNumber: {
isEmpty: boolean,
.... your other data
}
Then you will use orderByChild("isEmpty").equalTo(false);
And for querying a set of data from realtime database, have a look at the docs:
https://firebase.google.com/docs/database/web/lists-of-data
you can use a boolean if student is present (present = true).
put this variabble in te object
then you can run a loop on datasnashot for
i < noOfSeats
and show in te ListView with a condition
if (!present){
showInList();
}
Related
Goal: show the list of groups based upon the recent message and when a new message comes, update the chat group list.
Firebase Structure:
Left one structure represents user model: Basically under student key, there is a list of the student then its details along with group ids in which he/she participated.
Right one structure represents the group detail model: Under chat_group key, there is a list of groups with details and also recent message timing.
Solution Tried:
Fetch the group id from the student using the onChildAdded method of firebase DB one by one then fetch its group details using the addListenerForSingleValueEvent method, then store in the list and every time sort it using sort method of array list and then call notifyDataSetChanged method of recyclerview adapter.
Problem with this approach: Too time-consuming and as the number of groups increases processing time also increases.
I think the best solution is to add a new key to the group details model for the students signed up , like that
SignedStudents : "student1 , student2 , student3"
Then you will read data from chat_group directly orderedByChild("recent_message_timeStamp") , then you have to filter it locally to get the groups only related to the specific student to add it to your list like that
String students = model.getStudents();
if (students.contains("student1")) addGroupToYourList();
Can we keep storing data under a single column(if there is any) in firebase-database, for suppose , like in MySQL, there is a column called latitude we can keep storing/updating new data/latitude coordinates in the next row keeping the older ones and so on from a single user. Likewise, can we do it in Firebase-database? If so, how?
Short answer is: The structure does support something similar to columns where you can add new data.
Like ofalvai writes, Firebase is different from MySQL in that it's not table based but more like a JSON tree. So technically there aren't really tables with columns and rows. It's more like an array of arrays. So what you can do is create an "array" called latitude that stores data which you can keep adding to.
Adding to a child called latitude would look something like this on android:
private void updateLatitude(String latitudeID, LatitudeCoordinates latitude_coordinates) {
mDatabase.child("latitude").child(latitudeID).setValue(latitude_coordinates);
}
Where LatitudeCoordinates is a class, latitude is the parent, latitudeID is a unique value for each latitude coordinate.
https://firebase.google.com/docs/database/android/read-and-write
Shows in detail how to communicate with a Firebase database
Firebase Realtime Database is more like a JSON tree, rather than a relational database. Take a look at their documentation on how to (and not to) structure your data.
I want to create an application that any user can add an advert (announce) with something that he wants to sell.
This is the structure of the Real-time Database in Firebase:
- advert
- category
- {uid}
- title
- price
- description
- location
I want to let the user to filter the adverts by category, title, and price.
Currently, I can filter the adverts only by title like this:
FirebaseDatabase.getInstance().getReference()
.child("adverts")
.orderByChild("title")
.startAt("tv")
.limitToFirst(20)
I have 3 questions:
How can i add more "and clauses"? Or how should i structure the nodes to filter more values?
How should I sort the values that i receive from the server in ascending order or descending order depending on uid?
Seems that the method startAt("abc") is not fetching only the children that has contains in the title "tv". Am i doing something wrong? How should I fetch only the children that contains the string "tv"?
On firebase, there is no way to add "AND clauses". You must structure your data in a way that matches your filtering needs.
I believe firebase already sorts the data by uid.
If you want to fetch only the children that contains the string "tv", you should use this query:
FirebaseDatabase.getInstance().getReference().child("adverts").orderByChild("title").startAt("tv").endAt("tv").limitToFirst(20);
I suggest that you watch the Firebase Database for SQL Developers Series. It has the answers for the 3 of your questions
I'm trying to migrate an app I had built which used Parse as its cloud backend. In my Parse backend database, I had a table which stored data as shown below:
Device ID | Contacts
xxxxx001 | "(800)-888-8888"
xxxxx002 | "(800)-888-8858"
xxxxx003 | "(800)-888-8868"
Over here, device ID is the android device ID and the Contacts are an ArrayList of strings which was generated through logic on the device. Basically, the user would select a contact (multiple in future iterations, hence it being an ArrayList, for testing I'm just keeping one item in the list) and that contact is saved for that DeviceID in the backend database. If the same DeviceID changes the contact, the contacts ArrayList in the database corresponding to its DeviceID would be replaced with the new ArrayList.
I'm trying to get something similar set up on Firebase, however right now it seems I only have a global variable on my databse which seems to get updated each time I press my button.
Here is my code for the button:
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mContactsRef = mRootRef.child("contacts");
#Override
protected void onStart() {
super.onStart();
mButtonContactSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mContactsRef.setValue(contacts); //contacts is an arraylist with 1 item
}
});
}
Here is how it looks in Firebase after clicking the button 3 times:
Instead of updating the value, it seems to add another row(?) of to store the current phone number selected. How can I go about setting up a DeviceID->(Objects to be stored per device)
sort of setup?
You're looking for push(), which generates a unique ID for new items.
From the Firebase documentation on reading and writing lists of data:
// Create a new post reference with an auto-generated id
var newPostRef = postListRef.push();
newPostRef.set({
// ...
});
The new items will have complex-looking keys of the form -KTTHEScy82fpfNSCoYN. Read this article on why those are preferred over array indices and (if you're interested) this article that explains the format of these keys.
Consider a different data model
In general though you might want to consider a different data model. What you're storing is a collection of phone numbers. At first sight, storing those in an array-like list seems fine.
But typically you'll want these behaviors for this contact list:
each phone number can only be present once
you need to find whether a given phone number is already in the list
With your current structure you can only see if a number is already in the list by scanning all items in the list. Whenever that is the case, it is a good moment to consider using a set data structure instead.
In Firebase you'd model a set of phone numbers like this:
"contacts": {
"(800)-888-8858": true
"(800)-888-8868": true
"(800)-888-8888": true
}
While this structure initially looks less efficient, it is actually stored more efficiently than the array list in Firebase. And looking up whether an item exists is now a simple existence check instead of having to scan the array. And with this structure it is impossible to store the same number twice.
The goal is : after a user has been logged in , the next activity should display his list of courses.
There is a table of courses in Parse's cloud, but how can I retrieve the correct courses (current user's courses) ?
I've thought of 2 approaches :
1. using getCurrentUser method - but what if there are more than one user in the cache ?
2. save for each course the userName that saved it , and then query for that userName - but how should I know that the currentUser method will return the correct user ?
How can I solve this problem ?
using getCurrentUser method - but what if there are more than one user in the cache ?
There's always one currently logged in user and ParseUser.getCurrentUser() will get it. Well, unless there is no logged in user.
but how should I know that the currentUser method will return the correct user
As above. I don't get what you're confused about.
There is a table of courses in Parse's cloud, but how can I retrieve the correct courses (current user's courses)
and
save for each course the userName that saved it , and then query for that userName - but how should I know that the currentUser method will return the correct user ?
I can think of two approaches here. There may be more. Up to you what you decide to use.
So you have the _User table and the Course table. You can do one of the following:
Add a courses array to each _User and for each _User, store their list of courses there. It should be a list of objectIds, so basically you'll have the ID's of all the courses that _User is registered for. Each Parse object has a limited size in the database so you should use it if you are sure you won't need big amounts of data for each user. If you want to retrieve this, query the _User table by the id of the user and fetch the list of courses.
The "relational" approach: add an UserCourse table that has a userId and a courseId column. Every time you want to add a course for a particular user, you add a new entry in here that holds the id of that user and the id o the course. Similarly to the above, have a query that fetches all the stuff from UserCourse by userId. Note that in this case you'll also need to make sure your query fetches the data from _User and Course. Otherwise you'll just end up with UserCourse entries, which merely store ID's.