Rickybobby
Rickybobby

Reputation: 305

Reading from a simple FireBase Database

I'm having some issues reading from a Firebase Database.

I have a pretty simple layout

{
  "lot" : {
    "lot1" : "low",
    "lot2" : "low",
    "lot3" : "low"
  }
}

Of course MyAppName { } is above this all.

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getInstance().getReference();

   // 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.

            lotMap = (HashMap) dataSnapshot.getValue();
            Log.d("[Directions Activity]: ", "Lot1 value ======    " +lotMap.get("lot"));
            Iterator it = lotMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry)it.next();
                Log.d("[Directions Activity]: ", "iterator " + pair.getKey() + " = " + pair.getValue());
                System.out.println();
                it.remove(); // avoids a ConcurrentModificationException
            }

        }

Here's what returns from log

 D/[Directions Activity]:: Lot1 value ======    null //null obviously
                                                //because key lot1 doesn't exist
 D/[Directions Activity]:: lot = {lot3=low, lot2=low, lot1=low}

So to me, it looks like it's returning the string {lot3=low, lot2=low, lot1=low}, but I'd like to be able to get an array, with each value if possible.

Is this achievable??

Upvotes: 1

Views: 579

Answers (3)

Ethan
Ethan

Reputation: 65

I had the same question and this is what i used. Modifying to fit the question here

private List<String> lotList;

lotList = new ArrayList<>();

DatabaseReference reference= database.getInstance().getReference().child("lot");

Now adding value event listener

reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Iterable<DataSnapshot> mData = dataSnapshot.getChildren();

            for(DataSnapshot d : mData){

                String lot_string = d.getValue(String.class);
                lotList.add(lot_string);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Upvotes: 2

Infinite Loops
Infinite Loops

Reputation: 681

There's some tweak in your code. Your

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();

should be write like this,

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference database = myRef.child("anyValueNameYouSpecifyInConsole");

Those 2 lines should be declare outside onCreate method. The one that you need to specify with addValueEventListener is the 2nd DatabaseReference, not the first one. So, it should looks like this from my example,

database.addValueEventListener (new ValueEventListener) 

and it will import method.

If you wish the data to be displayed in a particular TextView, then just findViewById the TextView you wanna use and include it in onDataChange method like so,

String x = dataSnapshot.getValue(String.class);
textViewNameDeclared.setText(x);

And don't forget to change the security rule for reading.

Upvotes: 1

CharanRoot
CharanRoot

Reputation: 6325

you can use typecast to JSONObject and parse the JSONObject

    JSONObject jsonObject= new JSONObject((Map)dataSnapshot.getValue());

    JSONObject jsonObj= (JSONObject) jsonObject.get("lot");

         for (Object key : jsonObj.keySet()) {
        //based on you key types
        String keyStr = (String)key;
        Object keyvalue = jsonObj.get(keyStr);

        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);
}

if you using java 8 than you use lamada expression.

Upvotes: 0

Related Questions