SingleValueEvent Showing null - java

Query sqlite = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId);
sqlite.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("Message")) {
String msg = dataSnapshot.child("Message").getValue().toString();
String from = dataSnapshot.child("From").getValue().toString();
String time = dataSnapshot.child("Time").getValue().toString();
} else {
Toast.makeText(getApplicationContext(), "NULLLL", Toast.LENGTH_SHORT).show();
}
Database
This is the most basic thing in the database. I have never got a problem with childEvent or valueEvent and i want a single event for now and I'm not able to fetch.
There is no error because i have put an if statement and it shows toast as null which means dataSnapshot doesn't have a child named messages but it's right there. I tried putting a for loop too, but didn't work

You have not given the full reference. There is a list of push keys and you have to use a foreach loop.
Query sqlite = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId);
sqlite.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot vinSnapshot : dataSnapshot.getChildren()) {
if (vinSnapshot .hasChild("Message")) {
String msg = dataSnapshot.child("Message").getValue().toString();
String from = dataSnapshot.child("From").getValue().toString();
String time = dataSnapshot.child("Time").getValue().toString();
} else {
Toast.makeText(getApplicationContext(), "NULLLL", Toast.LENGTH_SHORT).show();
}
}
Or you can store all data into ArrayList then perform your task.

Related

Delete FireBase Value Without Knowing The Key Name

So I am working on the memories Firebase app and there is a stage where the user can upload photos to his memory. Each photo has uniq name "ImgLink0","ImgLink1",etc..
The function I am working on is to delete a specific photo when I am pressing a long click, but I can't reach the image in Firebase.
I tried like below but I got stuck because I can't identify the image key:
mDatabase.child(userUID).child("Memories").child(memoryName).child("Images").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot imageSnapshot : dataSnapshot.getChildren()) {
String imagesKey = imageSnapshot.getKey();
String imagesValue = (String) imageSnapshot.getValue();
Log.e("Test","" + imagesKey + "" + imagesValue);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
And this is the data structure:
I tried using query too but with no success because I don't have the image key.
Thank you for any help :)
To delete a node from the database, you need to know the completely path to that node.
Assuming you do know the URL of the image to delete, but not the key (ImgLink1 or ImgLink2) that is stored under, you're going to have to use a query to look up that key.
Something like:
DatabaseReference ref = mDatabase.child(userUID).child("Memories").child(memoryName).child("Images");
Query query = ref.orderByValue().equalTo("URL of the image")
query..addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot imageSnapshot : dataSnapshot.getChildren()) {
imageSnapshot.getRef().removeValue();
}
}
...
Also see these related answer:
deleting specific post in database(by post node) but it deletes entire database_table
How can i remove all fields and values by using key value or a field key from firebase realtime database?
To remove the second URL for example, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference imageToDeleteRef = rootRef
.child(uid)
.child("Memories")
.child("TestMem")
.child("Images")
.child("ImgLink1");
imageToDeleteRef.removeValue().addOnCompleteListener(/* ... */);
So I have created a reference that points exactly to ImgLink1 node and then I called .removeValue() on reference in order to delete it. So there is no need to read the value in order to perform a delete operation.
If you want to read the URL, please use these lines:
imageToDeleteRef.addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
String url1 = task.getResult().child("ImgLink1").getValue(String.class);
Log.d("TAG", url1);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
https://firebasestorage.googleapis.com...

Firebase get reference by value

I have Firebase node that look like this
How can i make a condition if (name.equalsTo("someValue") to scan database inside campus and get reference to node with key? I this case, i want to get reference or key of kazjap
To find the node under /campus/building where name has a certain value, you can use a query like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("campus/building");
Query query = ref.orderByChild("name").equalTo("someValue");
And then read the results of the query with:
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
for (DataSnapshot childSnapshot: task.getResult().getChildren()) {
Log.d("firebase", String.valueOf(childSnapshot.getKey()));
}
}
}
});
Or:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
// Handle the data
Log.d("TAG", childSnapshot.getKey())
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting User failed, log a message
Log.w("firebase", "Error getting data", databaseError.toException());
// ...
}
});
Firebase queries only work on direct child nodes, so this only works if you know the /campus/building part of the path already. There is no way to search across the entire campus for a building by its name in any campus. For more on that, see Firebase Query Double Nested

Why is my application not catching any data from Firebase?

I am working on my login screen.
However, when I run the code after filling both ID and pw, the userId (code below) is still null.
foundUser = dataSnapshot.getValue(User.class);
userId = foundUser.getId();
userPw = foundUser.getPw();
My application is definitely connected to the Firebase. However, when I debug the code, I can see
W/ClassMapper: No setter/field for exampleuserID found on class com.example.hellobook.User
Shouldn't this
for (DataSnapshot ds : dataSnapshot.getChildren()) {
foundUser = dataSnapshot.getValue(User.class);
be
for (DataSnapshot ds : dataSnapshot.getChildren()) {
foundUser = ds.getValue(User.class);
You have put wrong Reference of Database.
DatabaseReference ref = database.getReference().child("hellobookdatabase").child("User").child(id);
Now you need make little changes in your Condition.
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
foundUser = dataSnapshot.getValue(User.class);
userId = foundUser.getId();
userPw = foundUser.getPw();
if (userId!=null && userId.equals(id)) {
if (userPw.equals(psw)) {
startActivity(new Intent(LoginScreen.this, LandingScreen.class));
}
}
else {
Toast.makeText(LoginScreen.this, "Wrong ID or password. Try again", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled (DatabaseError error) {
#NonNull DatabaseError databaseError; }
});
The reason Why your query not working :
Your reference wasn't proper.
Your valueEventlistener was searching user id in hellobookdatabase instead of User child.
Any other query related to this just Comment down.
Try
Change this
DatabaseReference ref = database.getReference("User")

How can I get the value of an arraylist that is updated inside an addValueEventListener?

I want to show a listview from the ArrayList I am getting by the query.
The ArrayList pt in addValueEventListener becomes null outside the addValueEventListener although the ArrayList is declared as a static property.
Is there any way to get the values of the ArrayList outside this eventlistener?
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot!=null) {
Log.e("TAG", String.valueOf(dataSnapshot.child("uid").child("Name")));
int i=0;
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("Name").getValue(String.class);
Pt.add(userName);
//Toast.makeText(getApplicationContext(), dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Datasnapshot is null", Toast.LENGTH_SHORT).show();
}
}
Try this code..
private List<String> stringList=new ArrayList<>(); // define as class level
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot!=null) {
Log.e("TAG", String.valueOf(dataSnapshot.child("uid").child("Name")));
int i=0;
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("Name").getValue(String.class);
Pt.add(userName);
//Toast.makeText(getApplicationContext(), dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Datasnapshot is null", Toast.LENGTH_SHORT).show();
}
}
ArrayAdapter<String>adapter=new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,stringList);
listView.setAdapter(adapter);
Your Pt list will always be empty outside the onDataChange() due the asynchronous behavior of this method. This means that by the time you are trying to use the Pt list outside this method, the data hasn't finished loading yet from the database and that's why is not accessible.
A quick solve for this problem would be to use the Pt list only inside the onDataChange() method or if you want to use it outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

How to get value of Child of childs from firebase in java

From this I want take the value of email from mailID and subject, title from mailText.i'm able to access the value of single child but when it show null with when try get with all three.
Following code working for single child:
DatabaseReference databaseRef = database.getReference("/");
databaseRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> email = new ArrayList();
for (DataSnapshot sd: dataSnapshot.getChildren()) {
String emailStr = sd.child("email").getValue(String.class);
email.add(emailStr);
System.out.println(email);
}
latch.countDown();
}
Above code gives me array contain the all email like that i want to take value of email,title and subject.
Assuming that the new node is a direct child of your Firebase root, to achieve what you have explained in your comments, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference newRef = rootRef.child("new");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.child("mailID").getChildren()) {
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
Log.d("TAG", email + " / " + name);
}
for(DataSnapshot ds : dataSnapshot.child("mailText").getChildren()) {
String title = ds.child("title").getValue(String.class);
String subject = ds.child("subject").getValue(String.class);
Log.d("TAG", title + " / " + subject);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
newRef.addListenerForSingleValueEvent(valueEventListener);
As you see, you need to attach a listener one step higher in your tree hierarchy and to loop throught the children using getChildren() method twice.
You need to change the database structure(there is no join in firebase), to be able to query and get the required data:
new
mailId
email: userx#gmail.com
name:userx
title: test title
Body: test body
Then you will be able to retrieve the required data for the user.
You can also use Queries to be able to get the related data, example:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("new");
ref.orderByChild("email").equalTo("userx#gmail.com");

Categories

Resources