簡體   English   中英

如何從firebase檢索數據到ListView?

[英]How to retrieve the data from firebase into a ListView?

我看到了這段代碼,但是它在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);

您可以使用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);

首先,您需要修復對象類型。 您的適配器(和后備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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM