简体   繁体   中英

Basic Read & Write with Firebase on Android

So I started learning Android, a coworker -who is a fresh grad- at where I'm interning adviced me to learn Firebase since it is free and easy to use. I'm trying to do the most basic Read and Write operations, but for some reason I cant do it. I searched many different articles but i couldn't find why. Even said coworker tried to help me but still...

I connected to Firebase, gave needed permissions etc. and Firebase statics shows one app connected to it.

I'm following Firebase's own documents but its own code doesn't work on my app.

Said code:

// Read from the database
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);
        Log.d(TAG, "Value is: " + value);// "TAG" shows red
    }

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

The thing I'm missing might be really simple. But like I said I looked into alot of articles. For start i just want to write something on database and read a string from it and print it on screen.

Edit: Compiler error I'm getting is : https://prnt.sc/kb7kcu (Too long to paste as text)

As if code not working, Firebase docs I'm following gives compiler error. And other codes from articles i tried doesn't update the database or read from it.

Hint -> paste this code and look closer how data is structured as a map of key value pairs.

@Override 
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "dataSnapshot: " + String.valueOf(dataSnapshot));

for (DataSnapshot dataSnapshotItem : dataSnapshot.getChildren()) {
 Log.d(TAG, "Inside: " + String.valueOf(dataSnapshotItem));
}
}

I this you was not define a rule in firebase console, so you have not access to read and write permission, for permission do follow steps :

  • Go to firebase console
  • select Database and click on realtime databse
  • in a tab manu you can see Rules tab, in the rules tab set rules like follow

     { "rules": { ".read": "auth == null", ".write": "auth == null" } } 

check insertion or retrieve operation its work.

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