Reputation:
This is my code
final String name = subjectEditText.getText().toString();
final String desc = descEditText.getText().toString();
String DateNow = new SimpleDateFormat("ddmmyyyy", Locale.getDefault()).format(new Date());
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("products/" + DateNow);
myRef.setValue(name, desc);
But the two values are not being saved, only the name.
Upvotes: 0
Views: 64
Reputation: 54
Using map.
String DateNow = new SimpleDateFormat("ddmmyyyy",
Locale.getDefault()).format(new Date());
FirebaseDatabase database =
FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("products/" + DateNow);
final String name =
subjectEditText.getText().toString();
final String desc =
descEditText.getText().toString();
Map<String, Object> data = new HashMap<> ();
data.put("name", name);
data.put("desc", desc);
myRef.set (data).addOnSuccussListener(...)...;
You can instead replace
data.put("name", name);
data.put("desc", desc);
with
data.put("name_desc_array", name_desc_array);
But you have to create array with
ArrayList<String> name_desc_array = new ArrayList();
name_desc_array.add ("name");
name_desc_array.add ("desc");
Remember, using map is the best way
Upvotes: 0
Reputation: 599621
The second value you pass to setValue
is being set as the priority of the node. This priority isn't visible in the Firebase console, but it stored and retrieved through the API. If you get a DataSnapshot
for the node, you can use getPriority()
to get the desc
back.
Priorities are mostly a leftover from the olden days of this API, and serve very little useful purpose these days.
Nowadays if you want to store multiple values under a node, you should give them names. For example:
final String name = subjectEditText.getText().toString();
final String desc = descEditText.getText().toString();
String DateNow = new SimpleDateFormat("ddmmyyyy", Locale.getDefault()).format(new Date());
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("products/" + DateNow);
Map<String, Object> values = new HashMap<>();
values.put("name", name);
values.put("desc", desc);
myRef.setValue(values);
This will create a little JSON structure under DateNow
with:
{
"name": "the name from the text field",
"desc": "the value from the desc field"
}
You can then read these value back with:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("database", dataSnapshot.child("name").getValue(String.class);
Log.i("database", dataSnapshot.child("desc").getValue(String.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Upvotes: 0