I have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());
Related
I do not want numbering to appear, I want the time to appear as written in the code, so what is the reason for such a problem to appear?
deviceModels.add(new DeviceModel(newDeviceName, newDeviceWat, newDeviceUse, currentDateAndTime));
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
databaseReference.child("DeviceInfo").child(currentUser).child(currentDateAndTime).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// data base reference will sends data to firebase.
databaseReference.setValue(deviceModels);
Toast.makeText(MainActivity.this, "تم أضافة الجهاز", Toast.LENGTH_SHORT).show();
dialog.dismiss();
finish();
startActivity(getIntent());
}
It looks like your deviceModels is an array or a List, and this is how the Firebase Realtime Database persists arrays/lists. There is no way to configure it to do it differently, but you can of course use a different data type in your code.
More idiomatic in Firebase is to use the push() method when adding items to a list on the database. To learn more about why that is, have a look at Best Practices: Arrays in Firebase.
In your case you'd write the data for each individual DeviceModel:
databaseReference.push().setValue(new DeviceModel(newDeviceName, newDeviceWat, newDeviceUse, currentDateAndTime));
This will then end up in the database as:
DeviceInfo: {
"IN0r....T2": {
"-N.....": {
deviceId: ...,
deviceName: ...
}
}
}
And that entire list would then map back to a Map<String, DeviceModel> in your Java code.
I keep getting the old values (which no longer is in the database) from my Firebase database. Here is how the database looks right now:
I am getting the info under friendlist. It used to be only one child there with key-value set soosk: true, but now it looks like in the photo. When using addListenerForSingleValueEvent() to my databaseRef, the friendlist retrieved only has soosk: true in it. Here is my code:
mFirebaseDatabaseReference = FirebaseDatabase
.getInstance()
.getReference(
"users/"+FirebaseAuth.getInstance().getCurrentUser().getUid()
);
mFirebaseDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Log.d(TAG, user.getFriendlist().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The method you need to use to have all the values updated is addValueEventListener(). Because you need to listen for more than one value this is the only way to achieve it and to use addListenerForSingleValueEvent().
The most important thing is to remove the listener in your onDestroy method like this:
yourReference.removeEventListener(valueEventListener);
DatabaseReference databaseReference=mDatabase;
String queryText="Hotel";
databaseReference.orderByChild("Coupon")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.
In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html
But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:
DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot val : dataSnapshot.getChildren()){
//I am not sure what record are you specifically looking for
//This is if you are getting the Key which is the record ID for your Coupon Object
if(val.getKey().contains("Hotel")){
//Do what you want with the record
}
//This is if your are querying for the hotel child
if(val.child("hotel").getValue(String.class).contains("Hotel")){
//Do what you want with the record
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}
Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:
DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();
Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");
To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).
This my database in firebase
I want to get the value of page which is equal to 200.
When I tried like that:
DatabaseReference my= userid_database.child("Books").child("Book 1").child("Page");
System.out.println(my);
Output:
https://my-proje-book-timer.firebaseio.com/qpPLvgpM0TMF6vz4Kqw8QaYroG83/Books/Book%201/Page
When I tried like that:
DatabaseReference my= userid_database.child("Books").child("Book 1").child("Page").getKey();
System.out.println(my);
Output:
Page
I don't want to use this:
my.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Because I want to get all values for each Book pages and make a calculation with these values. In this way, I couldn't get the values outside of the method.
If you don't want to use a listener, you can use the REST API to easily make an HTTP query to find the data you want, assuming that it's readable without authentication. If you need authentication, it gets more difficult.
But you're really better off just learning now to make the listeners work for you, even if you're not accustomed to that kind of processing.
I am trying to use the firebase push() function, as I want to add a list off data to an allready existing list. The setValue() function overwrites existing data.
This is what I used to do:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
childref.setValue(getAnsweredQuestions(questionViewList));
This worked, but every time I use this function the data is overwritten and this is not what I want. I tried using the Push function as described by the firebase documation: https://firebase.google.com/docs/database/android/save-data
I am not sure I am doing it right, but it is not working. And this is when I tried to implement the push() function:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
String key = childref.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( key, questionViewList);
mDatabase.updateChildren(childUpdates);
The exception I get is:
com.google.firebase.database.DatabaseException: Failed to parse node with class class scrambled.nl.generationr.QuestionView
And this is weird, since I did not receive this error while doing the setValue method. Can anyone explain what I am doing wrong and how I should push a list to firebase?
edit:
What I can do is:
DatabaseReference childref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
childref.push().setValue(getAnsweredQuestions(questionViewList));
In added the push() here. This works, but instead of just increasing my list, i add another layer in my list so I actually get an array of arrays instead of a longer list.
See here the result:
Saving a List of AnsweredQuestion objects:
This assumes you've followed the rules when designing your AnsweredQuestion.class so that the Java object can be used to store data in Firebase. If you need guidance for that check under the "Basic write operations" heading for saving data in the documentation.
//List of AnsweredQuestions
List<AnsweredQuestion> mAllAnswers;
....
//create the database reference that points to the correct parent node
//where answeres are stored for each user
DatabaseReference ref = mDatabase.child("users").child(uih.getUserData().getUsername()).child("answered_questions");
//Iterate over your List of AnsweredQuestion objects and use push() along with setValue()
//to store a single AnsweredQuestion object to a unique location in your database.
for(AnsweredQuestion answer : mAllAnswers){
ref.push().setValue(answer);
}
Retrieve all answered questions for a user:
//create List to store AnsweredQuestion object
List<AnsweredQuestion> mAllAnswers = new ArrayList<AnsweredQuestion>();
...
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//iterate over datasnapshot to get/store each AnsweredQuestion object
if(datSnapshot.exists()){
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
AnsweredQuestion answer = snapshot.getValue(AnsweredQuestion.class);
mAllAnswers.add(answer);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle error
}
});
There are multiple ways to retrieve the answers for each user, using .addListenerForSingleValueEvent() is just one way. You can also use a FirebaseListAdapter or FirebaseRecyclerAdapter if you wanted to display the answers in a ListView or RecyclerView.