How to create a node and update it on Firebase - java

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");

Related

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

How to add child to existing data in Firebase

How would I do to add a child to existing data in a Firebase database through an Android application? Here is what my Firebase database looks like:
I want to be able to save data as children to the parent values in the image, so that I can have lists of values. The problem is that I do not know how to reach these existing values with auto-generated id's from my application, I want to be able to save a value as a child to the current choice of value in a spinner.
Here is the code that pushes the "lists" to the database:
private void onAddListClick()
{
String text = listEditText.getText().toString();
String refPath = "CategoryList";
if (text.trim().length() > 0)
{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(refPath);
myRef.push().setValue(text);
listEditText.getText().clear();
finish();
} else
{
//...
}
}
And here is the code that is supposed to save the value/task in the correct list depending on the spinner choice:
private void onAddTaskClick()
{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("CategoryList");
String text = taskEditText.getText().toString();
String spinnerValue = spinner.getSelectedItem().toString();
if (text.trim().length() > 0)
{
list.add(new Task(text));
recyclerViewAdapter.notifyDataSetChanged();
taskEditText.getText().clear();
//Change me!!
//myRef.push().setValue(text);
} else
{
//...
}
}
EDIT:
A possible solution to my question would be to get hold of the auto-generated id and then to add a child to that existing value. I know there are other questions with answers for getting the id instantly when pushing the value to the database, however I want to be able to get the id later when I want to add a child to the already existing value.
If spinnerValue is the key in the database of the item they clicked in the spinner, you can add a child to that node with:
String spinnerValue = spinner.getSelectedItem().toString();
if (text.trim().length() > 0)
{
list.add(new Task(text));
recyclerViewAdapter.notifyDataSetChanged();
taskEditText.getText().clear();
myRef.child(spinnerValue).push().setValue(text); // 👈 change here
} else

Adding a list inside a node in firebase

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.

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);

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

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;

Categories