How to Retrieve a List object from the firebase in android

后端 未结 5 1956
无人共我
无人共我 2020-11-30 03:13

I am having trouble retrieving a List from the Firebase. I have no trouble storing it, but as soon as I try to cast dataSnapshot.getValue() to ArrayList my app crashes, givi

5条回答
  •  Happy的楠姐
    2020-11-30 03:49

    Your Model

    public class TaskDes {
        private boolean done;
        private String taskDescription;
        private String taskTitle;
    
        public TaskDes() {
        }
    
        public boolean isDone() {
            return done;
        }
    
        public void setDone(boolean done) {
            this.done = done;
        }
    
        public String getTaskDescription() {
            return taskDescription;
        }
    
        public void setTaskDescription(String taskDescription) {
            this.taskDescription = taskDescription;
        }
    
        public String getTaskTitle() {
            return taskTitle;
        }
    
        public void setTaskTitle(String taskTitle) {
            this.taskTitle = taskTitle;
        }
    
    }
    

    You need to create a GenericTypeIndicator object to pass as DataSnapshot.getValue() parameter.

    In Activity

     private static final String TAG=MainActivity.class.getSimpleName();
     private FirebaseDatabase database;
     private DatabaseReference myRef=null;
    
     @Override
     protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        database=FirebaseDatabase.getInstance();
        myRef=database.getReference("ADD_YOUR_REFERECE");
    
    
        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.*/
              long value=dataSnapshot.getChildrenCount();
              Log.d(TAG,"no of children: "+value);
    
              GenericTypeIndicator> genericTypeIndicator =new GenericTypeIndicator>(){};
    
              List taskDesList=dataSnapshot.getValue(genericTypeIndicator);
    
              for(int i=0;i

提交回复
热议问题