How can I populate a Spinner with Firebase data?

2019-08-23 09:48发布

问题:

I've trawled through online articles on threads on SO to try and figure out how I can do this, but haven't come any closer.

This thread (How to get a String List from Firebase to fill a Spinner) seems like it could be beneficial, however I'm unsure how to implement it for my own scenario.

I want the property addresses to be present in the spinner.

Apologies if the question seems vague, quite hard to explain.

MaintenanceActivity

public class MaintenanceActivity extends AppCompatActivity {

EditText editTextTitle;
EditText editTextDesc;
Spinner spinnerPrimary;
Spinner spinnerSecondary;
Spinner spinnerProperty;
Button buttonSubmit;

DatabaseReference databaseMaintenance;

ListView listViewIssues;

List<Maintenance> maintenanceList;

fDatabaseRoot.child("propertyAddress").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Is better to use a List, because you don't know the size 
        // of the iterator returned by dataSnapshot.getChildren() to
        // initialize the array
        final List<String> propertyAddress = new ArrayList<String>();

        for (DataSnapshot addressSnapshot: dataSnapshot.getChildren()) {
            String propertyAddress = addressSnapshot.child("propertyAddress").getValue(String.class);
            propertyAddress.add(propertyAddress);
        }

        Spinner spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);
        ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(MaintenanceActivity.this, android.R.layout.simple_spinner_item, areas);
        addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerProperty.setAdapter(addressAdapter);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

activity_maintenance

<Spinner
    android:id="@+id/spinnerProperty"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/fuel" />

Firebase Database

Firebase

Error

Getting several errors with this answer. I have had these errors previously, not sure how to solve them.

Errors

LogCat Error

    03-01 17:19:53.402 28517-28517/com.example.***.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                       Process: com.example.***.myapplication, PID: 28517
                                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                                           at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:445)
                                                                                           at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:493)
                                                                                           at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:994)
                                                                                           at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:990)
                                                                                           at android.widget.Spinner.measureContentWidth(Spinner.java:856)
                                                                                           at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1225)
                                                                                           at android.widget.Spinner$DropdownPopup.show(Spinner.java:1251)
                                                                                           at android.widget.Spinner.performClick(Spinner.java:780)
                                                                                           at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:442)
                                                                                           at android.view.View$PerformClick.run(View.java:24770)
                                                                                           at android.os.Handler.handleCallback(Handler.java:790)
                                                                                           at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                           at android.os.Looper.loop(Looper.java:164)
                                                                                           at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                                           at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
03-01 17:19:53.403 28517-28517/com.example.***.myapplication E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                                              at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:445)
                                                                                              at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:493)
                                                                                              at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:994)
                                                                                              at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:990)
                                                                                              at android.widget.Spinner.measureContentWidth(Spinner.java:856)
                                                                                              at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1225)
                                                                                              at android.widget.Spinner$DropdownPopup.show(Spinner.java:1251)
                                                                                              at android.widget.Spinner.performClick(Spinner.java:780)
                                                                                              at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:442)
                                                                                              at android.view.View$PerformClick.run(View.java:24770)
                                                                                              at android.os.Handler.handleCallback(Handler.java:790)
                                                                                              at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                              at android.os.Looper.loop(Looper.java:164)
                                                                                              at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                                              at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

回答1:

There so much I can help you with, but you'll need to configure the database and firebase, see docs.

After that in your activity:

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

fDatabaseRoot.child("properties").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Is better to use a List, because you don't know the size
            // of the iterator returned by dataSnapshot.getChildren() to
            // initialize the array
            final List<String> propertyAddressList = new ArrayList<String>();

            for (DataSnapshot addressSnapshot: dataSnapshot.getChildren()) {
                String propertyAddress = addressSnapshot.child("propertyAddress").getValue(String.class);
                if (propertyAddress!=null){
                    propertyAddressList.add(propertyAddress);
                }
            }

            Spinner spinnerProperty = (Spinner) findViewById(R.id.maintenanceProperty);
            ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(MaintenanceActivity.this, android.R.layout.simple_spinner_item, propertyAddressList);
            addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerProperty.setAdapter(addressAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

You had added a listener for the propertyAddress, but when the datasnapshot returned you were probing for propertyAddress again, which wouldn't work because the listener would return the property address already. The way I wrote above it will return all keys in your database, in each key you have a propertyAddress that can be retrieved. Give it a try.