如何从firebase检索数据到ListView?

时间:2016-08-11 10:38:58

标签: android listview firebase firebase-realtime-database

我看到了这段代码,但它在TextView中检索数据,但是我希望它在ListView中设置。
我怎么能这样做?
这是我试过的代码:

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());
    }

这是我的ListView代码:

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

2 个答案:

答案 0 :(得分:0)

您可以使用FirebaseUI for Android库。

只需添加依赖项(0.4.4适用于firebase 9.4.0库):

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

然后将ListView与适配器连接(在本例中为人员列表):

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);

答案 1 :(得分:0)

首先,您需要修复对象类型。您的适配器(和后备ArrayList)具有Message对象,但Firebase为您提供了Person对象。

假设您使适配器获取Person对象,只需添加到适配器

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);