如何使用randomID将数据保存到Firebase?

时间:2018-11-09 18:43:15

标签: java android firebase firebase-realtime-database

我希望用firebase生成的随机ID替换以黄色突出显示的单词“ one”,就像我的子节点使用push方法随机生成的ID一样。 I hope this picture can better explain my question.

FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference Med_History = database.getReference("Patient_Medication_History");

Med_History.child(SignInIC.CustomUID).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot)
    {
        String taken = "Taken";
        String date = formattedDate.toString();
        String time = formattedTime.toString();
        String status = taken.toString();
        String medication = TV.getText().toString();
        String month = formattedMonth.toString();

        String combined = medication + " - " + status + " at " + time + " on " + date;
        String one = combined;

        Medication_History medication_history = new Medication_History(one);
        Med_History.child(SignInIC.CustomUID).child(month).setValue(medication_history);

        Intent Register_SignIn = new Intent(Medication_Attendance.this, HomeActivity.class);
        startActivity(Register_SignIn);
        finish();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});
public class Medication_History {

    private String One;

    public Medication_History() {
    }

    public Medication_History(String one) {
        One = one;
    }

    public String getOne() { return One; }

    public void setOne(String one) { One = one; }
}

2 个答案:

答案 0 :(得分:4)

您不能在要写入数据库的Java类(所谓的POJO)中使用动态键。但是,只要编写原始字符串值,就可以轻松使用动态键:

String combined = medication + " - " + status + " at " + time + " on " +` date;
String key = Med_History().push().getKey();
Med_History.child(SignInIC.CustomUID).child(key).setValue(combined);

这里的窍门是push()是纯客户端操作,因此您可以安全地调用它来生成在其他地方使用的ID。

顺便说一句,以上内容与习惯用法略有不同:

String combined = medication + " - " + status + " at " + time + " on " +` date;
Med_History.child(SignInIC.CustomUID).push().setValue(combined);

答案 1 :(得分:2)

尝试一下:

from tika import parser

raw = parser.from_file('test.pdf')
print(raw['myText'])

在这里,您使用DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Nov"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot ds: dataSnapshot.getChildren()){ String key=ds.getKey(); String value=ds.child("one").getValue().toString(); ref.child(key).push().setValue(value); } } @Override public void onCancelled(FirebaseError firebaseError) {} }); 检索随机ID,然后检索子节点getKey()的值,然后将随机ID one的值添加到{{1 }},使用key方法生成另一个随机ID,然后设置值。