I am working on an Android application. I want the first child (first UID) of the parent 'support' and store it in a String variable. How do I get the value of the first UID from the list?
I tried one approach. It doesn't work though.
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if (dataSnapshot1.exists()) {
String futureUID = "";
for(DataSnapshot futureUIDdatasnapshot:dataSnapshot1.getChildren() ){
futureUID = futureUIDdatasnapshot.getKey();
break;
}
/*Getting the first UID from the list of UID's in queue in 'future'*/
futureUID = dataSnapshot1.getChildren().iterator().next().getKey();
/*Moving a card from 'future' to 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_SERVING).child(futureUID).setValue(FIREBASE_ACCEPTED);
/*Removing the UID from 'future' after it is placed in 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_FUTURE).child(futureUID).removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
NOTE: 'futureUID' is the UID I want
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("support");
Query queryUid=ref.orderByKey().limitToFirst(1);
queryUid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
.orderByKey().limitToFirst(n) is what does the trick. It orders the query results by key and returns only the first n results; in this case 1
mDatabase.getChild("support").orderByKey().limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener () {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot supportItem: dataSnapshot.getChildren()) {
String futureUID =supportItem.getKey();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Catch your error here
}
});
see Work with Lists of Data on Android
Related
While displaying the recent chats fragment in the application I am fetching my chats from firebase and filtering out the chats by their receiverID and senderID in the chat object to display the recent chats.
The problem says ConcurrentModificationException in ArrayList and it looks like due to the complexity of searching id in the array it occurred, I need a solution to minimize this chat filteration complexity.
// private List<String> stringList; Declaration at top
stringList = new ArrayList<>();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("BaatCheet/Chats/");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//userModelList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
MessageModel messageModel = dataSnapshot1.getValue(MessageModel.class);
if (messageModel.getSender().equals(firebaseUser.getUid())){
stringList.add(messageModel.getReceiver());
}
if (messageModel.getReceiver().equals(firebaseUser.getUid())){
stringList.add(messageModel.getSender());
}
}
readChat();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The read chat function
private void readChat() {
userModelList = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("BaatCheet/Users/");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userModelList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
UserModel userModel = dataSnapshot1.getValue(UserModel.class);
for (String id: stringList){
if (userModel.getId().equals(id)){
if (userModelList.size() !=0){
for (UserModel userModel1 : userModelList){
if (!userModel.getId().equals(userModel1.getId())){
userModelList.add(userModel);
Log.d("DataAdded",userModel.getId());
} // If the existing list don't have same value for sender and reciever
} // end of inner userModel
} else {
userModelList.add(userModel);
Log.d("DataAdded",userModel.getId());
} // end of else
} // end of userModel id equals string id
} // end of String is loop
} // end of DataSnapshot loop
usersAdapter = new UsersAdapter(userModelList);
recyclerView.setAdapter(usersAdapter);
} // end of onDataChange
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}// end of readChat()
The results would be the recyclerView of recent chats containing the chats which contain messages either send by the sender or receiver to each other.
In the following snippet of code :
for (UserModel userModel1 : userModelList){
if (!userModel.getId().equals(userModel1.getId())){
userModelList.add(userModel);
Log.d("DataAdded",userModel.getId());
} // If the existing list don't have same value for sender and reciever
} //
You are modifying userModelList while iterating through userModelList. This is not allowed and is the cause of ConcurrentModificationException.
There are few ways to simplify the logic, the simplest (albeit not the best) would be to convert this foreach loop into a simple for i loop.
for (int i = 0; i< userModelList.size(); i++) {
UserModel userModel1 = userModelList.get(i);
if (!userModel.getId().equals(userModel1.getId())){
userModelList.add(userModel);
Log.d("DataAdded",userModel.getId());
} // If the existing list don't have same value for sender and reciever
} //
Basically to handle this complexity I am now using separate nodes just for storing the chatLists as such now I don't need to read chats for filtering the recent chats.
The below code is for creating a new node everytime user sends a message it will update the node if the recieverID is different.
dbrefChatList = FirebaseDatabase.getInstance().
getReference("BaatCheet/ChatList/")
.child(senderuserID)
.child(receiveruserID);
dbrefChatList.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
dbrefChatList.child("id").setValue(receiveruserID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
As such ChatList is a Model Class which contains single String called "id" and this id will be used to search in the node.
The below code is for the ChatFragment which fetches the chatList from firebase and set the data to recycler view.
// private List<ChatList> chatList; Declaration at top
chatListList = new ArrayList<>();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase
.getInstance()
.getReference("BaatCheet/ChatList")
.child(firebaseUser.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatListList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
ChatList chatList = snapshot.getValue(ChatList.class);
chatListList.add(chatList);
}
myChatList();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The function myChatList act as the function of readChat in the problem statement.
private void myChatList() {
userModelList = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("BaatCheet/Users/");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
UserModel userModel = snapshot.getValue(UserModel.class);
for (ChatList chatList : chatListList){
if (userModel.getId().equals(chatList.getId())){
userModelList.add(userModel);
}
}
}
usersAdapter = new UsersAdapter(userModelList);
recyclerView.setAdapter(usersAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You can set a flag while traversing the array, after it's done, add it if it doesn't exist yet:
// Display 1 user from chats
for (String id : str_usersList) {
if (user.getId().equals(id)) {
if (userList.size() != 0) {
boolean exists = false;
// If not exists then add
for (User user1 : userList) {
if (user.getId().equals(user1.getId())) {
exists = true;
}
}
if (!exists) {
userList.add(user);
}
} else {
userList.add(user);
}
}
}
I am trying to make multiple queries to my Firebase database, but it seems I am doing something wrong, and I just can't seem to understand what.
My code is this:
database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("Tbl1");
Query tbl1Query = ref.orderByChild("type");
tbl1Query .addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Tbl1Item item = singleSnapshot.getValue(Tbl1Item .class);
tbl1List.add(item);
}
DatabaseReference ref = database.child("Tbl2");
Query tbl2Query = ref.orderByChild("status");
tbl2Query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
tbl2Item item = singleSnapshot.getValue(tbl2Item.class);
tbl2List.add(item);
}
DatabaseReference ref = database.child("Tbl3");
Query tbl3Query = ref.orderByChild("status");
tbl3Query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
tbl3item item = singleSnapshot.getValue(tbl3item.class);
tbl3List.add(item);
}
SortTableData();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is that the app crashes though I get no error in console.
What I am trying to obtain, is create 3 lists of objects with data from table1, table2 and table3 and then call a method that will process that data.
If I remove the 2nd and 3rd queries, everything works fine, but I don't have all the needed data... so what I am doing wrong?
If I have a database that is set up like so
-users
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
-uId2
-Name: "Dave"
How do I get the uId elements if there name child starts with B.
The query should return somthing like this?
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
Thanks!!
DatabaseReference myReference = FirebaseDatabase.getInstance().getReference();
myReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//looping all your users
for (DataSnapshot messageSnapshot:dataSnapshot.getChildren())
{
name = (String)messageSnapshot.child("Name").getValue();
if (name.toLowerCase().contains("b")) {
//u can save your name with 'b' string here
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To achieve this, please use this code:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String uId = (String) ds.getKey();
DatabaseReference uIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(uId);
uIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("Name").getValue();
if (name.matches("^[B].*$")) {
System.out.println(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
A simple question:
Referring to my database image, I want to get the values of the children of node "user" in a list in an Activity, i.e. values "a" and "m" should be displayed in the list.
What should I use and how?
Please try this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("user");
yourRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> usersList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = (String) ds.getKey();
usersList.add(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This is the way in which you'll have in your list, a, m ans so on.
Hope it helps.
You can get the info from the docs here
List<User> allUsers = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allUsers.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
allUsers.add(userSnapshot.getValue(User.class));
}
yourRecyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Users failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
});
How can I get that value while I know nothing about the push key?
+users
+9JZTuGUzc8bx7FLrwResWmp8L583
+anon:
+email:
+fid: <- i want to get this id without knowing push key (9JZTuGUzc8bx7FLrwResWmp8L583 )
+username:
Currently, I am trying with a null response:
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
if(dataSnapshot.exists()){
User user = dataSnapshot.getValue(User.class);
fidanon = user.fid;}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
final Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME));
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
final String fid = dataSnapshot.child("fid").getValue().toString();
Toast.makeText(getActivity(), fid, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Use this,will solve your problem.