简体   繁体   中英

How to retrieve the data from firebase into a ListView?

I saw this code but it retrieve the data in a TextView, but I want it to be set in a ListView.
How can I do this?
This is the code I tried:

ref.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
            //Getting the data from snapshot 
            Person person = postSnapshot.getValue(Person.class);

            //Adding it to a string 
            String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n";

            //Displaying it on textview
            textViewPersons.setText(string);
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }

This is my ListView code:

messageList = (ListView) findViewById(R.id.messageList);
messages = new ArrayList<Message>();
mAdapter = new MyArrayAdapter(this, messages);
messageList.setAdapter((ListAdapter) mAdapter);

You can use the FirebaseUI for Android library.

Just add the dependency (the 0.4.4 works with firebase 9.4.0 libraries):

dependencies {
    // Single target that includes all FirebaseUI libraries
    compile 'com.firebaseui:firebase-ui:0.4.4'
}

Then connect the ListView with the Adapter (in this case a list of person):

ListView personsView = (ListView) findViewById(R.id.mylist);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
mAdapter = new FirebaseListAdapter<Person>(this, Person.class, R.layout.myItemLayout, ref) {
        @Override
        protected void populateView(View view, Person person, int position) {
             //Populate the item           
         }
    };
personsView.setAdapter(mAdapter);

First, you need to fix the object types. Your Adapter (and backing ArrayList) have Message objects, but Firebase is giving you Person objects.

Assuming you make the Adapter take Person objects, just add to the Adapter

ref.addValueEventListener(new ValueEventListener() {

     @Override
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
            //Getting the data from snapshot 
            Person person = postSnapshot.getValue(Person.class);
           mAdapter.add(person);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM