1

I have this model below in Firebase

model

I am trying to get all the values from child node posts using below code

  databasePostsReference = 
  FirebaseDatabase.getInstance().getReference().child("posts");

 final List<UserPostPOJO> list = Collections.EMPTY_LIST;

  databasePostsReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: entered list adding");
                UserPostPOJO post = snapshot.getValue(UserPostPOJO.class);
                list.add(post);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

but I am getting error java.lang.UnsupportedOperationException.

in the above scenario i know that error is because list is declared final and i am trying to assign value in onDataChangeMethod so is throwing error but if i am not declaring the list variable final then i cant access list variable from within the onDataChange() method how to solve this

  public class UserPostPOJO {
    String uid;
    Double elevation;
    String uri;
    String feel;

    public UserPostPOJO() {
    }

    public UserPostPOJO(String uid, Double elevation, String uri, String feel) {
        this.uid = uid;
        this.elevation = elevation;
        this.uri = uri;
        this.feel = feel;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public Double getElevation() {
        return elevation;
    }

    public void setElevation(Double elevation) {
        this.elevation = elevation;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getFeel() {
        return feel;
    }

    public void setFeel(String feel) {
        this.feel = feel;
    }
    } 

Error Log:

  05-08 22:19:49.706 6421-6421/redeyes17.com.abhi.android.iamat                      
    D/recentfragment: onDataChange: entered list adding
   05-08 22:19:49.726 6421-6421/redeyes17.com.abhi.android.iamat 
    E/AndroidRuntime: FATAL EXCEPTION: main

   Process: redeyes17.com.abhi.android.iamat, PID: 6421

   java.lang.UnsupportedOperationException

   at java.util.AbstractList.add(AbstractList.java:404)

   at java.util.AbstractList.add(AbstractList.java:425)

   at redeyes17.com.abhi.android.iamat.UI.tabs
  .RecentFragment$1.onDataChange(RecentFragment.java:78)

  at com.google.android.gms.internal.zzbpx.zza(Unknown Source)

  at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)

  at com.google.android.gms.internal.zzbra$1.run(Unknown Source)

   at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at android.os.Looper.loop(Looper.java:158)

  at android.app.ActivityThread.main(ActivityThread.java:7230)

  at java.lang.reflect.Method.invoke(Native Method)

 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller
 .run(ZygoteInit.java:1230)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Abhilash Reddy
  • 428
  • 1
  • 4
  • 19
  • 1
    Hi Abhilash. It would help if you could post the complete logs and the `UserPostPojo` class. Cheers! – AL. May 09 '17 at 02:10
  • Hi @AL. thanks for replying i posted the code after reading lot of articles i learnt that firebase operations are asynchronous operations so trying to assign values from inside the onDataChange method to a global variable would throw exception to make global variable final after declaring global final you cant assign anything here , so fix was to make callbacks and when you want to assign you have to use callback to assign but i dont know how to use callbacks can you please explain it if this all makes anysense – Abhilash Reddy May 09 '17 at 03:26
  • This is resolve your issue :https://stackoverflow.com/a/45328201/5973946 – viral 9966 Jul 28 '17 at 13:14

1 Answers1

1

To get all those values please use this code:

    databasePostsReference = FirebaseDatabase.getInstance().getReference().child("posts").child(postId);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           List<UserPostPOJO> list = new ArrayList<>();

           String elevation = (String) dataSnapshot.child("elevation").getValue();
           String feel = (String) dataSnapshot.child("feel").getValue();
           String uid = (String) dataSnapshot.child("uid").getValue();
           String uri = (String) dataSnapshot.child("uri").getValue();

          UserPostPOJO userPostPOJO = new UserPostPOJO();
          userPostPOJO.setElevation(elevation);
          userPostPOJO.setFeel(feel);
          userPostPOJO.setUid(uid);
          userPostPOJO.setUri(uri);

          list.add(userPostPOJO);
    }

          @Override
          public void onCancelled(DatabaseError databaseError) {}
};
databasePostsReference.addListenerForSingleValueEvent(eventListener);

In which postId is the unique id generated by the push() method. And notice, that the declaration of your list must be inside the onDataChange() method, otherwise, you'll get null.

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hi Alex eventually i figured it out this way , this works . I was wondering if we can assign the local list in onDataChange method to the list in global variable. – Abhilash Reddy May 09 '17 at 18:21
  • 1
    Happy to hear that you figure it out. No, you cannot make the `list` a global variable because `onDataChange` method is called asynchronously. This means that the statement that adds data to the list is executed before `onDataChange` is called and as said you'll get it `null`. If you want to learn more aboute this, pleas visit this [post](http://stackoverflow.com/questions/43576441/querying-data-from-firebase) and this [post](http://stackoverflow.com/questions/33723139/wait-firebase-async-retrive-data-in-android). – Alex Mamo May 09 '17 at 18:30
  • If you think that my answer helped you, please consider accepting it. Thanks! – Alex Mamo May 09 '17 at 18:31
  • I tried to accept it but couldnot because i have low reputation if myquestion is valid please up vote it and i have one more question if you dont mind answering it. i have this firebase child whose childs are all push keys how to sort them in ascending and descending order, basically want to retrieve recent ones but when i put in recycler view recent one is moving to the end of the recycler view how to handle this – Abhilash Reddy May 09 '17 at 18:56