Retrieve specific value from Firebase database into string variable - java

I'm trying to retrieve a specific value from a Firebase realtime Database.
The data looks like this:
I want to get the URL value from any of them and then put it into a string variable to use later. This is so that the program does not need to be changed if the download link is changed. The code I have so far is;
DatabaseReference fdb = FirebaseDatabase.getInstance().getReference();
//Query query = fdb.child("URLDOWNLOADS").child("WSSeasons")
fdb.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot url : dataSnapshot.getChildren())
{
LoginInfoFirebasedb DownURL = url.getValue(LoginInfoFirebasedb.class);
String temp = DownURL.dwldURL;
URL1 = temp;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
Some help would be seriously appreciated. I understand this may be a simple problem but I am stumped.

To get each url as a String, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("URLDOWNLOADS");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String url = ds.child("URL").getValue(String.class);
Log.d(TAG, key + " / " + url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);

Related

It does not fetch the required value Firebase Android

It does not fetch the required value and writes null What is wrong with the code please help
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("analysis_Client").child(searchUserId);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
userTotal = ds.child("Total").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
//Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
A picture of the firebase of the way to list the data I want to call both(Total - Rest - ProductNum)

How to retrieve the child data from Firebase?

My database looks as follows, in here I want to retrieve the data inside the mylocation child (see the attached image here). But it is not working.
How to solve that?
My current code looks as this,
private void loadAddress() {
DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Users");
ref.orderByChild("uid").equalTo(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String name=""+ds.child("name").getValue();
String lat=""+ds.child("name2").getValue();
addresstv.setText(name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
To get the data under mylocation, you use an explicit call to that child, like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("mylocation").child("name2").getValue(String.class);
double latitude = dataSnapshot.child("mylocation").child("latitude").getValue(Double.class);
double longitude = dataSnapshot.child("mylocation").child("longitude").getValue(Double.class);
Log.d("TAG", name + "/" + latitude + "/" + longitude);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
5555/79.8571577/6.9448882

Retrieving nested data with ids in firebase?

I am trying to retrive messages from Message node. Each message in messages has an Id. The final result I am trying to achieve is just the message for each user or is there ant better way to store the data as I don't need the key for storing messages, but when I don't include the key the old data gets deleted.
structure of my data
DatabaseReference dbfriends= FirebaseDatabase.getInstance().getReference().child("Users");
dbfriends.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for (DataSnapshot productSnapshot:dataSnapshot.getChildren())
{
Log.i("IDDD",productSnapshot.toString());
Log.i("IDDDDDDDD",productSnapshot.child("Messages").getValue().toString());
String friend=productSnapshot.child("Username").getValue().toString();
Log.i("This is friend",friend.toString());
friends.add(friend);
}
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child("Users").child(uid).child("Messages");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String sender = ds.child("sender").getValue(String.class);
String message = ds.child("message").getValue(String.class);
Log.d(TAG, sender + ": " + message);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
messagesRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
Jeffy: Alic how r you?
Jeffy: Alic how r you?
If you also need the key, simply use:
String key = ds.getKey();

Get user list from table-1, then compare with data from table-2

I get user list from data-1 table as seen in code below.
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference reference = rootReference.child("data-1")
ValueEventListener listener= new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> userList= new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String foundUserId= dSnapshot.getKey();
if (condition) {
userList.add(foundUserId);
//step one completed: userList is full with all necessary users
//Now how to iterate it and compare it with data from table-2?
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
reference.addListenerForSingleValueEvent(listener);
}
So far so good, userList has all the users found from data-1 table. But, I still need to filter out some users and add them to second list called filteredUserList. I need to filter them out by comparing each user to the current user that's saved on the final variable currentUserId
I get list of users from data-1, where each user has a list of users under it like so:
data-1
|_____uid1
| |_____uid3: true
| |_____uid4: true
|
|_____uid25
|_____uid34: true
|_____uid101: true
You see in data-1 each user has a list of users under it, which is how I first get to fill userList.
table-2 has timestamp node, and this is its structure:
table-2
|
|____userid1
| |
| |_____timestamp: timestamp
|
|____userid2
|
|_____timestamp: timestamp
//and so on..
What I want to do is, after I have userList filled with users, I need to check whether each user's timestamp is within a certain time delta from the current user. So I need to iterate the userList, and compare each user's timestamp with the current user's timestamp. But I can't get it to work because in order to get each user's timestamp I need a new onDataChange, and in a for loop, but it's out of scope, and it's also async so it's never working! What would be the correct way to make it work? I've been trying for over a week now. Is it even possible to do that?
The simplest solution I can think of is to get current user timestamp and then query the entire users node and compare current user timestamp with the other user timestamps.
I need to filter them out by comparing each user to the current user
So to solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users")
DatabaseReference uidRef = usersRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long currentUserTimestamp = dataSnapshot.child("timestamp").getValue(Long.class);
String currentUserKey = dataSnapshot.getKey();
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long timestamp = dataSnapshot.child("timestamp").getValue(Long.class);
if(currentUserKey != ds.getKey()) {
if(currentUserTimestamp > timestamp) {
//Do something
} else {
//Do something else
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
Edit: Accoding to the comments and edited question, please see the code below:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference table2Ref = rootRef.child("table-2");
DatabaseReference uidRef = table2Ref.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long currentUserTimestamp = dataSnapshot.child("timestamp").getValue(Long.class);
String currentUserKey = dataSnapshot.getKey();
DatabaseReference currentUserKeyRef = rootRef.child("data1").child(currentUserKey);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference userKeyRef = table2Ref.child(userKey);
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot d : dataSnapshot.getChildren()) {
long timestamp = d.child("timestamp").getValue(Long.class);
if(currentUserTimestamp > timestamp) {
//Do something
} else {
//Do something else
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userKeyRef.addListenerForSingleValueEvent(listener);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
currentUserKeyRef.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Categories

Resources