New Child is not created in firebase - android

i am trying to save new files in numbered order. so there is a count child it get updated but no new child is created
this is the code
databaseReference.child("AdminList").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long key= (long) dataSnapshot.child("count").getValue();
databaseReference.child("AdminList").child("count").setValue(key+1);
databaseReference.child("AdminList").child(String.valueOf(key+1)).child("uid").setValue(uid);
databaseReference.child("AdminList").child(String.valueOf(key+1)).child("Aname").setValue(fname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});``

You are trying to store your data in a "continuous" manner, which is something that JSON objects just aren't designed do. If you are looking for an ordered list, use the priorities property, or you can order the data on the client side. This means that you can just store the data, and then either order client-side, or prioritize the children. I would look to do something like:
databaseReference.child("AdminList").child("uid").setValue(uid);

Use push() to create new child nodes:
databaseReference.child("childName").push();

Related

How to read and store complete Objects in ArrayList from Fire DB

I am currently developing an app with Android Studio.
Now I would like to use the Fire DB, in order to take over the information from the data base in an Arraylist when starting the app. In this case, a node in the database should be saved as an object with its attributes.
The structure of the DB is still flexible. I had the plan to make a numbering of 1 and below the indexes all the attributes of one objet.
If anything else makes sense, this can still be changed
How can I read these and store them in a object per index, which is then put into a Array list?
I had already found several online examples, but none got to work.
Therefore, I would be grateful for an input that I can test and then possibly discuss it.
Please add some sample code to understand us what you do.
You need to do following things,
1) Model Class which contains setter and getter methods (same name as you store in firebase)
If you multiple node inside one object then,
2) RecyclerView and RecyclerAdapter Class
3) DatabaseRefrence to access your data.
example code to retrive data from firebase
final List<Certificates> list=new ArrayList<>();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference().child("Object");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
list.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren())
{
Model model=snapshot.getValue(Model.class);
list.add(model);
}
RecyclerAdapter adapter=new RecyclerAdapter(list,Activity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(CertificatesActivity.this));
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(),DividerItemDecoration.VERTICAL));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
//handle error here
}
});
If you need help to understand tell me.

Retrieve Data using Multiple keys Firebase Realtime Database

I have a list of Keys in a Array List . I want to retrieve data only from those keys but at a same time.
DatabaseReference mDBRef;
List<String> keys = new ArrayList<>();
I tried this with loop but the result coming in Model class is repeated 2 times.
for (int i= 0;i<keys.size();i++)
{
String id = keys.get(i);
Log.d("Keys",id);
mDBRef = FirebaseDatabase.getInstance().getReference().child("Gyms").child(id);
mDBRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
dataSnapshot.getKey();
gyms = dataSnapshot.getValue(Gyms.class);
if (gyms != null)
{
Log.d("Names",gyms.getName());
Toast.makeText(NearMeActivity.this, ""+ gyms.getName(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The Firebase Realtime database doesn't support loading items based on an array of values. You'll have to load each item with a separate call.
While this may convolute your code, it is not nearly as slow as most developers think. This is because Firebase pipelines the requests. For a longer explanation of that, see my answer here: http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786
firebase real time database doesn't support multiple matches. You can see Firestore which is NoSQL and provide some flexibility.
See Firestore: https://firebase.google.com/docs/firestore/
You have to use custom search solution like Elastic Search.

How to add new object to array in Firebase

my data look like this
and I simply want to add an object at index 3. How could I add it there. Is there any way to add an object without iteration or I have to iterate and getChildCount and then append new child("3") and it's data to it.
TransGenderBO transGenderBO = new TransGenderBO();
transGenderBO.setName("pushName");
transGenderBO.setAge(13);
mRef.child("").setValue(transGenderBO);
there is no method in mRef for getting child count and appending new item at 3 position..
Edit after using Frank code but still not working
Query last = mRef.orderByKey().limitToLast(1);
last.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int lastIndex = 0;
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
lastIndex = Integer.parseInt(childSnapshot.getKey());
}
TransGenderBO transGenderBO = new TransGenderBO();
transGenderBO.setName("pushName");
transGenderBO.setAge(13);
mRef.child(""+(lastIndex+1)).setValue(transGenderBO);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(mContext,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
There is a good reason that the Firebase documentation and blog recommend against using arrays in the database: they don't work very well for multi-user applications where users can be offline.
To add the next element to your array here, you'll have to download at the very least the last element of the array to know the index of the next element:
Query last = root.orderByKey().limitToLast(1);
last.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int lastIndex;
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
lastIndex = Integer.parseInt(childSnapshot.getKey());
}
root.child(""+(lastIndex+1)).setValue(true);
}
But this has an inherent race-condition. When multiple users are adding elements to the array at the same time, they may end up writing to the same index.
To prevent this you can use a Firebase transaction. With this you get the current value from a location and in exchange return the new value you want at that location. This ensures that no data is overwritten between users, but means that you have to download the entire array.
And neither of these scenarios works when a user is not connected to the network.
Firebase instead recommends using so-called push IDs, which:
Generate a always-increasing key that is guaranteed to be unique.
Do not require reading any data - they are generated client-side and are statistically guaranteed to be unique.
Also work when a user is offline.
The only disadvantage is that they're not as easily readable as array indexes.
Get your data like this
private ArrayList<TransGenderBO> transGenderBO;
FirebaseDatabase.getInstance().getReference().child("Main")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
transGenderBO = (ArrayList<TransGenderBO>) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and set your value like this
TransGenderBO transGender = new TransGenderBO();
transGender.setName("pushName");
transGender.setAge(13);
FirebaseDatabase.getInstance().getReference().child("Main").child(String.valueOf(transGenderBO.size())).setValue(transGender);
or U can set this way too
TransGenderBO transGender = new TransGenderBO();
transGender.setName("pushName");
transGender.setAge(13);
TransGenderBO.add(transGender);
FirebaseDatabase.getInstance().getReference().child("Main")
.setValue(transGenderBO);

How to retrieve value from the highest/last level node using 'ChildEventListener' from Firebase?

I have several strings stored under specific reference: mReference.child(rID).child(userID2) which I want to retrieve using childEventListener as I am doing some task also when these string gets removed and that is only possible with onChildRemoved of ChildEventListener.
Here's what I have tried:
mReference.child(rID).child(userID2).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("dataHEre", dataSnapshot.getValue().toString());
}
}
The problem is that I'm unable to retrieve data using keys here as dataHEre is logging out:
D/dataHEre: 28.8419556
D/dataHEre: 78.779063
D/dataHEre: 3
D/dataHEre: Railway Colony
D/dataHEre: Sleep
D/dataHEre: 12:36 AM
D/dataHEre: Superman
which are values?
So, I want to know how can I retrieve data here using keys and using ChildEventListener and then assign the data retrieved to various strings?
I think that you are doing your query in the wrong way. onChildAdded method is retrieving you each child of a specific value (userID2 I suppose). If that is what you want, then just use a onValueEventListener() to retrieve the whole dataSnapshot of your userId2 node each time that it changes.
If you want to retrieve the data just once, you should use onSingleValueEventListener(). And OnChildEvent() is used to retrieve lists of data where you want to track each of the child individually. For example if you attach an OnChildEventListener to mReference.child(rID) you will get a OnChildAdded for each userId, what is pretty usefull like for example fill a RecyclerView or a ListView being able to update each item individually together with your Firebase Data.
If i'm not wrong what you want is just get updates of your userId2 reference, in that case attach a OnValueEventListener to that reference and you will get a call each time a value is modified, deleted, or added.
firebaseDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
customPOJO customPOJO = dataSnapshot.getValue(YourCustomPOJO.class);
customPOJO.getName();
customPOJO.getEmail();
customPOJO.getfavoriteFood();
//and so on....
}
#Override public void onCancelled(DatabaseError databaseError) {
}
});

FireBase Android Need 1 value saved under a single user

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());

Categories

Resources