I have created an Android App By which user can register and login.When a user registration is successful a Name and value will created in my database for that User. Now I want to retrieve The Data For every User separately.
To retrieve the current user's data from this structure, you need two things:
to know the uid of the current user
to then read the data from the database
In code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseDatabase.getInstance.getReference(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long points = dataSnapshot.child("Points").getValue(Long.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Try this:
mDatabase.child("ezzeearn").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();
String point = map.get("Points");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
for using iterator you can get the data for specific user
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
Try to use below method :
public void getAllUsersFromFirebase() {
DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("ezzeearn");
UserRef.keepSynced(true);
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
String resultString = (String)dataSnapshotChild.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// for handling database error
}
});
}
Related
I have a questions how could i push array list to my freebase data base
and also read it to add a new element , then push it again.
In the above photo you can see i have added array list joinedStudents
and i need to read it and push new elements to it
I've tried the following
DatabaseReference requestsRef = FirebaseDatabase.getInstance().getReference();
requestsRef.child("requests").child(requestID).child("joinedStudents");
requestsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
requestsRef.child("requests").child(requestID).child("joinedStudents").setValue(string);
}
but it's not working
I believe you have your references slightly mixed up. Try something like:
DatabaseReference joinedStudentsRef = FirebaseDatabase.getInstance().getReference().child("requests").child(requestID).child("joinedStudents");
joinedStudentsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
joinedStudentsRef.child("1").setValue(string); // setValue is for key, value
// but you have an array
}
Where your reference is now the direct node that you want to monitor/read/write
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 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
I am having trouble fetching the custom push id which is created while pushing the value.
I want to fetch "4wJIGRCkYrZqFpb401hSmgHeBOI3" from rated_user node. Any help will be really useful. Thanks in advance.
Lets say database reference for rated_users is this RatedUser
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
String key = postSnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
RatedUser.addValueEventListener(valueEventListener);
Use the following code to archive your goal.
private DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://xxxx.firebase.com/rated_users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String key = dataSnapshot.getKey();
String value = dataSnapshot.child("key").getValue(String.class);
}catch (Exception e) {
String valws = e.getMessage();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
PS:
I did a quick sample it works for me.
All i did was added a foreach loop:
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.e("children" , snapshot.getKey()+"");
}
this gave me the key "4wJIGRCkYrZqFpb401hSmgHeBOI3"
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.