How do I get randomly generated userID from .push() in Firebase - java

Currently I am adding my user class to a firebase database using this code:
public void onClick(View v)
{
Firebase ref = new Firebase("https://xxxxxx.firebaseio.com/");
createAccount(emailString, passwordString);
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
ref.child("users").push().setValue(user);
}
Right now, since I use the .push() method, I am creating a unique ID in my database. How do I pull that unique ID? I looked at this tutorial but I don't understand how to implement it.

DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); //get the reference to your database
User user = new User ();
user.setEmail(emailString);
user.setPassword(passwordString);
String yourKey = dbRef.child("users").push().getKey(); //get the key
dbRef.child("users").child(yourKey).setValue(user); //insert user in that node
But if you want to access that node (yourKey) later, you will need to store it in some sort of permanent storage like a database on your web server.

Great example of how to get key check these docs out helped me a lot.
Firebase Docs
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;

Related

How to check a phonenumber that already added to the firestore database?

Here in the Firestore databases is a collection called "Users", In that collection, there are 29 documents(States) and in each of that documents there are many collections(Districts). This collection includes many documents these documents include the user's data along with numbers).
so how do we check the phone number that has already been added to the database?
I write something like this
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
CollectionReference usersRef = firestore.collection("Users");
String phoneNumber = "1234567890";
usersRef.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Map<String, Object> data = document.getData();
for (String key : data.keySet()) {
Object value = data.get(key);
if (value instanceof String && ((String) value).equals(phoneNumber)) {
isRealAvailable = true;
Toast.makeText(OtpActivity.this, "Number found", Toast.LENGTH_SHORT).show();
// Phone number found
break;
}
}
}
} else {
isRealAvailable = false;
Toast.makeText(OtpActivity.this, "No number found, create an account!", Toast.LENGTH_LONG).show();
}
// Handle error
}
});
(the number is not a String value)
I don't know how to retrieve these details from different document names.
How do we get the Phone Number from the document? if it exists.
What I wanted is, I'm building a blood donors app, where people can register using their phone numbers. From different countries. So when a user sign-up with proper details, he can go to the main screen. Whenever he logout and login, he doesn't need to update the details again. As we know phone number login and signup are the same. Also, I want to separate the states and places in different documents and collections. I added the location permission and perspective codes so the country and states are chosen automatically. (will get the users location)
When you're calling get() on the following collection reference:
CollectionReference usersRef = firestore.collection("Users");
It means that you're trying to get all user documents that exist in the Users collection. As soon as you get all users, you then check the phoneNumber against the one that you find in the database, which is bad since you'll need to pay for a document read even for the users that do not have that particular phone number. What you have to do instead is to create a query that should only return the documents that you are interested in.
On the other hand, your actual database schema isn't quite helping you to achieve that. In the NoSQL world, we are usually structuring a database according to the queries that we want to perform. So if you need to get all users from Brooklyn / New York that have a particular phone number, I would recommend you have a schema that looks like this:
db
|
--- users (collection)
|
--- $uid (document)
|
--- city: "New York"
|
--- borough: "Brooklyn"
|
--- mobNumber: 720555
And in code, it should look like this:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference usersRef = db.collection("users");
Query queryByMobNumber = usersRef.whereEqualTo("city", "New York")
.whereEqualTo("borough", "Brooklyn")
.whereEqualTo("mobNumber", 720555);
queryByMobNumber.get().addOnCompleteListener(/* ... /*);
So in Firestore, chaining multiple whereEqualTo calls will work perfectly fine.
Besides that, I see that you are changing a boolean value inside the callback, which will not be seen outside the callback because Firebase API is asynchronous. If you want to learn more about that, I recommend you check this resource. Here is the corresponding repo.

Finding random (auto) id assigned to our document by Firestore

I know its a bit weird question but how can I access the unique (auto) id google firebase generates for my document whenever I create new document. For example this is my code
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
How can I know that what is the id generated for this document of "newPost" because i want to use that id in my code and at the same time i dont want to send custom id because it won't be unique
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
As you've likely discovered, .set() returns a Promise <void> .
But what you've ignored is .set() only operates on a DocumentReference - which is what you get from postCollections.document(). A DocumentReference has properties id and path - it is the .document() that creates a new, unique, documentId.
So:
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
val newRef = postCollections.document()
newRef.set(newPost)
And now you have the document id (and path) available as properties of newRef.
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference

I am trying to access the values of a particular key from the Firebase database.I want to update those values and update it

[This is my json dataThis is my code ][1]
I am trying to change the value of the key-value pair in the Firebase database.
Lets suppose I have a key value like this:"chemistry":"20".I want to extract the value of the key chemistry and want to update it after adding some number like I add 10 to it so my final key value pair will become "chemistry":"30" .But I am unable to access the key can someone help me with this.
My code goes here:
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInWithEmail:success");
//extracting the current user from the databse
FirebaseUser user = mAuth.getCurrentUser();
//getting the uid of the user
String Uid=user.getUid();
//getting the databse instance for the particular user
FirebaseDatabase database = FirebaseDatabase.getInstance();
//setting the path to the Users/Uid to read the key values
DatabaseReference myRef = database.getReference("Users/"+Uid);
//textView.setText(myRef);
String key=myRef.child("chemistry").getKey();
textView.setText(key);
// myRef.setValue("Hello, World!");
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithEmail:failure", task.getException());
Toast.makeText(TestActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
my json is here:
{
"Users" : {
"LMn5GeZixNQNpdQhGzdKNbTgIw53" : {
"chemistry" : "20",
"email" : "umairnsr87#gmail.com",
"lastScore" : "0",
"maths" : "0",
"name" : "umair",
"phone" : "123456789",
"physics" : "0"
}
}
}
In general, you should add some attempt code of what you are trying to achieve, so that others can better guide you to fix your problems. People is not supposed to write code for you.
Anyway, if your collection is called users. then you would retrieve a specific ID in this way:
db.collection("users").doc(THEID).get()
.then( data => {
console.log(data)
})
use .add(jsondata) and .set(jsondata) for ading and updating
here's the documentation:
https://firebase.google.com/docs/firestore/?gclid=CjwKCAjwm4rqBRBUEiwAwaWjjK7_CnO37twhvxrw2-WUxep6ykpTEaJiGnmojoBz74TNylodfkL7DxoCE9gQAvD_BwE
I am trying to change the value of the key-value pair in the firebase database.
In general when you want to update a value of a property, you should use DatabaseReference's updateChildren(Map update):
Update the specific child keys to the specified values.
Regarding the second issue:
Lets suppose I have a key value like this:"chemistry":"20".I want to extract the value of the key chemistry and want to update it after adding some number like I add 10 to it so my final key value pair will become "chemistry":"30"
Above, I showed you how you can simply update the value of a property, however, if you want to increment the value of your chemistry field in a multiuser environment, to have consistent data, I recommend you see my answer from this post, where I have explained how to update a score field using Firebase Transactions.

How to create a node and update it on Firebase

I have to store my location in Firebase and keep it updated. I currently can store it, but when location changes it creates a new node, how can I make it to create only one node at the start of my app and update it every time the position changes? Thanks.
Code:
DatabaseReference rootRef = database.getInstance().getReference();
String key = firebaseData.child("Posicion/").push().getKey();
LatLng latLng = new LatLng(latitude,longitude);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/Posicion/" + key, latLng);
rootRef.updateChildren(childUpdates);
It creates this structure: https://i.stack.imgur.com/SlOQq.png
You are changing node keys between insert and update.
Try to create nodes in the following format, for example:
-locations
-- id (this one must be an unique id you create when app starts or the logged user id)
---- currentLatitude: "xxxxxx"
---- currentLongitude: "yyyyyy"
In this case, the implementation will be something like:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mDatabase.child("locations").child(user.getUid()).child("currentLatitude").setValue("xxxxxx");
mDatabase.child("locations").child(user.getUid()).child("currentLongitude").setValue("yyyyyy");

How to push data into firebase without overriding

I want insert these notes in firebase realtime data.. how to generate the keys(Note1, Note2, Note3.....) and push the note along with it like the picture attached... i also tried generating random keys but it always overriding the data which i don't want..
String note = ETNote.getText().toString();
DatabaseReference noteRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");
String noteID = noteRef.push().getKey();
Map newPost = new HashMap();
newPost.put(noteID, note);
noteRef.setValue(newPost);
Toast.makeText(HomeActivity.this, "Note Saved", Toast.LENGTH_LONG).show();
Try this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Notes").push();
ref.child("note1").setValue(notes1);
ref.child("note2").setValue(notes2);
ref.child("note3").setValue(notes3);
then you will have:
Notes
randomid
note1: notes
note2: notes
note3: notes
There are two ways.
The first is to address each child node directly, similar to what Peter shows in his answer:
noteRef.push().setValue(newPost);
The other is to create a map of (potentially multiple) new notes, and then update the noteRef:
String noteID = noteRef.push().getKey();
Map newPost = new HashMap();
newPost.put(noteID, note);
noteRef.updateChildren(newPost);

Categories