How to insert user current user details to another node in Firebase? - java

I am inserting a data in my Request Node in Firebase database in Android using this,
public void submitRequest(View v) {
Request myUserInsertObj = "Pending";
rootReference.child("Request").child("Pending").child(firebaseuser.getUid()).setValue
(myUserInsertObj);
}
This is my Request Class.
Public class Request{
public String request_status;
public Request(String request_status){
this.request_status = request_status;
}
Request()
}
I found in firebase documentation that I can use firebaseuser.getDisplayName to get the current logged in user's name. But where will the .getDisplayName get the user's name since I created my own login form and user registration in my app.
Question 2:
If I do this, is this possible? Because I want to put a name in requesting guest node so that when I retrieve it in my HTML web admin panel the data will be easier to read.
rootReference.child("Request")
.child("Pending")
.child(firebaseuser.getUid())
.setValue(myUserInsertObj + firebaseuser.getDisplayName);
If so what should I add in my Request Class?
Question 3.
How do I add timestamp I know timestamp is very important in data insertion on every system.

I found in firebase documentation that I can use firebaseuser.getDisplayName to get the current logged in user's name.
Yes, that correct. Calling getDisplayName() on a FirebaseUser object:
Returns the main display name of this user from the Firebase project's user database.
Regarding the second part of your question:
But where will the .getDisplayName get the user's name since I created my own log in form and user registration in my app.
As explained above, getDisplayName() is getting you the name that is coming from the authentication process. If you want to get the user name from your custom user object then you should first get the user object from the database and use it where it is needed.
Because I want to put a name in the request node so that when I retrieve it in my HTML web admin panel the data will be easier to read.
If you want to add the name in your node, you should pass the display name to the child() method and not to the setValue(). Your code should look like this:
rootReference.child("Request")
.child("Pending")
.child(firebaseuser.getUid() + "_" + firebaseuser.getDisplayName())
.setValue(myUserInsertObj);
This code will generate a child that might look like this:
Firebase-root
|
--- Request
|
--- Pending
|
--- SxbVg0...uobvk1_Theodore
|
--- //user details
DatabaseReference class has 4 overloaded setValue() methods but none of this methods allow you to pass an object along with a String as arguments.
Question 3. How do I add timestamp I know timestamp is very important in data insertion on every system.
This is how you add and get the timestamp that you were talking about.

Related

Retrieve multiple data in recycler view using FirebaseRecyclerOptions

I am using FirebaseRecyclerOptions in calling the database, however, I cannot get all of the data in the database. Here is the structure of the database: database structure the yellow underline is the user id (UID) and below is another node that contains the data that I want to retrieve in the RecyclerView.
Here is a snippet of the code
FirebaseRecyclerOptions<RegisterParking> options =
new FirebaseRecyclerOptions.Builder<RegisterParking>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("RegParkingArea"), RegisterParking.class)
.build();
voPListAdapter = new VoPListAdapter(options);
recyclerView.setAdapter(voPListAdapter);
When you're passing the following two arguments to the setQuery() method:
.setQuery(FirebaseDatabase.getInstance().getReference().child("RegParkingArea"), RegisterParking.class)
It means that the adapter expects to render on the screen RegisterParking objects. If you take a closer look at your database schema, under the RegParkingArea node, you can find UIDs and not RegisterParking objects. The objects that you want to display in the RecycerView exist under each UID. So when reading the data from the database, the Firebase-UI library tries to map each child under the above reference into an object of type RegisterParking, which is actually not possible since the UIDs are strings.
So if you're allowed to change the database schema, then you should either denormalize the data, basically copying the data under another node, or change the actual data into:
db-root
|
--- RegParkingArea
|
--- $pushedId
|
--- uid: "4u9h...XrP2"
|
--- //other fields.
What I have basically done, I have removed a level from the database tree. If you'll use this schema, then you can leave the code as it is and everything will work perfectly fine.
One more thing to note is that if you need to get all parking of a particular user, then you can use the following query:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByUid = db.child("RegParkingArea").orderByChild("uid").equalTo(uid);

Organizing firebase data

I am using Firebase Auth and Firebase Database to store student's profiles and students reports.
When the user signs up they input email, password, school name, school year, school discipline. I use the email and password for the Auth but the rest of the info is stored in the Database with a unique ID as shown below:
For the reports, each students can input many entries, each with its unique ID as shown below:
Here are my questions:
Once a student logs in, how can I find their profile info since the parent is a unique ID. In other words is there a way to search through the database for that students email (for example, mido4#hotmail.com, in the image) and from that get the students name (in this case, Emina Osman)?
Once you get the student's name, how can you search for all the entries that student has saved in the database? For each entry the student has, the student name is saved.
Not sure if the way I setup the database is ideal so is there a better way?
Thanks for your time! Any help would be really appreciated!
Yes, it is. The simplest way to achieve this, is to change your database structure a little bit. So instead of using as a unique identifier, the pushed key, generated by the push() method, i suggets you using the email address. It's also unique and easy to use. The benefit is, that is allows you to search your database for that particular email. Your database structure should look like this:
flashscreen-1d252
|
--- Users
|
--- mido4#hotmail,com
| |
| --- //User Details
|
--- mido5#hotmail,com
|
--- //User Details
Note, that Firebase does not allow symbols as . (dot) to be used in a key. So as you probably see, i have changed the . dot with a , (comma). I have achieved this using the below method:
String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
To search for an user and get the name, simply add a listener on Users node like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child("mido4#hotmail,com");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
String firstName = dataSnapshot.child("firstname").getValue(String.class);
String lastName = dataSnapshot.child("lastname").getValue(String.class);
Log.d("TAG", firstName + " " + lastName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
The output will be: Emina Osman
You'll have to search after the email address and not after the name.
Already answered above. This database structure is more efficient.
Edit: There 2 additional questions regarding this answer based on using the email address vs. uid.
What if a user decides to delete his account and after a while decides to return and tries to sign-in again? If we are using the email address, nothing happens. If we are using the uid, when the user signs in for the second time, another uid is generated, which is obvious that is different from the first one and this the moment in which you are in trouble, because even he is the same user, he is treated as a new one.
What if the users email address changes? IMHO, an email can be changed only if you decide to change it. Personally, I haven't changed my email address in years but I have deleted hundreds of accounts from hundreds of applications. Even if you change your email address, there's no much of a problem. You login in your application, change the email address and that's it. You'll have also all your history within that application. Having a unique identifier a uid, in case you delete the account and you come back again, you start from zero.
Once a student logs in, how can I find their profile info since the
parent is a unique ID.
Super easy! When a users account is created initially, Firebase assigns the user a 'random' and unchanging user uid (uid). That uid is what identified that specific user to Firebase. That's what you should store there info under within the users node like this:
users
uid_0
name: "users name"
Then when they authenticate in the future, firebase provides that uid to you in the authentication process. You can then simply get their user information from the users node via that uid. i.e. read the node /users/uid_0
Once you get the student's name, how can you search for all the
entries that student has saved in the database?
Again, super simple. For every entry you make in Firebase, reference that uid. For example, say you want to keep track of each users reports
reports
uid_0
-9i9sdjj3i0a09djads //create with push() or childByAutoId() in swift
reportName: "some report"
-ua9sd9i9i3i0idsfi
reportName: "another report"
Then to get all of their reports, read the node /reports/uid_0
conversely, you can store the reports and then a link to the user
reports
-9i9sdjj3i0a09djads
reportName: "some report"
report_by: "uid_0"
and with that structure a query can be done where report_by is equal to "uid_0" to return all of uid_0's reports.
Not sure if the way I setup the database is ideal so is there a better
way?
there's a number of different ways to achieve what you want but the above is a very common design pattern.

How to add user login check in GenericDao.java in Ofbiz

I am Trying to achieve single DB and multiple organization (not Multi tenancy) in ofbiz, how do i get user login Id till GenericDAO and append it to the query.
Please Suggest if you have any other ideas except multi tenancy!
Thanks
EDIT:
if (!conditions.isEmpty()) {
whereString.append(prefix);
whereString.append(EntityCondition.makeCondition(conditions, EntityOperator.AND).makeWhereString(modelEntity, whereEntityConditionParams, this.datasource));
}
System.out.println("************ whereString ************ "+whereString+" ---- ");
return whereString;
In line number 841 in my ofbiz v13.07 GenericDAO.java, i can get to know the place where query string is getting created. i want to access the session here to get the company Id and so i append it to the where clause. to get relevant data.

get user group description and name in liferay

I want to get the user group description as well the name of logged-in user in portlet.
I am able to get the logged-in user object using:
ThemeDisplay td = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
Please help me out with how to get the logged-in user's group.
These user groups are coming from ldap and mapped in liferay DB UserGroup.
Thanks in advance.
As you have the user object, you can get full name of user by using
user.getFullName()
for getting the user group description, call the following method, which will give you the list of Groups. which belongs to user.
List <Group> grpList = GroupLocalServiceUtil.getUserGroups(userId);
Iterate the list to get the groupId's. Pass group Id to following method.
Group grp = GroupLocalServiceUtil.getGroup(groupId)
You can get group Description using
String grpDisc = grp.getDescription();
Hope this is what you are looking for.

JDO - List of Strings not being retrieved from database

On my User class I have a field that is a list of strings:
#Persistent
private List<String> openIds;
When I create a new user I do this:
User user = new User();
user.openIds.add(openid);
pm.makePersistent(user);
When I break after that last line and look, the openIds contains the openid I put in there.
But, when I later call User user = pm.getObjectById(User.class, id); with the correct id, the openIds field is an empty list.
Anyone know what could cause that?
EDIT: BTW I'm running on the Google App Engine
UPDATE: Looking at the datastore viewer, I can see the openid was correctly stored in the database. So its just not getting it out correctly...
UPDATE 2: Its working fine now. I'm pretty sure I didn't change anything. I think what must have happened is that there was an old version of the user object being pulled from the database. A user object that was put in before I had the code that saves the openid. Once I wiped the database things worked fine.
Not putting that field in the fetch plan ?
Accessing persistent fields directly, rather than going via setters ?

Categories

Resources