FireBase Real Time Database - android

I am using Firebase Database in an Android application, and everytime a user is singUp I store some values in the database for this purpose I am doing what follows:
#Override
public void writeObject(IUser object) {
User usrReal = (User) object ; // this userReal's reference same with parameter
User usrCopy = new User(usrReal); // copy of it
String usrId = usrCopy.getUserId();
databaseReference.child("usrId").setValue(usrCopy);
//databaseReference = this.databaseReference = FirebaseDatabase.getInstance().getReference().child(path) is defined beginning of the class
}
as you see in the child method if called "usrId" it create usrId directory and add all neccesary information in it. But I want to create directory for every user ,so I tried to pass usrId variable as a parameter. Howewer it doesn't work. When I debug the code debugger says that Local var usrId can not recognized.My question is How can I create nested structure in Firebase wrt. user's id.

If the userId is the id generated by firebase authentication, then you can do:
String userId = user.getUid();
this.databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
this.databaseReference.child(userId).child("name").setValue("peter");
Then you will have this structure:
Users
userId
name : peter
userId1
name : john

Related

How do you manage your android device token generated by FCM after token expired?

I'm developing a push notification app, do you have same issue:
My app generate a FCM device token and store it in a cloud database, so I can send notification messages to a device via FCM, and my database table looks like:
userid | device_token
Mary | xxxxxxxxxxxxxxxxxxxxxxxxxxxx // token1, from Mary's first device
John | yyyyyyyyyyyyyyyyyyyyyyyyyyyy
Mary | zzzzzzzzzzzzzzzzzzzzzzzzzzzz // token2, from Mary's second device
Mary | kkkkkkkkkkkkkkkkkkkkkkkkkkkk // token, from Mary's first device
.......
After Mary reinstalled this app from her first device, a new device token generated, and it is stored with token3.
How can I remove the expired device token token1, the only information I got may only be a pair of device token and an account name.
So how do you manage your device in this situation?
If "Mary" is using the same account to log in each time in your app, even if it is a new phone or reinstalled app why do you create a new token field inside the database? Why don't you always write inside the same token field so you always have access to this field. This will also send notifications only to the phone that your user is actually using right now. So each time when the user starts the app check token, if not equal write the new one inside your database. And from the server-side take those tokens and send notifications.
Am I missing something?
To do this, I would suggest using FirebaseAuth for the SignIn and SignUp process of your application. Then use generated uid as the field ID for the user inside the Realtime Database. You can get this uid with FirebaseAuth.getInstance().getCurrentUser().getUid(). So your user Mary will always have the same uid no matter what phone she uses. Always find the user inside the database with this uid and overwrite the existing Firebase token. This also means that your "users" will not be a single line field inside the database, but a more complex and better representation of a user. You can use model classes for this like:
public class User {
public long id = 0;
public long account_id = 0;
public String account_name = "";
public String first_name = "";
public String last_name = "";
public String email_address = "";
public String password = "";
public User() {
}
}
It's up to you on how to configure this. But using models is also helping you on posting and retrieving data, like this:
Creating new user:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
Retrieving data from the real-time database:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseUsers = database.child("users");
User myUser = null;
Query usersQuery = databaseUsers.orderByChild("username").equalTo(uid); //you can use any value to order as you want, or you don't have to, there is many options for this query
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChanged(#NonNull DataSnapshot snapshot) {
try {
for (DataSnapshot user : snapshot.getChildren()) {
myUser = user.getValue(User.class);
}
} catch (Exception e) {
e.printStackTrace();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Inspired by this: Firebase Cloud Messaging - Managing Registration Tokens
When a token generated:
if Mary logged in:
add the device to the "Mary" Device Group.
store the device group id and connect the device group id to "Mary"'s profile in database.
if app server need to send notification to Mary, just send to the Device Group, the benifit is that you don't need to check if the device token is valid or not, Firebase Cloud Messaging discards invalid device tokens.
if no one logged in:
do nothing or just store the device token.

How can i populate a string value to a realtime firebase database with out creating a child nodes from android?

I wanted to add a string values to a realtime firebase database with the firebase UID being the name and the string being the value. When I use the below code it makes the UID a parent node and set the value to a child node.
ReferralCode referralCode = new ReferralCode(refCode); databaseReference.child("referralCodes").child(userId).setValue(referralCode);
I wanted the values to be populated as the second one. But with the above code,i get the first result. I'm going to search for the referral codes afterwards,so i think it would be faster if the values are populated as the second one to avoid accessing a child node which will be time consuming for large database entities.
When you are using a Model like you created ReferralCode and using it to with .setValue(referralCode) then Firebase will automatically create it as the child with attributes your ReferralCode.java has. Example below:
public class Restaurant {
private int code;
private int type;
private String name;
}
So if I create a variable Restaurant tempRest = new Restaurant(111, "Restoran DM", 0) and use it like this:
database.child("restaurants").child("1st restaurant").setValue(tempRest);
Firebase will create something like this:
restaurants
1st restaurant:
code: 111
name: "Restoran DM"
type: 0
But if you use String in setValue() like this:
String someValue = "some value";
database.child("restaurants").child("awpjawpdaw").setValue(someValue);
it will give you what you want. Example, I used this:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
String refCode = "1231231";
database.child("restaurants").child("wadawdapwodawp").setValue(refCode);
and here is what happened in database:

How to retrieve and display data from users that are logged in - Firestore

I am trying to get and display my user's information when they are logged in. (i.e: name, email, phone)
I have tried multiple snippets i have found on youtube and on stack overflow but they have failed. Most tutorials use realtime Database, which is not what i am looking for.
I have also tried making a "users" object.
private void getData(){
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users")
//.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("email:", FirebaseAuth.getInstance().getCurrentUser().getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
//Toast.makeText(getApplicationContext(),document.getId() +"==>" + document.getData(),Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(),""+ document.get("Email") ,Toast.LENGTH_LONG).show();
nameEdt.setText((CharSequence) document.get("First Name"));
emailEdt.setText((CharSequence) document.get("Email"));
phoneEdt.setText((CharSequence) document.get("Phone"));
}
} else {
Toast.makeText(getApplicationContext(),"No such document",Toast.LENGTH_LONG).show();
}
}
});
}
Database Structure:
I understand that documents in firestore are not associated with users, but i dont know how to set my code up so that it only retrieves data from the user that is signed in* It works fine for newly created accounts, but if i were to log out and sign in with a different user it will not update the "account/user information".
In short, how would I access and display my database information from signed in users?
Additional Notes: I am using Email and Password for authentication
To access your user data stored in Firestore, it shouldn't be as complicated as you thought, there's no queries needed, you just need to fetch the documents corresponding to the user's uid, and fetch the specific fields or do whatever you need with them, like this:
db.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.get().addOnCompleteListener(task -> {
if(task.isSuccessful() && task.getResult() != null){
String firstName = task.getResult().getString("First Name");
String email = task.getResult().getString("Email");
String phone = task.getResult().getString("Phone");
//other stuff
}else{
//deal with error
}
});
Original Answer:
User information is not stored in the Firestore database, they are associated with the Firebase Authentication which you set up for the log in. To retrieve the related user information, you need to use the related FirebaseAuth APIs. Use this to retrieve the current log in user:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Then you can get the name and email with something like this:
String name = user.getDisplayName();
String email = user.getEmail();
For more information, refer to the documentation.
If FirebaseAuth doesn't resolve, that probably means you didn't follow the set up guides correctly and forgot to include the dependency in your gradle file:
implementation 'com.google.firebase:firebase-auth:17.0.0'
After a couple days head butting at trying to find a solution, i have found one that is able to retrieve user information from the database. However it is important to note that because my application is not holding a lot of data so this structure works for me.
So i was essentially on the right track, but with some lack of understanding of firebase i missed a few concepts.
private void getData(){
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String current = user.getUid();//getting unique user id
db.collection("users")
.whereEqualTo("uId",current)//looks for the corresponding value with the field
// in the database
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
nameEdt.setText((CharSequence) document.get("firstName"));
emailEdt.setText((CharSequence) document.get("email"));
phoneEdt.setText((CharSequence) document.get("phone"));
// These values must exactly match the fields you have in your db
}
}
As mentioned before, documents do not associate with users, but you CAN link them together by creating a field in your db called "whatever your want" (i made mine uId). This is because firebase generates a unique id for each user when authenticated. By creating a field that holds that unique id you are able to retrieve the associated information in that collection.
How to create the field:
I created a "user" object that would grab the uid from my edit text. In my code, i passed the uid wherever i was creating/authenticating a new user/account.
FirebaseUser testUser = FirebaseAuth.getInstance().getCurrentUser(); //getting the current logged in users id
String userUid = testUser.getUid();
String uidInput = userUid;
User user = new User(firstNameInput,lastNameInput,uidInput);
db.collection("users").document(userUid)
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
note: I believe you can also add it to your hash map if you have it done that way.

How to get a key of an object that was pushed just now in Firebase?

I want to create kind of registration without password and email. I use only nickname. So,I have a User class that has nickname field and other fields. So, I want to push new user and the thing that I want is to save its key because I will need it in the future when I have to get some user's data. So how can I get a key of an object that was already pushed?
Here is my code how I push:
User user = new User() ;
user.setNick(nick.getText().toString());
user.setScore(0);
Firebase fire = new Firebase(FirebaseConfig.URL) ;
//how to get key of this object? Is it possible before pushing?
fire.push().setValue(user);
To get the key, please use the code below:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.push();
String key = keyRef.getKey();
keyRef.setValue(user);
or
Firebase fire = new Firebase(FirebaseConfig.URL) ;
String pushKey = fire.push().getKey();
fire.child(pushKey).setValue(user);
Hope it helps.
It is not possible to get pushKey before you do push().
You can try this one instead.
Firebase fire = new Firebase(FirebaseConfig.URL) ;
String pushKey = fire.push().getKey();
fire.child(pushKey).setValue(user);

request parameter in beforeSave() doesn't contain any stored values sent from android app

This is my android code :
ParseObject parseObject = new ParseObject("likes");
ParseObject parseuser=ParseObject.createWithoutData(ParseUser.class,post.getPosAuthorObjectId());
ParseObject parsepost=ParseObject.createWithoutData("posts",post.getObjectId());
parsepost.put("postAuthor",parseuser);
parseObject.put("ownerId", ParseObject.createWithoutData(ParseUser.class, ParseUser.getCurrentUser().getObjectId()));
parseObject.put("postId",parsepost);
parseObject.saveInBackground
I am trying to send some data regarding the user's id along with the post object so as to save the post object int the "likes" class and do changes in the post owner's attributes using masterkey without fetching the id of the post owner in a separate query as it is already stored in my android code .In my experimental beforeSave():
Parse.Cloud.beforeSave("likes",function(request,response){
var posts = Parse.Object.extend("posts");
var post=new posts();
var post=request.object.get("postId");
var user=Parse.Object.extend(Parse.User);
var user=new Parse.User();
var id =post.object.get("postAuthor").id;
if(id!=null){
response.success();
}
else{
response.error("The id is null");
}
});
Basically I am trying to retrieve the user id saved in the postobject and sent to the request parameter .But the output of my experiment is always null.
You're extending the Parse.Object for the user class and setting a new user using the same variable name. You can just get rid of the first var user line completely, since new Parse.User() works by default without any extending.
Anyway, try just console.log( request.object ); to see what you're actually passing in.

Categories

Resources