Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I confuse how to set "value", and here is the code
strong text
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
value="hello";
when I set the "value" to "Hello", appear an error
Variable defined in a method only exists in the method. Read more about it in variable scope in java
In your code, the value variable is inside onDataChange. This means that only code inside onDataChange can access it. You are trying to change the value variable from outside onDataChange.
Related
This question already has answers here:
How to return DataSnapshot value as a result of a method?
(6 answers)
getContactsFromFirebase() method return an empty list
(1 answer)
Setting Singleton property value in Firebase Listener
(3 answers)
Closed 1 year ago.
I need to return a read data from Firebase. Here is the code:
private String getInfo(DatabaseReference reference) {
String string = "";
reference.child("xxx").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
string = snapshot.getValue().toString();
// here the log display the correct value I need
Log.i("Log", string);
}
onCancelled() ...
}
});
return string; // HERE THE VALUE IS NULL!!!!
As written above the log show the correct value, but when I try to return it its value becomes null.
It's within the inner block, that's why it happens
Move the return function to the inside of the block so it will show the correct value
First try moving the return string; inside the method body, then if it doesn't help read below.
addListenerForSingleValueEvent() executes onDataChange method immediately and after executing that method once, it stops listening to the reference location it is attached to.
So instead use addValueEventListener(), which keeps listening to the query or database reference it is attached to as mentioned here Read and Write Data on Android
Here is another useful information from the official documentation:
The listener receives a DataSnapshot that contains the data at the
specified location in the database at the time of the event. Calling
getValue() on a snapshot returns the Java object representation of the
data. If no data exists at the location, calling getValue() returns
null.
In this example, ValueEventListener also defines the onCancelled()
method that is called if the read is canceled. For example, a read can
be canceled if the client doesn't have permission to read from a
Firebase database location. This method is passed a DatabaseError
object indicating why the failure occurred.
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 2 years ago.
Improve this question
Here is it I add value about user.
val user = hashMapOf(
USER_CONVERSATIONS to arrayListOf(""),
USER_EMAIL_COLUMN to personEmail,
USER_NAME_COLUMN to personName,
USER_PHOTO_URL_COLUMN to personPhoto.toString(),
USER_ID_COLUMN to personId
)
db.collection("users").add(user)
Which rule do I need to put inside Cloud Filestore or checking inside app?
Here is it my structure: https://imgur.com/a/w0AltSf
Thank you for extended answer!
I would like to do not register my account with new id, and check this in app, answer was given, thank you!
You can request to know if that document exists before inserting it. You can use something like this.
firestore.collection("users").whereEqualTo("id", YOUR_USER_ID)
.limit(1).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
// You can check here if document exist.
// It will be empty if it doesnt.
boolean isEmpty = task.getResult().isEmpty();
}
}
});
This question already has an answer here:
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 4 years ago.
I'm cycling through some children in firebase to see if the value of a key exists, and in my addListenerForSingleValueEvent function the key is found and a global boolean is set to true. However, after the function, the variable is set as false so the program does not enter the second if statement.
referenceClasses.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getKey().compareTo(combinedString) == 0) {
found = true;
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
if(found) {
//...
}
I know found is set to true within the addListenerForSingleValueEvent through various inputs to my database. the boolean is instantiated as
boolean found;
globally, before any other functions. I even tried to implement two functions, one which sets the boolean and another which returns it but I ended up with the same results of the boolean being true within addListenerForSingleValueEvent and false in the if statement. Any ideas?
This is happening because the firebase calls are asynchronous and as a result your program might be hitting the if block before it even enters the onDataChange() method. To see if this is the case, you could put a breakpoint inside onDataChange and a breakpoint on the if(found) line and see which one gets executed first.
If all you are trying to do is execute some code once found is set to true, then you should just move the whole if block inside onDataChange.
Hopefully this helps!
This question already has answers here:
Setting variable inside onDataChange in Firebase (singleValue Listener)
(3 answers)
Closed 5 years ago.
I'm using firebase in my project and i'm trying to figure out how to fix the next issue for few hours already without success,
I have the next code:
// gameIDperm is set as 0 as default
public void GenerateID(){
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if(snapshot.hasChild(gameIDperm))
{
gameIDperm = Integer.toString(Integer.parseInt(gameIDperm)+1);
Log.d("ID XXXX" , gameIDperm); // Here it says the right number
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d("ID YYYYYYYY" , gameIDperm); // Here it says gameIDperm is 0 again
}
How can i make the variable being saved in the current function and not being reset again to default?
Hope you can help!
The code inside of the firebase listener is a callback, it will be called at some point in the future but it is not specified when that will happen.
So what happens is:
You call ref2.addListenerForSingleValueEvent(..)
You execute Log.d("ID YYYYYYYY" , gameIDperm);, at this point the variable has not been changed yet.
Firebase invokes onDataChange(..) at a later date, changing the variable.
You execute Log.d("ID XXXX" , gameIDperm);
In such an asynchronous execution you cannot rely on the order of the code to tell you when things get executed.
In addition you are using the variable gameIDperm to look up a child of the firebase reference, then rewriting that variable with the contents. This is probably not correct.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
In my main class I want to check if there was a change by using a boolean variable:
public class Main {
private boolean change = false;
public boolean getChange() {
return change;
}
public void setChange(boolean change) {
this.change = change;
}
private void method1() {
// some command
setChange(true);
method1();
}
If I want to get this boolean value in my second class, I always get returned "false", no matter if my method1 ran or not.
public class BoolTest {
Main m = new Main();
System.out.println(m.getChange()); // returns "false"
}
You must have two instances of Main. Use the same one. Example:
Main m = new Main();
System.out.println(m.getChange());
m.setChange(true);
System.out.println(m.getChange());
You probably want to share the same instance over multiple classes. Pass the instance to the other classes and use them as expected.