This is my code for adding records in Firebase. there's variable outside called restauCount valued (int) as 1
public void sendMessage(){
int restauCount = 1;
String identifier ="Restaurant" + restauCount;
Firebase userRef = firebaseRef.child("Caloocan");
EditText nameInput = (EditText) findViewById(R.id.nameTxt);
String name = nameInput.getText().toString();
EditText locInput = (EditText) findViewById(R.id.locationTxt);
String location = locInput.getText().toString();
EditText typeInput = (EditText) findViewById(R.id.typeTxt);
String foodtype = typeInput.getText().toString();
if (!name.equals("")){
Map<String, String> caloocan = new HashMap<String, String>();
caloocan.put("resname", name);
caloocan.put("resloc", location);
caloocan.put("foodtype", foodtype);
Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
users.put(identifier,caloocan);
userRef.setValue(users);
restauCount++;
}
}
When i run the sendessage() again. i will type in the fields and when i click ADD which is the sendMessage it will be added in FireBase , however when i add new data. IT OVERWRITES THE OLD DATA INPUTTED ? HOW CAN I ADD MULTIPLE DATA IN FIREBASE WITHOUT OVERWRITING THE DATA?
restauCount was created to increment the number of Restaurant i inputted,
userRef.push().setValue(users);
The push() method generates a unique key every time a new child is added to the specified Firebase reference
Use
userRef.setValue(users).push();
instead of userRef.setValue(users);
You are using always the same ref
String identifier ="Restaurant" + restauCount;
Firebase userRef = firebaseRef.child("Caloocan");
userRef.setValue(users);
restauCount++;
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.
Firebase userRef = firebaseRef.child("Caloocan");
Firebase newRef = userRef.push();
newRef.setValue(users);
//to get the key
String key = newRef.getKey();
you need to update the identifier it stays the same :
int restauCount = 1;
String identifier ="Restaurant" + restauCount;
try something like :
long restauCount = System.currentTimeMillis();
String identifier ="Restaurant" + restauCount;
here each time you send a sendMessage() your identifier got a specific id as the current time in milliseconds + "Restaurant"
if its important to keep int numbers let me know
Related
edit = (EditText) findViewById(R.id.addCat);
addCate = edit.getText().toString();
Catcat add;
String x = myRef.child("sfasf").push().getKey();
add= new Catcat(addCate,x);
myRef.push().setValue(add);
When I use this code, the String x differs from the actual push id by 1 letter at the end. Is this intentional or am I using the method wrong?
You called push() twice, which leads to two different keys. There are a couple ways to push an object onto Firebase and get the key.
You can get the key first, then use the key to get and update the child.
String x = myRef.child("sfasf").push().getKey();
add = new Catcat(addCate,x);
myRef.child("sfasf").child(x).setValue(add);
Or you can first push the object then retrieve the key.
add = new Catcat(addCate,x);
DatabaseReference ref = myRef.child("sfasf").push(add)
String x = ref.getKey()
Now i'm following android tutorial with firebase from youtube
when i save the data the json data format the parent key is defaulted like this 1
1:
I want to save the data not default key auto
I want to save the data format like this
When i save the data like this
//regi button
mAdd_mypet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Pets");
String petid = reference.push().getKey();
RadioGroup rg = (RadioGroup)findViewById(R.id.genderGroup);
RadioButton seletedRdo = (RadioButton)findViewById(rg.getCheckedRadioButtonId());
final String selectedValue = seletedRdo.getText().toString();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("petname", mPetName.getText().toString().trim());
hashMap.put("petbreed", mPetBreed.getText().toString().trim());
hashMap.put("petweight", mPetWeight.getText().toString());
hashMap.put("birthday", mDisplayDate.getText().toString());
hashMap.put("intro", mIntro.getText().toString());
hashMap.put("gender", selectedValue);
hashMap.put("petimage", myUrl);
reference.child(petid).setValue(hashMap);
startActivity(new Intent(MyPetRegActivity.this, MyPetListActivity.class));
finish();
}
});
but the result save data parent key is auto
how can i do save the data clearly not make defualt not like
'2okCgbdTqlVgk6oDqPi'
i want to make like this -> 'firebase_01'
sorry my fool english...
This line String petid = reference.push().getKey();
Change it for something like String petid = 'firebase_01'
When you do reference.child(petid).setValue(hashMap); the child method set the id, you can come with your own or ask firebase to generate one (which you are doing on your project), more info here
my code:
lateadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String anahtar=databaseReference.getKey().toString();
final String kisiId = user.getUid().toString().trim();
final String kisiAd = user.getDisplayName().toString().trim();
final String yayinlananYorum = edituruneYorumyap.getText().toString();
List<Urun> urunListesi = new ArrayList<>();
Urun urunler = new Urun(kisiId, kisiAd, yayinlananYorum, urununAdi.getText().toString());
urunListesi.add(urunler);
String key = databaseReference.push().getKey();
databaseReference.child(anahtar).child("urunYorum").setValue(urunler);
}
});
databaseReference.child(anahtar).child("urunYorum").setValue(urunler);
->i think i need a change here but i don't know.
I want to add data to the child's pre-existing reference.
when I run this encoding, it creates a new reference. Unfortunately, it adds a new record.
How can I fix?
This line String key = databaseReference.push().getKey(); creates a new unique reference, that you then write to. If you want to write to an existing reference, you'll need to know the key of that reference, typically by reading it from the UI item that the user clicked on.
Note that calling setValue() replaces all data at the location. If you want to update a subset of the data, or add new properties, you will either have to call setValue() on a lower level, or call updateChildren().
So for example:
databaseReference.child(anahtar).child("urunYorum/newProperty").setValue(urunler);
Or:
Map<String,Object> values = new HashMap<String,Object>();
values.put("kisiId", kisiId);
values.put("kisiAd", kisiAd);
databaseReference.child(anahtar).child("urunYorum").updateChildren(values);
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);
How to give user defined key value in push(), instead of unique value created by push?
This is what am currently doing:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").push().setValue(user);
.push() will create a new item with a unique reference.
You can use updateChildren() to update instead. For example,
User user=new User(Editname.getText().toString(),Editpid.getText().toString(),Editsem.getText().toString());
Map<String, Object> itemValues = user.toMap();
Map<String, Object> childUpdates = new HashMap<>();
// Define the key value here
String username = "yourKeyValueHere";
childUpdates.put("/users/" + username, itemValues);
mDatabase.updateChildren(childUpdates);
You might have to add something similar to the following to your User class.
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("name", name);
result.put("pid", pid);
result.put("sem", sem);
return result;
}
Simplest way is to specify the child key with the child method:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
mRef.child("users").child(user.pid).setValue(user);
Where I specify user.pid, you can use whatever unique key you use to identify the user (typically when using Firebase Authentication this would be user.getUid()).
This is one way to do it assuming we want to use the User's name as unique key:
User user = new User(Editname.getText().toString(),
Editpid.getText().toString(),Editsem.getText().toString());
String uniqueKey = user.getName();
//You could use something else for quick reference since two users can have the same name
mDatabaseReference.child("users").child(uniqueKey).push().setValue(user);