I want to write the user's data to the database only when it first logs on. I don't want it to be written over and over. I wrote a method for this, but I had a problem because there was more than one value in the for loop. How can I solve this problem?
public void writeFirebase() {
final Users users = new Users();
final List<String> arrayList = new ArrayList<>();
myRef.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
arrayList.add(ds.getKey());
}
if (arrayList.size() > 0){
for (String cur : arrayList) {
if (cur.matches(mUser.getUid())) {
} else {
Log.e("preee",""+cur);
if (mUser.getPhotoUrl() != null) {
users.setUserProfilPic(mUser.getPhotoUrl().toString());
}
if (mUser.getDisplayName() != null) {
users.setUserName(mUser.getDisplayName());
}
users.setUserId(mUser.getUid());
users.setUserPremium(false);
users.setUserPremiumDate("free");
users.setUserEmail(mUser.getEmail());
myRef.child("Users").child(mUser.getUid()).setValue(users);
}
}
}else {
users.setUserId(mUser.getUid());
users.setUserPremium(false);
users.setUserEmail(mUser.getEmail());
users.setUserName(mUser.getDisplayName());
users.setUserProfilPic(mUser.getPhotoUrl().toString());
users.setUserPremiumDate("free");
myRef.child("Users").child(mUser.getUid()).setValue(users);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
if you want to write your user data in database once and prevent from writing again you just need to check if that user is already in your database. (in this answer i consider your concern is your user existence, it can be anything else for example maybe your don't want to let user update his email address if he already entered once. so you just check that if user has entered email before or not.)
for my example(user existence) i provide some links which help you check if user is already in your database.
How to search if a username exist in the given firebase database?
How to search if a username exist in the given firebase database?
How to check if a value exists in firebase database - android
just seach and find if your user is already in your database or not. check this ifs before any operation. if he was't you will allow him to continue.
Related
I am trying send my contacts to firebase one by one and checking if the user is present or not but due to the asynchronous behavior of firebase some information is showing twice.
I want to synchronize this method like this:
loop send one number to firebase, firebase response, save, and continue
for (int i=0 ; i< list.size();i++) {
Check_Contact(list.get(i));
}
public void Check_Contact(String number)
{
DatabaseReference myRef = database.getReference("user").child(number);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
}
else {
UserProfile row = dataSnapshot.getValue(UserProfile.class);
ls.add(row);
Adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Can somebody tell me how to synchronize this method?
Firebase Structure
output coming
It is not the firebase async behaviour. You may have duplicate contents in your database. Please check ur database and update a screenshot of your database in your question.
It will be more helpful to understand your question.
I'm developing an app. The app must able to show the latest 10 registered user detail from real-time database. That is, It removes any user older than latest 10 users. Is there any way I can do this? Right now my app is able to access the user details stored in realtime firebase.
Thanks in advance.
That sounds totally feasible. An incredibly simple way is to retrieve 11 users in your app, and then just remove the last one.
ref.orderByChild("descending_timestamp").limitToFirst(11).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int userCount = 0;
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
if (userCount++ > 10) {
userSnapshot.getRef().remove();
} else {
// TODO: show the user in your app
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "load users", databaseError.toException());
}
});
You'll note that I order on descending_timestamp, which is a property that you must add to the data and that allows you to sort the users in reverse chronological order. For more on this, see Firebase Data Desc Sorting in Android
This question already has answers here:
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 4 years ago.
Each time the activity is called, it writes again. But I don't want him rewriting the premium part. How do I check the user ID to not rewrite the database? How do I query the user's identity in the database ?
public void writeFirebase() {
Users users = new Users();
if (mUser.getPhotoUrl() != null) {
users.setUserProfilPic(mUser.getPhotoUrl().toString());
}
if (mUser.getDisplayName() != null) {
users.setUserName(mUser.getDisplayName());
}
users.setUserId(mUser.getUid());
users.setUserPremium("false");
users.setUserPremiumDate("");
users.setUserEmail(mUser.getEmail());
myRef.child("Users").child(users.getUserId()).setValue(users);
}
If you want to check that the data is not already present or not for the particular userID, you need to know the user ID.
For fetching user by ID :
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
User user = dataSnapshot.getValue(User.class);
// **HERE YOU CAN CHECK IF THE PREMIUM VALUE HAS BEEN SET OR NOT**
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
myRef.child("Users").child(yourUserID).addListenerForSingleValueEvent(userListener);
You can get more details here : https://firebase.google.com/docs/database/android/read-and-write#read_data_once
I'm implementing a search in my android app and I can't seem to make it work.
public void loadReleaseData(String name) {
mDatabase.child("releases")
.child("europe")
.child("data").orderByChild("game/name").startAt(name)
.endAt(name+"\uf8ff")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
Log.d(TAG, "New datasnapshot");
for (DataSnapshot data : dataSnapshot.getChildren()) {
_Release release = data.getValue(_Release.class);
if (release != null) {
// No platform filter set add all releases!
list.add(release);
if (release.getGame() != null) {
Log.d(TAG, "NAME: " + release.getGame().getName());
}
}
mUpcomingGamesAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
When I remove startAt or endAt either of the two data is shown but not the correct data, but when they're both added in, nothing is show and my log "New datasnapshot" doesn't even get printed. I'm searching on the names of the games I have in my database.
My firebase database:
According to your comments, the reason your code was not working was because the value of the name variable that was passed to startAt() and endAt methods was incorrect.
The key for solving the problem is to pass as an argument to both method the exact same name that exist in the database, in this case you should search the name in lower case.
I'm using firebase with android to create a simple chat app. When the user chooses another user to chat with I want to check whether they've chatted together or not.
In onCreate() method I'm retrieving all the rooms that the current user used before, and I'm putting them in an arraylist called MyChatRooms<>.
Then I want to check each room to see the users of the room.
The problem is that the loop I'm using to iterate through rooms name is finishing before I'm able to retrieve any data from the database.
I know there's similar questions to mine, but none of the answers worked for me.
Here's the related code:
if (!MYChatRooms.isEmpty()) {
for (j = 0; j < MYChatRooms.size(); j++) {
roomref.child(MYChatRooms.get(j)).child("First User").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if (!dataSnapshot1.getValue().toString().equals(Username) && dataSnapshot1.getValue().toString().equals(NUsername)) {
Users += dataSnapshot1.getValue().toString() + ",,, ";
} else if (dataSnapshot1.getValue().toString().equals(Username)) {
roomref.child(MYChatRooms.get(j)).child("Second User").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot2) {
if (dataSnapshot2.getValue().toString().equals(NUsername)) {
Users += dataSnapshot2.getValue().toString() + ",,, ";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I would suggest that you change the structure of your data. Imagine if a user has 100 chats that means your have to query 200 times to Firebase that of course does not look feasible.
What i would suggest is that your add a recentChat list in every user and whenever a user starts a new chat with someone you add the id of the second user to that list. That way you can track easily with whom the current user has interacted with.
It structure in firebase can look something like this:
User
recentChats
id of the other user
Try to change you database hierarchy or use firestore instead of real time database
Please check the following topic: https://firebase.google.com/docs/database/usage/optimize?
In my case, I had added and index column and limited the query in Firebase Rules.