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);
Related
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.
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'm having trouble lately adding the json structure i want into firebase database. I want to add an extra attribute to my database like in the image
I tried orderstReference.child(pid).child("quantity").setValue(orderId);
but the value is overwriting each time its execute where i want them to add like in a list.
How can i add this ? and is there any useful link to learn these stuff i can't find what i want?
If you already have a node with data, and you want to add an extra child then using setValue() will override the whole node. In this case, you need to use updateChildren():
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Check this link:
https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields
Instead of set value which will override everything try update Children.
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");
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;