0

I want to retrieve the structure as follows:

Courses>Course>Programme>Sem>{SubjectName}>total>attendance>orderbykey.equalsTo(uid)

I have a issue iterating through the subjects where the key is dynamic, like for for eg. here the key for one is PA and other is PC and it will be dynamically pushed by the user and will be different for every Sem.

I have tried this:

Query subjectQuery = mDatabaseRef.child("courses/"+user.getCourse()+"/"+user.getProgramme()+"/"+user.getSem()+"/subjects");
    subjectQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                Log.d("subjects", String.valueOf(dataSnapshot.getChildrenCount()));
                sub = new Subject[(int) dataSnapshot.getChildrenCount()];
                int i = 0;
                for (DataSnapshot subjectSnapShot: dataSnapshot.getChildren()){
                    sub[i] = new Subject(subjectSnapShot.getValue().toString());
                    Log.d("subject_class","sub["+i+"] : "+sub[i].getName());
                    i++;
                }
            }else{
                Toast.makeText(DashboardActivity.this, "Data Not Found", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Toast.makeText(this, String.valueOf(sub.length), Toast.LENGTH_SHORT).show();

As The Listener is Async the toast makes the app crash and gives a NullPointerException as the sub is still null

edited: the reason for this is to get the subjects and pass it to the fragment. please suggest if anyone has a better way to go around the problem

Firebase Structure Here

Marmik Thakkar
  • 108
  • 1
  • 6
  • Your question title is very different from your actual problem. I think [this answer](https://stackoverflow.com/a/43576696/4916627) will help you understand and solve your problem. – André Kool Apr 17 '18 at 13:36
  • @andrekool Well i have issue iterating through dynamic key values so this is a snippet which i wrote to get the key values before and pass it to my fragment, else i would have have to nest addListenerForSingleValueEvent or ValueEventListener which makes no sense as it would mean if the head listens a change then only it will detect a change in the nested ones. Could you suggest something better to iterate through the subjects first? – Marmik Thakkar Apr 19 '18 at 13:35
  • Keys will be dynamically pushed by the user! How you gonna ensure that keys be unique?! Because **keys are always unique within their context**. – MuhammadAliJr Apr 19 '18 at 13:48
  • @MuhammadAliJr In my app only certain users can write these keys and on their side i will keep a check whether their the keys are not repeating using the snapshot.getKey() – Marmik Thakkar Apr 19 '18 at 14:28

0 Answers0