Filling data to spinner from firebase database

2019-08-20 09:47发布

问题:

My FireBase DataBase is like this:

I want to get all the values from groupname as a String List or any form of list and use it to populate a Spinner. The problem I am getting is that it doesn't retrieve any value . This is my actual code:

 @Override
    protected void onStart() {
        super.onStart();
        databaseGroups.child("Groups").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                final List<String> areas = new ArrayList<String>();
                for (DataSnapshot areaSnapshot: dataSnapshot.getChildren()) {
                    String areaName = areaSnapshot.child("groupname").getValue(String.class);
                    areas.add(areaName);
                    System.out.println("Group Names are ::::::::::::::::::::::"+areas);
                }
                // Spinner element
                Spinner spinner = (Spinner) findViewById(R.id.spinner);

                // Creating adapter for spinner
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(member_auth.this, android.R.layout.simple_spinner_item, areas);

                // Drop down layout style - list view with radio button
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                // attaching data adapter to spinner
                spinner.setAdapter(dataAdapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

The Spinner is empty, plse help...

回答1:

Once check databaseGroups value. Does it equal to

databaseGroups = FirebaseDatabase.getInstance().getReference();

or somthing else. Can you provide some error log you got?



回答2:

I actually found the solution, the onStart function was not trigerring at all. so i put the whole in another function, and it works flawlessly.