简体   繁体   中英

Can't read or write to the firebase realtime database (android studio)

I think I connect to the firebase because I received the message for the terminal which is

I/FirebaseInitProvider: FirebaseApp initialization successful

And I think I set the rules correct

{
"rules": {
    ".read": true,
    ".write": true
  }
}

Here are my read and write codes.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");

    myRef.setValue("Hello, World!");

}

@Override
protected void onStart() {
    super.onStart();
    // Read from the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            System.out.println(value);
            Log.d("T", "Value is: " + value);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("F", "Failed to read value.", error.toException());
        }
    });
}
}

And a very weird thing, it can print the value, but the data is never get updated in the console.

printed value

I/System.out: Hello, World!
D/T: Value is: Hello, World!

but in the console... 在此处输入图像描述

You have to push the messages so they don't get updated each time:

// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

//use a map
Map<String, String> message = new HashMap<>();  
message.put("text", "Hello, World!");

myRef.push().setValue(message);

After this your messages will look like this:

message
|
|----------randomID
           |-----text : "Hello, World!"
|
|

To read the messages text:

@Override
protected void onStart() {
    super.onStart();
    // Read from the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds: dataSnapshot.getChildren()){
              //this loops through all random ids and grabs the text 
              //you can maybe store the text in some list and do whatever.
              String value = ds.child("text").getValue(String.class);
              System.out.println(value);
              Log.d("T", "Value is: " + value);

             }

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("F", "Failed to read value.", error.toException());
        }
    });
}
    tableUser.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
         tv.setText(dataSnapshot.getValue().toString());
            Log.e(TAG, "onDataChange: " + dataSnapshot.getValue().toString());
            Toast.makeText(MainActivity.this, "" + dataSnapshot, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Yes, I encounter this problem too. I connect to firebase via a tool on IntelliJ and I can Logcat firebaseProjectID which means it already connect to firebase. So I create a new project and copy all the code from the old project, connect to firebase via tool and it works normally with both read and write DB without touching any code. This is a very annoying solution but easier than trying to find a solution on the internet, which I still can't find them.

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