简体   繁体   中英

How do I add data to the Firebase database?

I cannot add any data on the Firebase Realtime Database. Database connections are ok but I cannot add any data. When I click to button, add to data on my database.

MainActivity.java - codes

        private FirebaseDatabase database;
        private DatabaseReference dbRef;
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String plan,note,date,time,remb,eventId;
                plan = etplan.getText().toString();
                note = etnote.getText().toString();
                date = etdate.getText().toString();
                time = ettime.getText().toString();

                if (remember.isChecked()==true){
                    remb= "true";
                }
                else{
                    remb = "false";
                }
                database = FirebaseDatabase.getInstance();
                dbRef = database.getReference("events");
                eventId = dbRef.push().getKey();
                event = new Events(plan,note,date,time,remb);
                dbRef.child(eventId).setValue(event);

                Toast.makeText(MainActivity.this,"Events Added SUCCESSFULLY!", Toast.LENGTH_SHORT).show();
            }
        });

Events.java - codes

public class Events {
    String plan;
    String note;
    String date;
    String time;
    String remb;

    public Events(){

    }

    public Events(String plan, String note, String date, String time, String remb){
        this.plan=plan;
        this.note=note;
        this.date=date;
        this.time=time;
        this.remb=remb;
    }
}

I am getting the following error in run : at com.cdirect.agenda.MainActivity$4.onClick(MainActivity.java:118)

this code:

dbRef.child(eventId).setValue(event);

and before this code of eventID (is String)

eventId = dbRef.push().getKey().toString();

What you can do is to add a listener to setValue(event) method like this:

dbRef.child(eventId).setValue(event)
     .addOnCompleteListener { task ->
            if(task.isSuccessful) {
                 Toast.makeText(this, "Successful", Toast.LENGTH_SHORT).show()
                 } else {
                 Toast.makeText(this, task.getException().getMessage(),
                         Toast.LENGTH_SHORT).show();
                }
      }

Now task.getException().getMessage() will let you know what the actual problem is about saving your event data.

Also, don't forget to check the database rules that read and write is set to true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM