Firebase setValue not creating unique child node? - android

ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (ListingModel m : list) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
myRef.push().setValue(m);
}
I am trying to save 4 objects from android app to firebase database. So I am using loop to store data into the node. It should have create 4 different child with auto id and stored the object there . But it's only storing the last model in one unique id like image below :
How can I save all four objects(data in list) with unique id each?

Fully documented at firebase
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);
}
Put your models in a map, put them, and use updateChildren

The best way to do is to use for loop.
ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (int i =0; i<list.size();i++){
ListingModel model = list.get(i);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
myRef.child(i).setValue(model);
}

So the problem was with how I set the model (Sorry for partial code in my question)
ListingModel model = new ListingModel();
model.setTitle("test0");
ListingModel model1 = new ListingModel();
model.setTitle("test1");
ListingModel model2 = new ListingModel();
model.setTitle("test2");
ListingModel model3 = new ListingModel();
model.setTitle("test3");
I was instantiating different models, but only altering value of first model.
model1, model2, and model3 was empty hence was not appearing in firebase database for being an empty object.

I think the code only read push once. And when you using the same id to write the data, you will overwrite the previous version.
ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (ListingModel m : list) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
String modelID = myRef.push().getKey();
myRef.child(modelID).setValue(m);
}
Try this, I hope it helps.
Btw, practice using updateChildren rather than setValue for saving your data.

Related

I am trying to fetch multiple values query from Firestore am i doing it right?

I used hashmap to get the data from Filter data fragment that the user wants
to display, and I want to build a dynamic Firestore fetch query, but I'm
not sure if this is the right way to do it.
I'm new to firestore query but I’ve tried to setup build a dynamic query by store the variables into the query using foreach, in the code explain I transform this code
Query filterQuery= db.collection("Property").
.whereEqualTo("noBathrooms", "5")
.whereEqualTo("noRooms", "2");
to this.
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
filterQuery=propertyRef.whereEqualTo(key,value);
}
here where I setup the query
public void filterData(){
Query filterQuery =null;
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
Log.i(key,value);
filterQuery=propertyRef.whereEqualTo(key,value);
}
dataFetch(filterQuery,R.id.rentRV);
}
and here where i am bulidng it
private void dataFetch(Query query,int rvView){
FirestoreRecyclerOptions<Property> options = new
FirestoreRecyclerOptions.Builder<Property>()
.setQuery(query, Property.class)
.build();
mAdapter = new DiscoverAdapter(options);
RecyclerView recyclerView = root.findViewById(rvView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new
LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(mAdapter);
mAdapter.startListening();
mAdapter.setOnItemClickListener((documentSnapshot, position) -> {
Property property = documentSnapshot.toObject(Property.class);
String id = documentSnapshot.getId();
Bundle mBundle = new Bundle();
mBundle.putString("id", id);
Toast.makeText(getContext(), id, Toast.LENGTH_SHORT).show();
});
}

How to create child inside child in firebase table

I am trying to create table A which has child "1" and it will also supposed to have sub children's as "LSUNL84fjMtKKc6rMlB" and "LSUNNauQJSlub-lrIC2".
You'd better tell me more. Try to share some code. The answer to this question I can give is that.
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Your Channel Name");
dbRef.child("1").child("1.1").setValue("Sameer");
As you want to create child inside A that would be 1.
Below code will create child inside A that would be 1 Then inside it. It will create a unique id for each record.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("A/1").push();
String push_id = reference.getKey(); //creating unique id here
//inserting data into Hashmap to store that data
Map data = new HashMap();
data.put("name", "my_name");
data.put("type", "type here");
//this Hashmap points to location where you want to store above data.
Map map1 = new HashMap();
map1.put("A/1/" + push_id, data);
//updateChildren will create a new child inside your Database or update it, if already exists.
reference.updateChildren(map1, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(Messages.this, "Data inserted !!", Toast.LENGTH_SHORT).show();
}
}
});

Updating Firebase Database Data with android

I am using this method to store data in my firebase database:
First i store all the data in a Model Class, called SubjectDataModel,
then i get the push key from the firebase database.
and then i set value to that particular key.
Here is my code :
SubjectDataModel:
public class SubjectDataModel {
public String id;
public String dbName;
public String subName;
public String tagline;
public int preference;
public SubjectDataModel()
{
}
public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
this.id = id;
this.dbName = dbName;
this.subName = subName;
this.tagline = tagline;
this.preference = preference;
}
}
Then i use the following code to push it to the database and then i also store the key id locally.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);
Now imagine, later in time, i want to update this data,
so i have the key id stored, so i can access it, i also have edited all the other data locally, so now if i make a SubjectDataModel Object with that data and again do ref.child(id).setValue(newSub); with the stored id, will the data be updated ? Or is there any other method to do so ?
updateChildren() is the method you are looking for, refer this documentation Firebase Read and Write Data on Android
Here's an example from documentation...
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);
}
Okay, so i tried this and it works perfectly, like i expected it to. No need for me to use maps or anything. Simplest way to update data.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
SubjectDataModel newSub = new SubjectDataModel(idForUpdate, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(idForUpdate).setValue(newSub);
So here basically, i created the object with the required data, and pushed it back to the same id with which i created a node in the firebase database, so it updates that same node with the new values.

limitToLast is being ignored

I need some help please. I'm trying to retrieve the last 2 values from the firebase database, but the following code returns all 3 values. What am I doing wrong?
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference().child("data/" + userId + "/contents/");
mDatabaseReference.limitToLast(2);
mFirebaseAdapter = new FirebaseRecyclerAdapter<MyObject, MyObjectViewHolder>(
MyObject.class,
R.layout.item,
MyViewHolder.class,
mDatabaseReference) {...}
This is how my database structure looks like:
d5TPjSY2rJRrFJUF7nPrQWcGAjh1
contents
-KqKbcnMfHwYKChXHiCA
-KqKbibX3f96ceVfoTLV
-KrBrtsHeLaWv_gEUjIT
where d5TPjSY2rJRrFJUF7nPrQWcGAjh1 is the userId.
Thanks in advance!
When you call limitToLast() (or any other of the query methods), it returns a new object. You must use this new object.
DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference().child("data/" + userId + "/contents/");
Query query = mDatabaseReference.limitToLast(2);
mFirebaseAdapter = new FirebaseRecyclerAdapter<MyObject, MyObjectViewHolder>(
MyObject.class,
R.layout.item,
MyViewHolder.class,
query) {...}

How to add new data in firebase android

This is my logic for adding new person in firebase realtime databse. But instead of making a new entry it is just updating the old data with new one.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*
new Firebase(Config.FIREBASE_URL)
.push()
.child("title")
.setValue(text.getText().toString());
*/
Firebase ref = new Firebase(Config.FIREBASE_URL);
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
ref.child("Person").setValue(person);
}
});
new Firebase(Config.FIREBASE_URL).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
What is wrong here? Can anyone help me on this?
You are using always the same ref
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
ref.child("Person").setValue(person);
Check the doc:
Using setValue() in this way overwrites data at the specified location, including any child nodes.
In your case you are overriding the same data for this reason.
You should use the push() method to generate a unique ID every time a new child is added to the specified Firebase reference.
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
DatabaseReference newRef = ref.child("Person").push();
newRef.setValue(person);
You can add a new Child to your data, such as:
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
Firebase rootRef = new Firebase(Config.USER_URL);
Firebase userRef = rootRef.child("Users");
Person newUser = new Person();
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
userRef.child(userId).setValue(newUser);
The userId varies when the logging user is different, therefore, you will always go to a new data list for a new logged-in-user in the userId under Users.
every time when you optate to insert data to database call the follwing method.
You can integrate as many attributes you optate.It will engender a unique key everytime and insert records.
public void insert2database(double latitude,double longitude,String name) {
HashMap<String,String> student=new HashMap<>();
student.put("Name",name);
student.put("Lat", String.valueOf(latitude));
student.put("Long", String.valueOf(longitude));
student.put("Phone", String.valueOf("78787500000"));
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tasksRef = rootRef.child("USERS").push();
tasksRef.setValue(student);
}
It will be in the database hierarchy like this
-database-4df17-default-rtdb
-USERS
-MUqgUu8zUpYcIaUVSsj
-Lat: "25.9405145"
-Long: "79.9100086"
-Name:"Dilroop"
-Phone: "78787500000"
-MUqoL2AUQFjH2ggKWev
-Lat: "32.9405145"
-Long: "73.9178186"
-Name: "Sanghavi"
-Phone: "78787500000"
-MUsfc-H-7KdQhrkHb_F
-Lat: "52.9405145"
-Long: "79.9175856"
-Name: "MDNSRF"
-Phone: "78787500000"
You are referencing to the "Person" child and setting it's value (setValue()) every time you click buttonSave, which only edits that one child. Try to use push() instead.

Categories

Resources