
1. สร้าง class user
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class User { public String display_name ; public String mobile ; public String role ; public int total ; public Map<String, String> created_at; public Map<String, String> updated_at; public User(){ } public User(String display_name, String mobile, String role) { this.display_name = display_name ; this.mobile = mobile ; this.role = role ; this.total = 0 ; Map<String, String> timestampNow = ServerValue.TIMESTAMP; this.created_at = timestampNow ; this.updated_at = timestampNow ; } } |
2 . เพิ่ม method toMap
สำหรับ Map ข้อมูลของ class user ให้อยู่ในรูปแบบ Map<String, Object>
ใส่ Annotation @Exclude สำหรับบอกให้ Firebase Database ไม่ต้องสนใจ
( Marks a field as excluded from the Database )
1 2 3 4 5 6 7 8 9 10 11 |
@Exclude public Map<String, Object> toMap() { HashMap<String, Object> dataMap = new HashMap<>(); dataMap.put("display_name", display_name); dataMap.put("mobile", mobile); dataMap.put("role", role); dataMap.put("total", total); dataMap.put("created_at", created_at); dataMap.put("updated_at", updated_at); return dataMap; } |
3. เพิ่มข้อมูล User ตอน Create user
1 2 3 4 5 6 7 8 9 10 |
user = firebaseAuth.getCurrentUser(); String uid = user.getUid(); User newuser = new User(display_name,mobile,role); Map<String, Object> userValues = newuser.toMap(); Map<String, Object> childDatas = new HashMap<>(); childDatas.put("/users/" + uid, userValues); DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference(); mRootRef.updateChildren(childDatas) ; |
4.ข้อมูลที่เพิ่มใน Firebase