Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing array in Firebase android

I am trying to write this to my Firebase

Parent

--0 : John

--1 : Tim

--2 : Sam

--3 : Ben

I am doing this

String[] names = {"John","Tim","Sam","Ben"};
myFirebaseRef.setValue(names);

And it is not writing anything.

It works using the Chrome Console for Firebase.

Isn't this the way you write an array to firebase?

Thanks

like image 582
masood elsad Avatar asked Dec 05 '15 21:12

masood elsad


1 Answers

The .setValue() method needs a List rather than an Array.

The native types accepted by this method for the value correspond to the JSON types: Boolean, Long, Double, Map, String, Object, List, Object...

Firebase ref = new Firebase("<my-firebase-app>/names"):
String[] names = {"John","Tim","Sam","Ben"};
List nameList = new ArrayList<String>(Arrays.asList(names));
// Now set value with new nameList
ref.setValue(nameList);  

But, I recommend using a Map instead of a List. Rather than having an index based key (1,2,3...), you could use the name as the key so it's easier to retrieve.

Firebase ref = new Firebase("<my-firebase-app>/names"):
HashMap<String, String> names = new HashMap()<String, String>;
names.put("John", "John");
names.put("Tim", "Tim");
names.put("Sam", "Sam");
names.put("Ben", "Ben");
ref.setValue(names);

And now if you want to retrieve the data, you just need to know the name.

Firebase ref = new Firebase("<my-firebase-app>/names"):
Firebase johnRef = ref.child("john");
johnRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
       System.out.println(snapshot.value); // the String "John"
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

Read the Firebase docs for more information.

like image 68
David East Avatar answered Oct 23 '22 10:10

David East