Hello guys I am new to Firebase and I am trying to retrieve all data under Uid.
I store them like this:
mDatabase=FirebaseDatabase.getInstance().getReference().child("Data").child(auth.getCurrentUser().getUid());
//some other code here
DatabaseReference newProduct =mDatabase.child(category).child("Product").push();
newProduct.child("productname").setValue(name);
newProduct.child("date").setValue(date);
My question is how can I retrieve all data under userUid category? Do I need something like .child(*).child("Products")?
What you need to do is use a listener to retrieve that data, something along the lines of
mDatabase.child(category).child("Product").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("productname").getValue;
String date = (String) dataSnapshot.child("date").getValue;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
There you go, now you pulled all that data as Strings.
Also, I would suggest that instead of
auth.getCurrentUser().getUid()
use
String uid = (String) auth.getCurrentUser().getUid();
and just put uid in there instead, that way your code is much cleaner and everytime you need to refer to uid, you have a string for it.
Related
I am new to android programming and wish to explore more on Android programming. My current database tree looks like this and this is how I push the data into the database .
Can any professional teach me on how to retrieve a specific data (e.g. name / phone number) from a specific user in the user list and display them?
Thanks in advance!
Update:
After trying several solutions, the only code that can retrieve the name is this
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("-MA5f3qb0nBBTkViv-pz");
I even tried to assign the UID to a string and put in into the second child like this
String UID = firebaseAuth.getCurrentUser().getUid();
But the code will not run too with the error of "Attempt to invoke virtual method on a null object reference".
To retrieve information try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User userInfo = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Add a reference to node User and then using addListenerForSingleValueEvent you can retrieve the values.
One of my routines in my main activity's onCreate() method is to communicate with the Firebase database to do one of three things:
1) If the user is a returning user, update all of their preferences on Firebase stored using SharedPreferences locally.
2) If the user is new and has no data stored on the cloud (they've never downloaded the app), do nothing.
3) If the user is new but has preferences stored under their unique Facebook profile ID, download their preferences and apply them to the SharedPreferences instance.
I must be missing some key, probably basic, piece of insight into how DataSnapshot works, because I can't get my following code to work:
private void initializeFirebase(){
my_db = FirebaseDatabase.getInstance();
DatabaseReference my_ref = my_db.getReference();
Map<String, ?> values = sharedPreferences.getAll();
if (values.isEmpty()){
final String id = Profile.getCurrentProfile().getId();
my_ref = my_ref.child("userid");
my_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getKey().equals(id)){
data = (Map<String, Object>)dataSnapshot.getValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else {
for (Map.Entry<String, ?> entry : values.entrySet()) {
my_ref.child("userid").child(Profile.getCurrentProfile().
getId()).child(entry.getKey()).setValue(entry);
}
}
}
data is a global Map variable that is always null after getValue() is executed.
My JSON tree is organized as: root -> users -> userid -> each preference as a child node to the userid node. Any help would be appreciated!!
According to the API docs for getValue(), it can return null:
The data contained in this snapshot as native types or null if there is no data at this location.
So, the location you're querying has no data.
I'm going to guess that you didn't want to hard code a value of "userid" in your reference. I bet you mean to use the user's id from the previous line:
final String id = Profile.getCurrentProfile().getId();
my_ref = my_ref.child(id); // id instead of "userid"
I want to retrieve data from my database. For example: I just want to get the username and password from my database, what should I implement next ?
public void loginToSystem(String usernameLogin, String passwordLogin){
usernameLogin = username.getText().toString();
passwordLogin = password.getText().toString();
if(TextUtils.isEmpty(usernameLogin)){
username.setError("Please Input Username");
return;
}
else if(TextUtils.isEmpty(passwordLogin)){
password.setError("Please Input Password");
return;
}
else {
Query query1 = databaseReference.orderByChild("usnername").equalTo(usernameLogin);
Query query2 = databaseReference.orderByChild("password").equalTo(passwordLogin);
//What Should I do Here
}
}
What should I do with the Code.
Ps: I am using the DatabaseReference and am I doing a good way to proceed Login with using this ?
Or I have to separate my data username and password using FireAuth
And Personal Data using Firebase Database
You need to add ValueEventListener to be able to retrieve the data:
Query query1 = databaseReference.orderByChild("username").equalTo(usernameLogin);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String address=datas.child("address").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
Also you can only use one orderByChild with each listener.
You dont need to add the password in the database as it is stored in the firebase auth. Also you are using a random id generated by push(). Since you are using Firebase Auth, then get the userid and add the data inside of it.
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
then you will have:
Users
userid
address: address_here
name: name_here
email:email_here
What you could do is when the user clicks on the login button you could add a ValueEventListener on the node that you want to listen then what you'll get is the whole data from the node and then we could check that if the username and password are contained in the node then you could log in or maybe save the data whichever suits your case.
I have tried the same logic by clicking on a login button and it worked for me. Kindly try the below code.
DatabaseReference ref = mDatabaseReference.child("YOUR NODE NAME");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
HashMap<String,String> map = (HashMap<String,String>)dataSnapshot1.getValue();
if (map.get("username").equals("USERNAME THAT TO BE CHECKED")){
Log.d("Testing","True "+map.get("name"));
}
else {
Log.d("Testing","True "+map.get("name"));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope it works.
this is my first question in Stackoverflow.
I use firebase in my android app, and my DB schema is as follows:
Users schema:
and
Posts schema:
Now, I have used a recyclerview to show the posts by users. I have implemented SingleValueEventListener where I get list of Posts by users and another eventlistener nested inside to fetch the User's name and profile picture.
The code is as follows:
Query query = databaseReference.child("Posts");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren())
{
final PostsPOJO postsPOJO = data.getValue(PostsPOJO.class);
images = postsPOJO.getcontent_post();
//Nested listener to fetch User's name and profile picture from another node "Users/UserID"
final Query userDetails = databaseReference.child("Users/"+postsPOJO.getUserID());
mListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
String username = dataSnapshot1.child("Username").getValue(String.class);
String profilePicturePath = dataSnapshot1.child("ProfilePicture").getValue(String.class);
list.add(new PostsPOJO(postsPOJO.getUserID(),profilePicturePath ,username, postsPOJO.getTimestamp(),postsPOJO.getPostText(),postsPOJO.getLocation(),postsPOJO.getcontent_post()));
Log.d("datalist", postsPOJO.getUserID()+","+profilePicturePath +","+username+","+postsPOJO.getTimestamp()+","+postsPOJO.getPostText()+","+postsPOJO.getLocation()+","+postsPOJO.getcontent_post());
newsFeedListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
userDetails.addListenerForSingleValueEvent(mListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now, the problem is that the first UserID which the nested listener gets, it fetches all the Posts from that particular UserID first and then goes on to the next UserID for example if it gets UserID : 1, then it will give all the posts from that User first and then go on to the next one, if its UserID : 2, vice versa. I want the Posts data by the UserID associated with that post.
I have implemented .orderByKey() but no success.
Thank you.
You can put post Ids under user data like
Users -> 1 -> Posts -> [postId-1,postId-2,postId-3]
I am storing user details 'firstname' and 'lastname' in UserNode. But when i want to retrieve that details then no data is being retrieved. I tried almost all solutions on the internet but nothing solved my problem. Here is my code for retrieving data of the current user:
FirebaseUser userr = FirebaseAuth.getInstance().getCurrentUser();
if (userr != null) {
String name = userr.getDisplayName();
Log.e("value", name);
}
but it says "println needs a message"
I also tried with this but nothing happened:
DatabaseReference DataRef;
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String acctname = (String)dataSnapshot.child("firstname").getValue();
Log.e("name", acctname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
]1
Please help me I am stuck with it
You're reading a collection of user with a ValueEventListener. As the [Firebase documentation for reading lists with a value event](Listen for value events) explains:
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single [child node], the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result.
So in your code:
DatabaseReference DataRef;
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");
DataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String acctname = (String)childSnapshot.child("firstname").getValue();
Log.i("name", acctname);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Using FirebaseUser:
FirebaseUser implements UserInfo and in UserInfo's getDisplayName() documentation says
Returns the user's display name, if available.
So, it is possible that FirebaseUser.getDisplayName() return null when display name is not set. In that case Log.e() receives null as message and therefore prints println needs a message
Using your own structure:
Instead of using type conversion use getValue(Class<T>) like so:
String acctname = dataSnapshot.child("firstname").getValue(String.class);
Please, read how to retrieve data from firebase. I think you have a problem because you don't have Class Model.
Your steps:
Create model UserModel with firstname and lastname field
Use listener (example from docs):
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
See other answers: How to retrieve data from one single userID Firebase Android and retrieving data from firebase android