Populatate the spinner from Firebase database

2019-07-10 22:46发布

public class MainActivity extends AppCompatActivity {
DatabaseReference reference;
Spinner areaSpinner;
ArrayList<String> areas = new ArrayList<>();


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    reference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vbspinner.firebaseio.com/Location");

    areaSpinner = (Spinner) findViewById(R.id.spinner);
    DatabaseReference mref = reference.child("areas");

    FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(this, String.class, android.R.layout.simple_spinner_item, mref) {
        @Override
        protected void populateView(View v, String model, int position) {
            ((TextView)findViewById(android.R.id.text1)).setText(model);

        }
    };
    areaSpinner.setAdapter(firebaseListAdapter);
}

My Firebase database:

1

My constructor class code is

public class VBSpinner extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if(!com.google.firebase.FirebaseApp.getApps(this).isEmpty()){
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }

I would like that my spinner values are from the Firebase database (Kvp, Tn,Tvl, so on). Where do I need to change the data?

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-10 23:33

Maybe I am quite late to answer but try my method to parse firebase document items into spinner adapter

https://gist.github.com/majeytunio/9cc24a7edb06b2c2d3bbbb649ac9b602

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-10 23:34
reference = FirebaseDatabase.getInstance()
     .getReferenceFromUrl("https://vbspinner.firebaseio.com/Location");

In above code, you make reference object point to "Location" (which I think what you're trying to do. But in the following code:

DatabaseReference mref = reference.child("areas");

You make another reference called mref that (because of child("areas")) point to "https://vbspinner.firebaseio.com/Location/areas". So if you use mref in your FirebaseListAdapter, it will return null because there is no value in ".../Location/areas".

You should use reference in FirebaseListAdapter to make it work.

查看更多
登录 后发表回答