Related
I don't have much experience with Java. I'm not sure if this question is stupid, but I need to get a user name from Firebase realtime database and return this name as a result of this method. So, I figured out how to get this value, but I don't understand how to return it as result of this method. What's the best way to do this?
private String getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
This is a classic issue with asynchronous web APIs. You cannot return something now that hasn't been loaded yet. In other words, you cannot simply create a global variable and use it outside onDataChange() method because it will always be null. This is happening because onDataChange() method is called asynchronous. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available.
But not only Firebase Realtime Database loads data asynchronously, but almost all modern web APIs also do, since it may take some time. So instead of waiting for the data (which can lead to unresponsive application dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called, and can use the data. In other words, by the time onDataChange() method is called your data is not loaded yet.
Let's take an example, by placing a few log statements in the code, to see more clearly what's going on.
private String getUserName(String uid) {
Log.d("TAG", "Before attaching the listener!");
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
Log.d("TAG", "Inside onDataChange() method!");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Log.d("TAG", "After attaching the listener!");
}
If we run this code will, the output will be:
Before attaching the listener!
After attaching the listener!
Inside onDataChange() method!
This is probably not what you expected, but it explains precisely why your data is null when returning it.
The initial response for most developers is to try and "fix" this asynchronous behavior, which I personally recommend against this. The web is asynchronous, and the sooner you accept that the sooner you can learn how to become productive with modern web APIs.
I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get the data, then log it", I frame the problem as "Start to get data. When the data is loaded, log it". This means that any code that requires the data must be inside onDataChange() method or called from inside there, like this:
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
if(dataSnapshot != null) {
System.out.println(dataSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
If you want to use that outside, there is another approach. You need to create your own callback to wait for Firebase to return you the data. To achieve this, first, you need to create an interface like this:
public interface MyCallback {
void onCallback(String value);
}
Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
myCallback.onCallback(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:
readData(new MyCallback() {
#Override
public void onCallback(String value) {
Log.d("TAG", value);
}
});
This is the only way in which you can use that value outside onDataChange() method. For more information, you can take also a look at this video.
Edit: Feb 26th, 2021
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
Starting from the "19.6.0" version, the Firebase Realtime Database SDK contains a new method called get(), that can be called either on a DatabaseReference or a Query object:
Added DatabaseReference#get() and Query#get(), which return data from the server even when older data is available in the local cache.
As we already know, Firebase API is asynchronous. So we need to create a callback for that. First, let's create an interface:
public interface FirebaseCallback {
void onResponse(String name);
}
And a method that takes as an argument an object of tye FirebaseCallback:
public void readFirebaseName(FirebaseCallback callback) {
DatabaseReference uidRef = databaseReference.child(String.format("users/%s/name", uid))
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
String name = task.getResult().getValue(String.class);
callback.onResponse(name);
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
}
Now, to read the data, you need to simply call the above method passing as an argument an object of type FirebaseCallback:
readFirebaseName(new FirebaseCallback() {
#Override
public void onResponse(String name) {
Log.d("TAG", name);
}
});
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
I believe I understand what you are asking. Although you say you want to "return" it (per se) from the fetch method, it may suffice to say you actually just want to be able to use the value retrieved after your fetch has completed. If so, this is what you need to do:
Create a variable at the top of your class
Retrieve your value (which you have done mostly correctly)
Set the public variable in your class equal to value retrieved
Once your fetch succeeds, you could do many things with the variable. 4a and 4b are some simple examples:
4a. Edit:
As an example of use, you can trigger whatever else you need to run in your class that uses yourNameVariable (and you can be sure it yourNameVariable not null)
4b. Edit:
As an example of use, you can use the variable in a function that is triggered by a button's onClickListener.
Try this.
// 1. Create a variable at the top of your class
private String yourNameVariable;
// 2. Retrieve your value (which you have done mostly correctly)
private void getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// 3. Set the public variable in your class equal to value retrieved
yourNameVariable = dataSnapshot.getValue(String.class);
// 4a. EDIT: now that your fetch succeeded, you can trigger whatever else you need to run in your class that uses `yourNameVariable`, and you can be sure `yourNameVariable` is not null.
sayHiToMe();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
// (part of step 4a)
public void sayHiToMe() {
Log.d(TAG, "hi there, " + yourNameVariable);
}
// 4b. use the variable in a function triggered by the onClickListener of a button.
public void helloButtonWasPressed() {
if (yourNameVariable != null) {
Log.d(TAG, "hi there, " + yourNameVariable);
}
}
Then, you can use yourNameVariable wherever you would like throughout your class.
Note: just be sure you check that yourNameVariable is not null when using it since onDataChange is asynchronous and may not have completed at the time you attempt to use it elsewhere.
Here's a crazy Idea, inside onDataChange, put it inside a TextView with visibility gone
textview.setVisiblity(Gone) or something,
then do something like
textview.setText(dataSnapshot.getValue(String.class))
then later get it with textview.getText().toString()
just a crazy simple Idea.
Use LiveData as return type and observe the changes of it's value to execute desired operation.
private MutableLiveData<String> userNameMutableLiveData = new MutableLiveData<>();
public MutableLiveData<String> getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
String userName = dataSnapshot.getValue(String.class);
userNameMutableLiveData.setValue(userName);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
return userNameMutableLiveData;
}
Then from your Activity/Fragment observe the LiveData and inside onChanged do your desired operation.
getUserName().observe(this, new Observer<String>() {
#Override
public void onChanged(String userName) {
//here, do whatever you want on `userName`
}
});
This is NOT a solution, just a way to access the data outside the method for code organization.
// Get Your Value
private void getValue() {
fbDbRefRoot.child("fbValue").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String yourValue = (String) dataSnapshot.getValue();
useValue(yourValue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// Use Your Value
private void useValue(String yourValue) {
Log.d(TAG, "countryNameCode: " + yourValue);
}
Another way of achieving result (but not necessarily a solution)
Declare a public variable
public static String aPublicVariable;
Set This Variable Inside The Async Method
aPublicVariable = (String) dataSnapshot.getValue();
Use The Variable Anywhere
Log.d(TAG, "Not Elegant: " + aPublicVariable);
In the second method if the async call is not long it will nearly work all the time.
I don't have much experience with Java. I'm not sure if this question is stupid, but I need to get a user name from Firebase realtime database and return this name as a result of this method. So, I figured out how to get this value, but I don't understand how to return it as result of this method. What's the best way to do this?
private String getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
This is a classic issue with asynchronous web APIs. You cannot return something now that hasn't been loaded yet. In other words, you cannot simply create a global variable and use it outside onDataChange() method because it will always be null. This is happening because onDataChange() method is called asynchronous. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available.
But not only Firebase Realtime Database loads data asynchronously, but almost all modern web APIs also do, since it may take some time. So instead of waiting for the data (which can lead to unresponsive application dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called, and can use the data. In other words, by the time onDataChange() method is called your data is not loaded yet.
Let's take an example, by placing a few log statements in the code, to see more clearly what's going on.
private String getUserName(String uid) {
Log.d("TAG", "Before attaching the listener!");
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
Log.d("TAG", "Inside onDataChange() method!");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Log.d("TAG", "After attaching the listener!");
}
If we run this code will, the output will be:
Before attaching the listener!
After attaching the listener!
Inside onDataChange() method!
This is probably not what you expected, but it explains precisely why your data is null when returning it.
The initial response for most developers is to try and "fix" this asynchronous behavior, which I personally recommend against this. The web is asynchronous, and the sooner you accept that the sooner you can learn how to become productive with modern web APIs.
I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get the data, then log it", I frame the problem as "Start to get data. When the data is loaded, log it". This means that any code that requires the data must be inside onDataChange() method or called from inside there, like this:
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
if(dataSnapshot != null) {
System.out.println(dataSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
If you want to use that outside, there is another approach. You need to create your own callback to wait for Firebase to return you the data. To achieve this, first, you need to create an interface like this:
public interface MyCallback {
void onCallback(String value);
}
Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
myCallback.onCallback(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:
readData(new MyCallback() {
#Override
public void onCallback(String value) {
Log.d("TAG", value);
}
});
This is the only way in which you can use that value outside onDataChange() method. For more information, you can take also a look at this video.
Edit: Feb 26th, 2021
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
Starting from the "19.6.0" version, the Firebase Realtime Database SDK contains a new method called get(), that can be called either on a DatabaseReference or a Query object:
Added DatabaseReference#get() and Query#get(), which return data from the server even when older data is available in the local cache.
As we already know, Firebase API is asynchronous. So we need to create a callback for that. First, let's create an interface:
public interface FirebaseCallback {
void onResponse(String name);
}
And a method that takes as an argument an object of tye FirebaseCallback:
public void readFirebaseName(FirebaseCallback callback) {
DatabaseReference uidRef = databaseReference.child(String.format("users/%s/name", uid))
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
String name = task.getResult().getValue(String.class);
callback.onResponse(name);
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
}
Now, to read the data, you need to simply call the above method passing as an argument an object of type FirebaseCallback:
readFirebaseName(new FirebaseCallback() {
#Override
public void onResponse(String name) {
Log.d("TAG", name);
}
});
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
I believe I understand what you are asking. Although you say you want to "return" it (per se) from the fetch method, it may suffice to say you actually just want to be able to use the value retrieved after your fetch has completed. If so, this is what you need to do:
Create a variable at the top of your class
Retrieve your value (which you have done mostly correctly)
Set the public variable in your class equal to value retrieved
Once your fetch succeeds, you could do many things with the variable. 4a and 4b are some simple examples:
4a. Edit:
As an example of use, you can trigger whatever else you need to run in your class that uses yourNameVariable (and you can be sure it yourNameVariable not null)
4b. Edit:
As an example of use, you can use the variable in a function that is triggered by a button's onClickListener.
Try this.
// 1. Create a variable at the top of your class
private String yourNameVariable;
// 2. Retrieve your value (which you have done mostly correctly)
private void getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// 3. Set the public variable in your class equal to value retrieved
yourNameVariable = dataSnapshot.getValue(String.class);
// 4a. EDIT: now that your fetch succeeded, you can trigger whatever else you need to run in your class that uses `yourNameVariable`, and you can be sure `yourNameVariable` is not null.
sayHiToMe();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
// (part of step 4a)
public void sayHiToMe() {
Log.d(TAG, "hi there, " + yourNameVariable);
}
// 4b. use the variable in a function triggered by the onClickListener of a button.
public void helloButtonWasPressed() {
if (yourNameVariable != null) {
Log.d(TAG, "hi there, " + yourNameVariable);
}
}
Then, you can use yourNameVariable wherever you would like throughout your class.
Note: just be sure you check that yourNameVariable is not null when using it since onDataChange is asynchronous and may not have completed at the time you attempt to use it elsewhere.
Here's a crazy Idea, inside onDataChange, put it inside a TextView with visibility gone
textview.setVisiblity(Gone) or something,
then do something like
textview.setText(dataSnapshot.getValue(String.class))
then later get it with textview.getText().toString()
just a crazy simple Idea.
Use LiveData as return type and observe the changes of it's value to execute desired operation.
private MutableLiveData<String> userNameMutableLiveData = new MutableLiveData<>();
public MutableLiveData<String> getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
String userName = dataSnapshot.getValue(String.class);
userNameMutableLiveData.setValue(userName);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
return userNameMutableLiveData;
}
Then from your Activity/Fragment observe the LiveData and inside onChanged do your desired operation.
getUserName().observe(this, new Observer<String>() {
#Override
public void onChanged(String userName) {
//here, do whatever you want on `userName`
}
});
This is NOT a solution, just a way to access the data outside the method for code organization.
// Get Your Value
private void getValue() {
fbDbRefRoot.child("fbValue").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String yourValue = (String) dataSnapshot.getValue();
useValue(yourValue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// Use Your Value
private void useValue(String yourValue) {
Log.d(TAG, "countryNameCode: " + yourValue);
}
Another way of achieving result (but not necessarily a solution)
Declare a public variable
public static String aPublicVariable;
Set This Variable Inside The Async Method
aPublicVariable = (String) dataSnapshot.getValue();
Use The Variable Anywhere
Log.d(TAG, "Not Elegant: " + aPublicVariable);
In the second method if the async call is not long it will nearly work all the time.
I don't have much experience with Java. I'm not sure if this question is stupid, but I need to get a user name from Firebase realtime database and return this name as a result of this method. So, I figured out how to get this value, but I don't understand how to return it as result of this method. What's the best way to do this?
private String getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
This is a classic issue with asynchronous web APIs. You cannot return something now that hasn't been loaded yet. In other words, you cannot simply create a global variable and use it outside onDataChange() method because it will always be null. This is happening because onDataChange() method is called asynchronous. Depending on your connection speed and the state, it may take from a few hundred milliseconds to a few seconds before that data is available.
But not only Firebase Realtime Database loads data asynchronously, but almost all modern web APIs also do, since it may take some time. So instead of waiting for the data (which can lead to unresponsive application dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called, and can use the data. In other words, by the time onDataChange() method is called your data is not loaded yet.
Let's take an example, by placing a few log statements in the code, to see more clearly what's going on.
private String getUserName(String uid) {
Log.d("TAG", "Before attaching the listener!");
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
dataSnapshot.getValue(String.class);
Log.d("TAG", "Inside onDataChange() method!");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Log.d("TAG", "After attaching the listener!");
}
If we run this code will, the output will be:
Before attaching the listener!
After attaching the listener!
Inside onDataChange() method!
This is probably not what you expected, but it explains precisely why your data is null when returning it.
The initial response for most developers is to try and "fix" this asynchronous behavior, which I personally recommend against this. The web is asynchronous, and the sooner you accept that the sooner you can learn how to become productive with modern web APIs.
I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get the data, then log it", I frame the problem as "Start to get data. When the data is loaded, log it". This means that any code that requires the data must be inside onDataChange() method or called from inside there, like this:
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
if(dataSnapshot != null) {
System.out.println(dataSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
If you want to use that outside, there is another approach. You need to create your own callback to wait for Firebase to return you the data. To achieve this, first, you need to create an interface like this:
public interface MyCallback {
void onCallback(String value);
}
Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
databaseReference.child(String.format("users/%s/name", uid)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
myCallback.onCallback(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:
readData(new MyCallback() {
#Override
public void onCallback(String value) {
Log.d("TAG", value);
}
});
This is the only way in which you can use that value outside onDataChange() method. For more information, you can take also a look at this video.
Edit: Feb 26th, 2021
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
Starting from the "19.6.0" version, the Firebase Realtime Database SDK contains a new method called get(), that can be called either on a DatabaseReference or a Query object:
Added DatabaseReference#get() and Query#get(), which return data from the server even when older data is available in the local cache.
As we already know, Firebase API is asynchronous. So we need to create a callback for that. First, let's create an interface:
public interface FirebaseCallback {
void onResponse(String name);
}
And a method that takes as an argument an object of tye FirebaseCallback:
public void readFirebaseName(FirebaseCallback callback) {
DatabaseReference uidRef = databaseReference.child(String.format("users/%s/name", uid))
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
String name = task.getResult().getValue(String.class);
callback.onResponse(name);
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
}
Now, to read the data, you need to simply call the above method passing as an argument an object of type FirebaseCallback:
readFirebaseName(new FirebaseCallback() {
#Override
public void onResponse(String name) {
Log.d("TAG", name);
}
});
For more info, you can check the following article:
How to read data from Firebase Realtime Database using get()?
And the following video:
https://youtu.be/mOB40wowo6Y
I believe I understand what you are asking. Although you say you want to "return" it (per se) from the fetch method, it may suffice to say you actually just want to be able to use the value retrieved after your fetch has completed. If so, this is what you need to do:
Create a variable at the top of your class
Retrieve your value (which you have done mostly correctly)
Set the public variable in your class equal to value retrieved
Once your fetch succeeds, you could do many things with the variable. 4a and 4b are some simple examples:
4a. Edit:
As an example of use, you can trigger whatever else you need to run in your class that uses yourNameVariable (and you can be sure it yourNameVariable not null)
4b. Edit:
As an example of use, you can use the variable in a function that is triggered by a button's onClickListener.
Try this.
// 1. Create a variable at the top of your class
private String yourNameVariable;
// 2. Retrieve your value (which you have done mostly correctly)
private void getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// 3. Set the public variable in your class equal to value retrieved
yourNameVariable = dataSnapshot.getValue(String.class);
// 4a. EDIT: now that your fetch succeeded, you can trigger whatever else you need to run in your class that uses `yourNameVariable`, and you can be sure `yourNameVariable` is not null.
sayHiToMe();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
// (part of step 4a)
public void sayHiToMe() {
Log.d(TAG, "hi there, " + yourNameVariable);
}
// 4b. use the variable in a function triggered by the onClickListener of a button.
public void helloButtonWasPressed() {
if (yourNameVariable != null) {
Log.d(TAG, "hi there, " + yourNameVariable);
}
}
Then, you can use yourNameVariable wherever you would like throughout your class.
Note: just be sure you check that yourNameVariable is not null when using it since onDataChange is asynchronous and may not have completed at the time you attempt to use it elsewhere.
Here's a crazy Idea, inside onDataChange, put it inside a TextView with visibility gone
textview.setVisiblity(Gone) or something,
then do something like
textview.setText(dataSnapshot.getValue(String.class))
then later get it with textview.getText().toString()
just a crazy simple Idea.
Use LiveData as return type and observe the changes of it's value to execute desired operation.
private MutableLiveData<String> userNameMutableLiveData = new MutableLiveData<>();
public MutableLiveData<String> getUserName(String uid) {
databaseReference.child(String.format("users/%s/name", uid))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// How to return this value?
String userName = dataSnapshot.getValue(String.class);
userNameMutableLiveData.setValue(userName);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
return userNameMutableLiveData;
}
Then from your Activity/Fragment observe the LiveData and inside onChanged do your desired operation.
getUserName().observe(this, new Observer<String>() {
#Override
public void onChanged(String userName) {
//here, do whatever you want on `userName`
}
});
This is NOT a solution, just a way to access the data outside the method for code organization.
// Get Your Value
private void getValue() {
fbDbRefRoot.child("fbValue").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String yourValue = (String) dataSnapshot.getValue();
useValue(yourValue);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// Use Your Value
private void useValue(String yourValue) {
Log.d(TAG, "countryNameCode: " + yourValue);
}
Another way of achieving result (but not necessarily a solution)
Declare a public variable
public static String aPublicVariable;
Set This Variable Inside The Async Method
aPublicVariable = (String) dataSnapshot.getValue();
Use The Variable Anywhere
Log.d(TAG, "Not Elegant: " + aPublicVariable);
In the second method if the async call is not long it will nearly work all the time.
I know how to parse a simple DataSnapshot object to any Java class using public T getValue (Class<T> valueType). But after the Firebase 3.0 I am not able to parse the following data to my Java Class, as it contains a custom type instance for which I'm receiving NULL.
NOTE: The same logic was working fine before Firebase 3.0. I suppose its because now Firebase is using GSON instead of JACKSON. Please correct me if I'm wrong
DATA:
{
"address" : "DHA karachi",
"addresstitle" : "DHA karachi",
"logoimage" : {
"bucketname" : "test2pwow",
"id" : "zubairgroup",
"mediaType" : "image/png",
"source" : 1,
"url" : "https://pwowgroupimg.s3.amazonaws.com/zubairgroup1173.png?random=727"
},
"title" : "zubairghori"
}
Group.java
public class Group {
public String address;
public String addresstitle;
public LogoImage logoimage;
public Group(){}
}
LogoImage.java
public class LogoImage {
public String bucketname;
public String id;
public LogoImage(){}
}
Code that read:
Group group = datasnapshot.getValue(Group.class);
It doesn't cast LogoImage part of the database into the logoimage object. We always retrieve null in the logoimage object.
public T getValue(Class valueType)
1.The class must have a default constructor that takes no arguments
2.The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized
Check it from:
this source It'll help you
detail
I'm not sure why that is causing problem for you. This code works fine for me with the data you provided:
DatabaseReference ref = database.getReference("37830692");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Group group = dataSnapshot.getValue(Group.class);
System.out.println(group);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I had the same problem. I solved it by providing not only getters for all the values, but setter too. Hope this helps.
I had the same problem and solved it by making sure that the arguments of the constructor are spelled the same than the elements saved at Firebase. My mistake was that I was setting the key of Firebase with Uppercase letters and object arguments with lowercase letters.
I am implementing Firebase Recyclerview UI in my application. I have implemented a recyclerview adapter and it shows me following exception.
Following is my adapter code :
FirebaseRecyclerAdapter<DataSnapshot, MyHolder> recyclerAdapter = new FirebaseRecyclerAdapter<DataSnapshot, MyHolder>(
DataSnapshot.class,
R.layout.row_slots,
MyHolder.class,
databaseReference.child("slots").child(uid).child(dayOfWeek).child("time")
) {
#Override
protected void populateViewHolder(MyHolder viewHolder, DataSnapshot model, int position) {
System.out.println("Key : "+model.getKey());
}
};
It is showing following exception :
How can I get a snapshot value using FirebaseRecyclerAdapter?
The problem is DataSnapShot is missing a no Argument Constructor so you can not use it directly like this.
Use some other model class instead.
Like this :
Create your own model called FriendlyMessage :
public class FriendlyMessage {
private String text;
private String name;
// Created constructor with no Arguments
public FriendlyMessage() {
}
public FriendlyMessage(String text, String name) {
this.text = text;
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Most important thing we have created constructor with no Arguments
which was missing in DataSnapShot
NOTE : The above model class is just an example for you as you are new in firebase. You can have your own model class with your own type of parameters and all.
The use it like this for your Firebase Recyclerview :
FirebaseRecyclerAdapter mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MyHolder>(
FriendlyMessage.class,
R.layout.row_slots,
MyHolder.class,
databaseReference.child("slots").child(uid).child(dayOfWeek).child("time")) {
#Override
protected void populateViewHolder(MyHolder viewHolder, FriendlyMessage friendlyMessage, int position)
{
}
};
EDIT :
It also matter how you are pushing the data on Database. Do it
directly with your model class.
For example for above model FriendlyMessage push it like this :
FriendlyMessage friendlyMessage = new FriendlyMessage("message", "Username");
databaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage);
Here your child() will be somewhat different from my implementation it is just an example.
For Listening to a particular DataSnapShot :
databaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//The PUSH ID OP WANTED
System.out.println("Push Id ---"+postSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
})
Explaining the above listener. It will give you the DataSnapShot
Object for your every user who is falling inside your child "users". You can access Push id by getKey() method.
firebaser (and author of the FirebaseUI adapters) here
Lots of good answers already. I'd indeed typically recommend creating a Java class that represents your data objects.
But if you're intent on using a DataSnapshot, you can override FirebaseRecyclerAdapter.parseSnapshot to handle the "conversion":
#Override
protected ChatMessage parseSnapshot(DataSnapshot snapshot) {
return snapshot;
}
When initializing your recyclerAdapter, your passing a DataSnapshot.class as your modelClass, wherein a DataSnapshot doesn't really have a Constructor with no parameters which I think is causing the error, also I think that makes a DataSnapshot an invalid modelClass.
As stated in the FirebaseRecyclerViewAdapter for the modelClass:
modelClass - Firebase will marshall the data at a location into an instance of a class that you provide
You should define your own modelClass by creating an object that suites your needs. There's a simple example on the FirebaseRecyclerViewAdapter link that you can check out. Cheers!
EDIT:
As per the comments, I suggested to have your own modelClass object have a DataSnapshot as a parameter. For a simple example of what I'm saying, refer below.
public class ModelClass {
String sampleString;
ModelClass() {
}
ModelClass(DataSnapshot dataSnapshot) {
// Do what you need from the dataSnapshot here
sampleString = dataSnapshot.child("").toString();
}
}
I think from the example above, you would get what I mean. BUT, I'm not sure if this is recommended nor if it's even acceptable. I haven't tried this out before so I'm also not sure if it'll work.
Since this concern is actually different from the one posted. I suggest posting a different one if ever it doesn't work. Happy Coding. Cheers!