I'm starting to use firebase and everything looks great but I have 50k records to show inside a recyclerview and I can't figure out how to paginate or something similar because load everything at once takes too much time.
I used childEventListener and FirebaseUI as well with no luck.
UPDATE 1:
Finally I got working for the update 1, this is not the best solution for this but I think I'm going to make some changes later.
private String lastKey = null;
private List<Comment> commentList = new ArrayList<>();
private final static int QUERY_LIMIT = 20;
private int page = 0;
private void loadComments() {
page++;
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
commentList.add(comment);
adapter.notifyDataSetChanged();
lastKey = String.valueOf(comment.getTimestamp());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
if (lastKey != null) {
commentList.clear();
adapter.notifyDataSetChanged();
comments.child(id_post).orderByChild("timestamp").endAt(lastKey).limitToLast(QUERY_LIMIT * page).addChildEventListener(childEventListener);
} else {
comments.child(id_post).orderByChild("timestamp").limitToLast(QUERY_LIMIT).addChildEventListener(childEventListener);
}
}
You can add a value event listener to limit the number of of results you would like to receive, here is a quick example from firebase-ui
ref.limitToLast(5).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot msgSnapshot: snapshot.getChildren()) {
Chat msg = msgSnapshot.getValue(Chat.class);
Log.i("Chat", chat.getName()+": "+chat.getText());
}
}
Use the method limitToLast(5) to get the last 5 objects that were added. Other methods with regards to this include limitToFirst(), limitToLast(), startAt(), endAt(), and equalTo()
More information can be found Here.
I am using this method to show 8 Million Records stored in the Real-time Database, 50 at a time with pagination.
private void getUsers(String nodeId) {
Query query;
if (nodeId == null)
query = FirebaseDatabase.getInstance().getReference()
.child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
.orderByKey()
.limitToFirst(mPostsPerPage);
else
query = FirebaseDatabase.getInstance().getReference()
.child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
.orderByKey()
.startAt(nodeId)
.limitToFirst(mPostsPerPage);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel user;
List<UserModel> userModels = new ArrayList<>();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
userModels.add(userSnapshot.getValue(UserModel.class));
}
mAdapter.addAll(userModels);
mIsLoading = false;
}
#Override
public void onCancelled(DatabaseError databaseError) {
mIsLoading = false;
}
});
}
You also don't have to store the last key separately.
If you are not able to understand it fully then you can read the blog post here which explains everything.
Related
I have a problem after I add another table to my firebase database. it gives me following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type ...
here is my code, which works fine if I have database like this:
and code:
Main activity code:
rvOrder = (RecyclerView) findViewById(R.id.rvOrders);
rvOrder.setLayoutManager(new LinearLayoutManager(this));
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
rvOrder.setAdapter(myAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
rvOrder.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase helper code:
public class FirebaseHelper {
DatabaseReference databaseReference ;
Boolean saved = null;
ArrayList<Order> orders = new ArrayList<>();
public FirebaseHelper(DatabaseReference databaseReference) {
this.databaseReference = databaseReference;
}
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
private void fetchData(DataSnapshot dataSnapshot) {
orders.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
}
public ArrayList<Order> retrieve() {
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return orders;
}
If I change my code to this (which I saw in this question link to the question ):
in Main activity:
databaseReference= FirebaseDatabase.getInstance().getReference();
to
databaseReference= FirebaseDatabase.getInstance().getReference().child("Orders");
and in firebasehelper:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
to
System.out.println(dataSnapshot.getValue(Order.class));
Order order = dataSnapshot.getValue(Order.class);
orders.add(order);
then I am able to add another tables to database but I just get only the last item from the Orders table.
I want to add many tables with multiple items into the database and also I want to get all items from the "Orders" table.
Can anybody suggest me anything?
In your first code snippet you read from the root of the database. Since you're trying to read orders, you should read from /Orders instead:
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
//myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
//rvOrder.setAdapter(myAdapter);
databaseReference.child("Orders").addValueEventListener(new ValueEventListener() {
Now in your onDataChange you can read the orders by looping over them. Since you already do precisely that in FirebaseHelper.fetchData, you can call that method:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
}
Now all that is left is to wire up the data from firebaseHelper.orders to an adapter and the view:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
myAdapter=new MyAdapter(this,firebaseHelper.orders);
rvOrder.setAdapter(myAdapter);
}
This last step will require that you make FirebaseHelper.orders public, and probably some of the variables must be final.
I think you need to update this method accordingly:
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
Try to change:
databaseReference.child("Orders").push().setValue(order);
To:
databaseReference.child("Orders").child(order.getId).setValue(order);
Also, to retreive all Orders keep using the enhanced loop:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
How do I search for users based on their usernames? I have looked at numerous SO posts on this matter but am still unable to achieve what I want to do.. I have tried to apply what I saw in those posts and is shown below:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
usersRef.orderByChild("username")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
searchList = new ArrayList<>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
Log.d("USER: ", "" + user.getUsername());
searchList.add(user);
}
adapter = new UserCardAdapter(getContext(), searchList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("onQueryTextChange: " ,databaseError.getMessage());
}
});
However, all users are still retrieved. I have seen the usage of startAt() and endAt() supposedly work for others on other posts but I cannot manage to get it to work for me..
This is how the user data is stored:
User Data Structure
You almost done right but you should add addListenerForSingleValueEvent after the database reference that already apply orderBy() , startAt(), endAt() like this.
usersRef.orderByChild("username")
.startAt(queryText)
.endAt(queryText+"\uf8ff")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
searchList = new ArrayList<>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
Log.d("USER: ", "" + user.getUsername());
searchList.add(user);
}
adapter = new UserCardAdapter(getContext(), searchList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("onQueryTextChange: " ,databaseError.getMessage());
}
});
Your use of orderBy(), startAt(), and endAt() is correct according to the documentation.
But the addListener method must be applied directly to the object returned by the chain of orderByChild(), startAt(), and endAt() methods, and not in a new statement on the DatabaseReference retrieved with ... .getReference("users").
If you use a ChildEventListener:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
usersRef.orderByChild("username")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
.addChildEventListener(new ChildEventListener() {
List<User> searchList = new ArrayList<>();
#Override public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
Log.d("USER: ", "" + user.getUsername());
searchList.add(user);
}
#Override public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override public void onCancelled(DatabaseError databaseError) {}
});
I am having a hard time with figuring out how to query my Firebase database. Here is what it looks like.
And here is my code:
//RETRIEVE
public ArrayList<Spacecraft> retrieve()
{
String myUserId = acct.getId();
//db.addChildEventListener(new ChildEventListener() {
db.child("/users/uid").equals(myUserId)
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//fetchData(dataSnapshot);
fetchData(dataSnapshot);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
adapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
So db.addChildEventListener will retrieve the entire database. But what I want is to only retrieve data for users whose uid is equal to String myUserId. And I want to sort in ascending order by Level. I have read the docs and watched videos but I cannot figure it out. Any help would be appreciated.
Query query = db.child("users").orderByChild("uid").equalTo("myUserId");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot userSnapshot: snapshot.getChildren()) {
System.out.println("User "+userSnapshot.child("uid").getValue());
}
}
...
But if you're frequently accessing the data by UID, you're off restructuring your database to store all users under their own UID:
users
myUserId
Level: 2
NumCorrect: 8
You can then read the data with:
db.child("users/myUserId").addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
fetchData(dataSnapshot);
}
For more on Firebase queries, see the Firebase documentation on sorting and filtering data. Since you're new to NoSQL, I also recommend reading NoSQL data modeling and viewing Firebase for SQL developers.
You can reverse the array list
ArrayList<UserModel> user_list = new ArrayList<>();
for (DataSnapshot snapshot :dataSnapshot.getChildren()) {
UserModel userModel = snapshot.getValue(UserModel.class);
user_list.add(userModel);
Collections.reverse(user_list);
}
After create data on Firebase. I try retrieving data from Firebase. But I have problem, I think may be Log.d(TAG,list.size()) run before ref.addChildEventListener(childEventListener); complete. Who can help me ?
public class NewFirebase extends AppCompatActivity {
List < Product > list = new ArrayList < > ();
private static final String TAG = "Firebase";
DatabaseReference ref;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
ref = FirebaseDatabase.getInstance().getReference();
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Product comment = dataSnapshot.getValue(Product.class);
for (DataSnapshot child: dataSnapshot.getChildren()) {
Product post = child.getValue(Product.class);
list.add(post);
}
// ...
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
}
};
ref.addChildEventListener(childEventListener);
Log.d(TAG, list.size() + "");
}
class RetrievingData extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...voids) {
return null;
}
}
}
You need to take a second approach to how you are structuring your code, or even take a look at the definition of callback/listener itself.
The addChildEventListener() method assigns a callback and initiates a query for retrieving the result. That is, of course, done in background.
Using listeners will never work that way, that's why they were made for, to don't follow line-by-line execution. If you want to get some result from them, you need to put the code inside their methods, which is when they give you some response. Can take milliseconds, seconds, even minutes, but don't expect to be so immediate to be quicker than the execution of the next line that it was posted to execution.
Take a look at https://www.firebase.com/docs/android/guide/retrieving-data.html.
If you want to see the size of the list that you get from Firebase database, you should use addValueEventListener instead of addChildEventListener
List<Product> commentList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
Product comment = postSnapshot.getValue(Product.class);
commentList.add(comment);
}
// here you can print the size of your list
Log.d(TAG,list.size())
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
I want to retrive the id that generated by firebase when I pushed value to it like next
I want to retrieve "-KGdKiPSODz7JXzlgl9J" this id for that email
I tried by getKey() but it return "users"
and when user get value it return the whole object from the id to profile picture and that won't make me get it as User object in my app
how solve this ?
Firebase users = myFirebaseRef.child("users");
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getKey();
Log.d("User",dataSnapshot.getRef().toString());
Log.d("User",dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("User",firebaseError.getMessage() );
}
});
You can read the key from push() without pushing the values. Later you can create a child with that key and push the values for that key.
// read the index key
String mGroupId = mGroupRef.push().getKey();
....
....
// create a child with index value
mGroupRef.child(mGroupId).setValue(new ChatGroup());
mGroupId contains the key which is used to index the value you're about to save.
UPDATE 1:
it can obtain also by one line
String key = mDatabase.child("posts").push().getKey();
//**************************************************************//
after searching and trying a lot of things i came to 2 ways to do that
.
1. first one to get the key when i upload the post to the server via this function
public void uploadPostToFirebase(Post post) {
DatabaseReference mFirebase = mFirebaseObject
.getReference(Constants.ACTIVE_POSTS_KEY)
.child(post.type);
mFirebase.push().setValue(post);
Log.d("Post Key" , mFirebase.getKey());
}
i used it in my code to get the key after i have already pushed it to node for it in my database
public void getUserKey(String email) {
Query queryRef = databaseRef.child(Constants.USERS_KEY)
.orderByChild(Constants.USERS_EMAIL)
.equalTo(email);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//TODO auto generated
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//TODO auto generated;
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//TODO auto generated;
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//TODO auto generated
}
#Override
public void onCancelled(DatabaseError databaseError) {
//TODO auto generated
}
});
}
When you fire a Firebase query there can potentially be multiple results. So when you ask for the value of a query, Firebase returns a list of items. Even if there is only one matching item, it will be a list of one item.
So you will have to handle this list in your code:
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
}
}
In Java - Android Studio, you can get the unique pushed ID as the item is written to the db...
Per "Firebase's: Save Data on Android": You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.
To get the reference at write time, instead of loading DATA with a single push()...
use push() to create a blank record in the database, return value is the record's reference.
use .getKey() to get the Key for that record.
use .setValue(DATA) to fill in the blank record
here's an example:
FirebaseDatabase fb_db_instance = FirebaseDatabase.getInstance();
DatabaseReference db_ref_Main = fb_db_instance.getReference("string_db_Branch_Name");
hashMap_record = new HashMap<String, String>(); //some random data
hashMap_record.put("key_Item1", "string_Item1");
hashMap_record.put("key_Item2", "string_Item2");
DatabaseReference blankRecordReference = db_ref_Main ;
DatabaseReference db_ref = blankRecordReference.push(); //creates blank record in db
String str_NEW_Records_Key = db_ref.getKey(); //the UniqueID/key you seek
db_ref.setValue( hashMap_record); //sets the record
I solved it to get id you need to use firebase url
String uid = firebaseRef.child("users").push().getKey();
Log.i("uid", uid);
this will give you the key KG.....
For those using TVAC Tutorials(https://www.youtube.com/watch?v=cSMMWOHkP68&list=PLGCjwl1RrtcTXrWuRTa59RyRmQ4OedWrt&index=16)
You can get Key using onClick method as follows:
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String key = getRef(position).getKey();
}
});
Just add new field to Users like userID, when you create new User add uid and than you can receive it by reading query
I'm doing it like this.
String userID;// in Users
Firebase users = myFirebaseRef.child("users");
users.orderByChild("email").equalTo("z#m.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users user= dataSnapshot.getChildren().iterator().next().getValue(Users.class);
Log.d("User",user.getUserID());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d("User",firebaseError.getMessage() );
}
});
I had faced this problem and I found the solution,
you can get it using this code:
dataSnapshot.getChildren().iterator().next().getKey()
// Unity, code in C#
{
reference = FirebaseDatabase.DefaultInstance.RootReference;
string s = reference.Push().Key;
reference.Child(s).Child(Username).SetValueAsync(Username);
Debug.Log(s);
}
Another Option to get the unique Post-id from firebase is by getting key (dataSnapshot.getKey()) in #Override method public void onChildAdded and maintaining it locally for example
private void attachDatabaseReadListener() {
if (mTaskEventListener == null) {
mTaskEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Task friendlyMessage = dataSnapshot.getValue(Task.class);
friendlyMessage.setId(dataSnapshot.getKey());
System.out.println("friendlyMessage = " + friendlyMessage);
DummyContent.ITEMS.add(new DummyContent.DummyItem("" + DummyContent.ITEMS.size()+1,friendlyMessage.getStatus(),friendlyMessage.getSummary()));
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mUserDatabaseReference.addChildEventListener(mTaskEventListener); // remove it
}
}
dataSnapshot.getKey will set the unique post id in Task Instance and can be used later to perform any update operation.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference1 = firebaseDatabase.getReference("users");
databaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String key = dataSnapshot1.getKey();
Log.d(TAG, "onCreate: key :" + key);
String email = dataSnapshot1.child("email").getValue(String.class);
String roomno =dataSnapshot1.child("address").getValue(String.class);
Log.d(TAG, "onDataChange: email: " + email);
Log.d(TAG, "onDataChange: address: " + address)
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Use this
mFirebaseDatabase=mFirebaseDatabase.getInstance().getReference("tablename");
Query query = mFirebaseDatabase.orderByChild("tablenme").getRef();
query.orderByChild("Id").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String id =dataSnapshot1.child("Id").getKey();
String Name = dataSnapshot1.child("Name").getValue().toString();
String lastName= dataSnapshot1.child("lastname").getValue().toString();
flatDataGets.add(Name+"-"+lastname);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(RagisterActivity.this, R.layout.support_simple_spinner_dropdown_item, DataGets);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mRegisterSpinner.setAdapter(arrayAdapter);
mRegisterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
flatName =DataGets.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Yes, you can retrieve the node or main child name by adding its name in that particular child as a key and value {main_child_name}.
Simply do similar:
HashMap<String, Object> hashLcl = new HashMap<>();
hashLcl.put("admin", firebaseUser.getUid());
hashLcl.put("name", textPrm);
DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference();
String keyLcl = referenceLcl.child("GroupChats").push().getKey();
hashLcl.put("key", keyLcl);
Task task = referenceLcl.child("GroupChats").child(keyLcl).setValue(hashLcl);
task.addOnSuccessListener(aVoid -> {
//the data is added and now we are sure to do something related
});
This is the result:
String id = Objects.requireNonNull(task.getResult().getUser()).getUid();