This question already has answers here:
Android Firebase retrieve data from child node
(5 answers)
Closed 4 years ago.
I am building an app that will be able to let you answer assessment questions. Now I have a problem on how to save the scores to the current user. I cannot access the child node. This is the real time database. How can I access the child node under Users
You can simply use for loop to access the users just write this code under addOnEventListener:
DataSnapshot Users = datasnapshot.child("Users");
for(DataSnapshot userChild : Users.getChildren()){
DataSnapshot email = userChild.child("email");
String emailString = email.getValue(String.class);
}
Related
I am developing an Android chat application in which I need to order the conversation details by the date. My firebase data structure is mentioned below.
Now I want to retrieve and show the data on the latest date on my RecyclerView from Firebase Realtime Database based on timestamp.
I have tried the following approaches.
final DatabaseReference nm =
FirebaseDatabase.getInstance().getReference("Transaction");
Query query = nm.orderByChild("Date").limitToFirst(5);
;
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listData.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) {
Transaction ld = npsnapshot.getValue(Transaction.class);
listData.add(ld);
}
Tadapter = new TransactionAdapter(listData);
rv.setAdapter(Tadapter);
Log.d(TAG, "Total Count" + Tadapter.getItemCount());
}
}
}
I am developing an android chat application in which I need to order the conversation details by the date.
As I see in your screenshot, your Date property is of type String. This means that you cannot call:
.orderByChild("Date")
And expect to behave as it was a Timestamp. When you order String elements, the order that you get is always lexicographically. This means that Strings doesn't consider any sort of numeric values when sorting, especially when it comes to the dates, even if the dates contain numbers, as your first element does:
Date: "30/7/2021"
So using String values when querying your database it's not an option. However, I see you already have a Timestamp property. Maybe on that property, it was supposed to do the ordering. If that was not the case, I suggest you change the type of the Date property from String to Timestamp, as explained in my answer from the following post:
How to save the current date/time when I add new value to Firebase Realtime Database
Now I want to retrieve and show the data on the latest date on my RecyclerView
This means that most likely you need to reverse the order, meaning that all your transactions have to be displayed in your RecyclerView descending. In this case, there are a few options that you have, either on the server or on the client.
Assuming that you have changed the type of your Date property from String to Timestamp, then you can simply consider storing an inverted Timestamp value like this:
Firebase-root
|
--- transactions
|
--- 1
|
--- Date: 1627714194
|
--- invertedDate: -1627714194
See, the invertedDate property holds a negative value. Since by default, the elements are ordered ascending, to be able to order the transaction desecendiong, you should simply use:
Query query = nm.orderByChild("invertedDate").limitToFirst(5);
On the other hand, there are some workarounds that can be made to achieve the same thing on the client, as explained in my answer from the following post:
How to arrange firebase database data in ascending or descending order?
Query query = nm.orderByChild("Date").limitToFirst(5);
Firebase realtime database sorts in ascending order that means those 5 nodes that you'll receive will be the oldest.
I want to retrieve and show the data in latest date
Try using limitToLast instead which will return the last 5 documents after ordering the nodes by Date field i.e. the 5 latest nodes.
Query query = nm.orderByChild("Date").limitToLast(5);
You can read more about that at sorting and filtering data.
This question already has answers here:
shopping cart for non registered users
(6 answers)
Closed 3 years ago.
I have a doubt to storing data in database without login like e-commerce app.
In back-end the data is store by userID to store data but client side is the app used without login and the product can be add to cart and add to wish list so how can that possible to store data in android.Any help or idea it will more helpful.Thanks
Find the below code
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); //0 - for private mode
Editor editor = pref.edit();
For storing the data
editor.putString("key_name", "string_value"); // Storing string
editor.commit(); // commit changes
For Retrieve
pref.getString("key_name", null); // getting String
To Clear
editor.remove("Key_name"); // will delete key name
editor.commit(); // commit changes
You can either store the temporary data in SharedPrefs or in the SQLite database using Room.
When the user adds/removes the product simply update the database or prefs and when user wants to buy move to the login screen > after successful login read the data from the database and proceed as you want.
When the user clears the cart or wishlist, clear the respective tables.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm developing an app in which each user must log-in first then they are able to add some objects . every objects they create will be save on firebase . but i want to separate user's obeject ! for example if user A save X and user B save Y , they must only access to their objects(user A must only have access to X) , but i don't know why anybody adds anything others have access to it ! got any idea?
in order to achieve your criteria , add an child attribute to your object node called user (the user who added that object) and then you could do a filter while requesting the data this way :
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference("Object");
Query query = mDatabaseReference.orderByChild("user").equalTo("the_user_name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
//here you get your object data
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you're trying to ensure that users can only access their own data, have a look at Firebase's server side security for Firestore, or for Realtime Database. These allow you to determine what data each user can access by specifying rules that are enforced on the server, so that they can't bypassed by any malicious client.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am using dataSnapshot to get a value from my Firebase Database, but I keep getting a null reference error. The path to my firebase is correct and I have Datasnapshot defined, so I am not too sure why this error is coming up.
Here is the snippit that is giving me issues
User user = new User();
String username;
username = (String) datasnapshot.child("Users").child(uid).child("userName").getValue();
user.setusername(username);
navuserName.setText(username);
and this is the error that it is giving me.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DataSnapshot com.google.firebase.database.DataSnapshot.child(java.lang.String)' on a null object reference
I have Datasnapshot dataSnapshot; defined in the class but the error is being thrown. Any suggestions?
Your variable dataSnapshot is not initialized. It's value is null. You need to initialize the variable before you can use it's methods.
CONTEXT :
Hi, I'm currently working on an Android project backed by Firebase.
I have set up a denormalized data structure that relates polls to users (many-to-many relationship) via way of votes. Here is an image displaying the votes path of my database. The structure is as follows :
votes -> [pollUid] -> [votePushuid] -> vote object
So in this example we have a single poll that has 4 votes.
I want to run a check to see if a user has already voted on a poll. In order to do this I fetch the pollsUid, then run through its votes to see if any of them contain the voterUid property == to their user uid.
This is done as follows :
FirebaseHandler.getInstance().getMainDatabaseRef()
.child(FirebaseConstants.VOTES) //votes root
.child(pollKey) //polluid
.orderByChild("voterUid")
.equalTo(FirebaseHandler.getInstance().getUserUid())
.limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
If the datasnaptshot exists then we know that the user has already voted on this poll and can handle it in the Java logic.
PROBLEM :
The datasnapshot received by onDataChange is always null (ie does not exist) when searching for a specific user's vote on a specific poll. I know for a fact that the vote exists in the db through inspecting the data, and that the userUid is correct via debugging. Removing the equalTo and limitToFirst returns all of the votes for the poll without a problem so clearly the stem of the ref is correct. This implies to me that the issue is created by one of the two methods just mentioned. Even stranger is the fact that this approach does work at certain times, but not at others.
QUESTION :
How do I return a list of firebase stored objects filtered by a grandchild property? If this is not possible what would be the more appropriate datastructure for this problem?
On a further note I've seen people taking the approach of using Query instead of Databasereferences. Perhaps this might have something to do with the current issue.
Your query is correct. I have no problem running that query using my own DB. It's probably the userId doesn't match. DatabaseReference extends Query, that's why you can access Query's methods.
A database structure alternative would be
{ "users_votes": {
"<userId>": {
"<pollId1>" : true,
"<pollId2>" : true,
"<pollId3>" : true
}
}
}
Set the value to that node once the user voted to a poll.
To check if the user has voted for a poll
usersVotesRef.child(FirebaseHandler.getInstance().getUserUid())
.child(pollKey).addListenerForSingleValueEvent(valueEventListener);