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
Related
I wanted to add a string values to a realtime firebase database with the firebase UID being the name and the string being the value. When I use the below code it makes the UID a parent node and set the value to a child node.
ReferralCode referralCode = new ReferralCode(refCode); databaseReference.child("referralCodes").child(userId).setValue(referralCode);
I wanted the values to be populated as the second one. But with the above code,i get the first result. I'm going to search for the referral codes afterwards,so i think it would be faster if the values are populated as the second one to avoid accessing a child node which will be time consuming for large database entities.
When you are using a Model like you created ReferralCode and using it to with .setValue(referralCode) then Firebase will automatically create it as the child with attributes your ReferralCode.java has. Example below:
public class Restaurant {
private int code;
private int type;
private String name;
}
So if I create a variable Restaurant tempRest = new Restaurant(111, "Restoran DM", 0) and use it like this:
database.child("restaurants").child("1st restaurant").setValue(tempRest);
Firebase will create something like this:
restaurants
1st restaurant:
code: 111
name: "Restoran DM"
type: 0
But if you use String in setValue() like this:
String someValue = "some value";
database.child("restaurants").child("awpjawpdaw").setValue(someValue);
it will give you what you want. Example, I used this:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
String refCode = "1231231";
database.child("restaurants").child("wadawdapwodawp").setValue(refCode);
and here is what happened in database:
Here's how I put value in firebase:
exDBKey1 = exerciseList.get(position).getExerciseId();
exerciseName = exerciseList.get(position).getExerciseName();
weekExerciseModel = new WeekExerciseModel(exerciseName, exDBKey1);
executedExercises.child(userID).child("WeeklyExercises").child(exerciseWeek)
.child(exerciseDay).push().setValue(weekExerciseModel);
Here's my firebase which gets deleted after I re-open the app:
The dynamic data are from this code
exerciseReference.addListenerForSingleValueEvent (new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
WeekExerciseModel weekExerciseModel = dataSnapshot1.getValue(WeekExerciseModel.class);
if("Very Active".equalsIgnoreCase(weekExerciseModel.getStatus()) &&
"1".equalsIgnoreCase(weekExerciseModel.getExerciseDay()) &&
"2".equalsIgnoreCase(weekExerciseModel.getExerciseWeek()) &&
"Gain".equalsIgnoreCase(weekExerciseModel.getUserGoal())
&& "None".equalsIgnoreCase(weekExerciseModel.getUserDisease())){
exerciseList.add(weekExerciseModel);
Log.e("exercisenameSnapshot", String.valueOf(dataSnapshot1.getKey()));
}
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("FitureUser", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("exerciseIDW2D1", weekExerciseModel.getExerciseId());
// editor.putInt("exerciseSum",day);
editor.putString("exerciseDay","Day 1");
editor.putString("exerciseWeek","Week 2");
editor.putString("exercisenameSnapshot", String.valueOf(dataSnapshot1.getKey()));
editor.apply();
It looks like this after it gets deleted
Can you try with static values but also try
executedExercises.child(userID).child("WeeklyExercises").child(exerciseWeek).child(exerciseDay).setValue(weekExerciseModel);
And see if this helps.
Also, how are you calling your firebase database path - .getInstance().getReference() line when you open the app?
My next question would be on why you have a key map of exDBKEY1 in your weekExerciseModel but the key name is showing as exerciseID in your database when it probably should show as exDBKEY1 just like how your exerciseName variable shows as exerciseName for the key name. You might need to show more of the code such as where the exerciseID comes form because it looks like a firebaseUID which means it's going to the database to get it which could be clearing out your data from wherever else the code for that UID is.
Instead of using the same Parent node which later I found out that is what's causing the wiped out data. So I made a new Parent node still the same process but it only contains the data that I need.
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);
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
I have 3 edit-texts in my activity (Name, mobile number, occupation) and a button (Save). I want to save these three data to Parse-cloud every-time when user clicks on the button.
Then new activity to display with a image in imageview that should be saved with the corresponding mobile number.
Saving data to parse is very simple. In your button click handler you just need to get the 3 values that you are interested in then create the new parse object;
String name = nameEditText.getText().toString();
String mobileNumber = mobileNumberEditText.getText().toString();
String occupation = occupationEditText.getText().toString();
ParseObject dataObject = new ParseObject();
dataObject.put("name", name);
dataObject.put("mobilenumber", mobileNumber);
dataObject.put("occupation", occupation);
dataObject.saveInBackground();
Somewhere in your app you will need to remember to set your application id and key as supplied to you by Parse. I tend to do it in an Application object in the onCreate method;
public void onCreate() {
Parse.initialize(this, "Your Application Id", "Your Client Key");
}
The Parse Object API is very simple to work with I tend to find as there isn't too much to get your head around. If you are completely new to Parse and you haven't already then I would recommend taking a look at their quickstart.