How to bind firebase database user and user data - java

I don't really know what to search regarding this specific question but recently I just did
a login/sign up feature on my app with firebase and it works great.
Context of what I wanna do:
This app already has a working assessment feature that will give a score to the user and will store the score in their profile.
The problem is how do I make sure that the score (and other user info) will be bound to a specific user that is currently logged in?
How do I make it so that when a specific user does an assessment their score will fall into their own node?
example of what I want to accomplish:
>USER1 signs up.
>USER1 will take the assessment.
>After USER1 takes an assessment
he will go to the profile to see his results
as well as his basic info like fullname,username and age.
This is the sample of my firebase database.
Thank you! I will keep searching I just need a little bit of help cause I don't really know what to search about this specific thing.

If the user is logged in, then you can simply do:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
Now you have access to the userId. Then if you want to add a new score to the database, you can do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Score");
ref.child(userId).child("result").setValue(1);
This will give you the following database:
Score
userId
result : 1

Related

How to login a user with custom fileds, let's say with his CNIC number or bloodtype?

I'm new to android and firebase, so let me ask. I'v an application for Blood Bank, I've done registering user by asking email and password. Also I've verified his phone number and store additional information in Realtime Database.
The real question is, I want the user to log his bloodtype and phone number and if its in the database, he's logged in and save his userID for signing out later.
Sorry for asking a silly question.I'll appreciate if someone help me out here.

How to best store IDs of other database objects within Firebase (Ex: Event with Users)

I am new to firebase, and am building an android app to practice.
My app is very straightforward. There are Users, who can create an Event. Other users can either accept or reject an invitation to an Event.
To keep things simple, whenever an Event is created, all Users in the database get invited to that Event.
My database is currently structured like this:
What I want to do now is for each Event, I want to know which Users have accepted, declined, or are yet to respond to the invitation.
I am unsure the best way to approach this. These are some ideas I have had:
For an Event, create 3 children which will store all the User information for each response option. (accepted, rejected, pending).
For an Event, create a child 'responses' which will have each Users uid as a key, and the value could be either "accepted", "rejected", or "pending".
Something else completely.
Option 1 seems like it can work, however it means that a User data is going to be copied all over the database. If a User is invited to 1000 events, there will be a copy of that User literally 1000 times, once within every Event.
Option 2 seems logical to me, however I have tried implementing it and am having difficulties building a firebase Query. If I want all the accepted users, I need to get all the uids of the 'acceptedUsers' child, and then pull out of the 'users' node all the children that match these uids. This doesn't seem to be possible...?
Any help or guidance would be greatly appreciated!!
Option 2 seems most direct to me:
responses
eventid
uid1: "accepted"
uid2: "rejected"
uid3: "pending"
You will indeed have to load the additional information for each user client-side. This works fine, and performs much better than most developers expect due to the fact that the requests can be pipelined over a single connection. For more on this 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
If you'd really prefer not to perform the client-side join, you can store additional data for each response that allows you to display it. If you want to display user names:
responses
eventid
uid1
status: "accepted"
displayName: "Ryan Saffar"
This gets closer to Peter's answer, but here we key them off event id and uid.
Try this:
Events
eventid1
createdby: userx
eventname: Party
eventid2
createdby: usery
eventname: Meetup
AttendancetoEvent
eventid1
username: userf
response: accepted
eventid1
username: userg
response: rejected
eventid2
username: userg
response: accepted
then to get the accepted users, do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("AttendancetoEvent");
Query queries=ref.child("eventid1").orderByChild("username").equalTo(accepted);
Well you're doing everything right, just to say. For the Events node, you can use .push() function for random branch name. So let's begin, each User has a UID, alright? User's data is particularly stored there including their name, that's done. Now a user posts an event so push that event to Events, now make an arrayList of user's event in the UID node. So when you upload that event you get it's reference and store it in the UID branch so the user can retrieve all of his events.
For accepted, pending or rejected choices , I hope whatever you're building has buttons for these functions.
So now onClickListener() store the user's
Uid in an arrayList for any of the choices and upload it to the branch of retrieved Event. For that in your Event model class add a String for the path reference, so you can upload the choices there. All done.
Now if the user who wants to know who accepted, rejected or have pending choices you can display the user name using UID from the arrayList. I suggest to use uid because just in case if the event uploader wants to get any more of the User data who chose any of the options.
I think this will work fine.

Firebase user data storage issue

I am working with Firebase Authentication and while coding I realised that I can use User user = FirebaseAuth.getInstance().getCurrentUser; to fetch user data in any activity through out the application if user successfully logged in but I am confused that whether I can store user data in sharedPreferences after user login or I can use User user = FirebaseAuth.getInstance().getCurrentUser; way to get user data in whichever activity I want to. So which method is preferable to use firebase user data. And if there any other method you have to suggest then you are always welcome. Thanks in advance.
The user data is limit to login info like user id or email address by using FirebaseAuth.getInstance().getCurrentUser().
If it's enough to use it for you, that's ok.
In order to get the data which saved to sharedpreferences, you can define PreferencesUtils class.
The class is singleton or has static members.
If so, I think you can call this members anywhere.
I hope it helps.. If you any questions, let me know.
Use always firebase user instance, because it gives to you an updated user instance. if you are going to save user data in sharedPreferences, you should always save user details in sharedPreferences when you update the user data.
I would use an AuthStateListener to listen to possible changes to the authenticated user, and persist changes to that user object only when they might change, according to that listener. It's probably not worthwhile to continually ping currentUser for changes when you know it can only change when response to the listener callback.

Android App storing and searching data

I am looking for recommendations on how to have the data setup for a car wash appointment scheduler app I am making for fun.
I think there is a better way to store and search through the information with the way I have it setup below.
So far this is what I have,
On an online MYSQL Database:
User Table: name, street, zipcode, state, phone, username, password
Vehicles Table: username, year, make, model, color
On the App:
SharedPreferences with name, username, street, zipcode, state, phonenumber, password
SQLiteDatabase with year, make, model and color.
When the user logins on the main activity it checks for the username and password in the User Table on the online server. If there is a match it downloads the full user data. It also downoads all the vehicles that have the correct username from the Vehicles Table. Then this data is stored in the app in its proper place (user data in the Shared Preferences and the vehicles each entered into the SQLiteDatabase).
What I am having trouble implementing is a full history of service per vehicle. I think there is a more efficient way of getting the vehicle history without searching through an appointments of every users appointments every time I want to show the vehicles history.
Any recommendations?
EDIT:
The only other idea I have is to create a table on the server and the local SQLite that is the named "username-vehicle-appointments". That way it has to search through a smaller table and there is less data to download.
I am still trying to think a way to have the appointment request and confirmation setup.
EDIT:
Maybe have a new table on the server that is named new-appointments. The app could check the new-appointments table every few minutes to see if there are new appointment requests?
Does this sound like a good way to do this?
Thanks!
Not sure if this could help but have you thought about making an API and storing everything in JSON instead? It might work out better for your needs

How do I separate keywords for 2 different users?

I have couple of different users on my app. There are certain keywords associated with these users based on their selections and I want to make them such that, user1's kselected keywords are not displayed for user 2 when he logs on the same device.
Here's the basic code :
Boolean firstuserlogin= Sharedpreferences.getinstance().firstlogin;
Boolean sameuserlogin = !Sharedpreferences.getinstance().differentuser;
Boolean differentuserlogin = Sharedpreferences.getinstance().differentuser;
if(firstuserlogin && differentuserlogin) {
//Please note: firsttime user is also considered a new/different user
m_keyword = Sharedpreferences.getinstance().getkeyword1();
}else if(sameuserlogin){
m_keyword = Sharedpreferences.getinstance().getkeyword1();
}else if(differentuser){
m_keyword = Sharedpreferences.getinstance().getkeyword2();
}else{
m_keyword = Sharedpreferences.getinstance().getkeyword1();
}
The issue is I am not able to get it to work as expected.Theoretically: Say a user 1 logs in ,he's considered first user and at the same time a new/different user, until he logs out.His keyword settings which he selects during his session are saved as expected. Now, Say he logs out and logs in again , he should be able to see his keyword settings and be considered as the "sameuser" since he logged in before, unless some other user with a different id logs in on the same device, in which case, it should show all new default keyword(which is lets say keyword2 in this case ) and should not show the previous users selections.Currently based on the above logic I implemented it seems to go haywire, sometimes it works, and sometimes it doesnt recognize the user as a different user, but same user AND VICE VERSA. is there a better and compact way I can restrict and implement this logic?
Thanks!
Well, if you insist on using shared preferences, you can use a unique key(email,username,userId anything) and merge it with the keyword and save to share preferences. You will need a special character to seperate the unique key and keyword (somekind of key-value pair)
for example if we use id as uniqkey and ## as token character. keywordA for the keyword you should save as "userid1##keywordA) and read it back from preferences. After you get it. You should split it via ##.
But for such operations shared preferences is not the best place, you should use a database since you have multiple users. Android supports sqlite database built in. You can see a tutorial here
Good luck

Categories

Resources