Android - 从Firebase数据库中显示ListView中的数据

时间:2016-08-10 16:32:12

标签: android firebase firebase-realtime-database

我有一个自定义listview来显示来自Firebase数据库的数据。

SectionDetails型号

public class SectionDetails {
    private String sectionCode;
    private String sectionSeats;

public SectionDetails() {
}

public SectionDetails(String sectionCode, String sectionSeats) {
    this.sectionCode = sectionCode;
    this.sectionSeats = sectionSeats;
}

public String getSectionCode() {
    return sectionCode;
}

public String getSectionSeats() {
    return sectionSeats;
}

public void setSectionCode(String sectionCode) {
    this.sectionCode = sectionCode;
}

public void setSectionSeats(String sectionSeats) {
    this.sectionSeats = sectionSeats;
}
}

FirebaseHelper上课

public class FirebaseHelper {
        DatabaseReference db;
        Boolean saved;
        ArrayList<SectionDetails> sectionDetailsArrayList = new ArrayList<>();

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;
    }

    public Boolean save(SectionDetails sectionDetails) {

        if (sectionDetails == null) {
            saved = false;
        } else {
            try {
                db.push().setValue(sectionDetails);
                saved = true;

                adapter.notifyDataSetChanged();

            } catch(DatabaseException e) {
                e.printStackTrace();
                saved = false;
            }
        }

        return saved;
    }

    private void fetchData(DataSnapshot dataSnapshot) {
        sectionDetailsArrayList.clear();

        SectionDetails sectionDetails = dataSnapshot.getValue(SectionDetails.class);
        sectionDetailsArrayList.add(sectionDetails);
    }

    public ArrayList<SectionDetails> retrieve() {
        db.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        return sectionDetailsArrayList;
    }
}

CustomAdapter上课

public class CustomAdapter extends BaseAdapter {
        Context c;
        ArrayList<SectionDetails> sectionDetailsArrayList;

    public CustomAdapter(Context c, ArrayList<SectionDetails> sectionDetailsArrayList) {
        this.c = c;
        this.sectionDetailsArrayList = sectionDetailsArrayList;
    }

    @Override
    public int getCount() {
        return sectionDetailsArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return sectionDetailsArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(c).inflate(R.layout.sections_custom_listview, parent, false);
        }

        TextView lvTvSectionCode = (TextView) convertView.findViewById(R.id.lvTvSectionCode);
        TextView lvTvSectionSeats = (TextView) convertView.findViewById(R.id.lvTvSectionSeats);

        final SectionDetails sd = (SectionDetails) this.getItem(position);

        lvTvSectionCode.setText(sd.getSectionCode());
        lvTvSectionSeats.setText("allocated seats: " + sd.getSectionSeats());

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(c, sd.getSectionCode(), Toast.LENGTH_LONG).show();
            }
        });

        return convertView;
    }
}

MainActivity上课

public class AddSection extends AppCompatActivity implements View.OnClickListener {

DatabaseReference mRef;
FirebaseHelper helper;
CustomAdapter adapter;
Button btnCreateSection;
ListView lvSectionsListOne;
String getFullSection, seats;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_section);

    lvSectionsListOne = (ListView) findViewById(R.id.lvSectionsList);

    mRef = FirebaseDatabase.getInstance().getReference().child(Constants.FIREBASE_COURSES).child("sections");
    helper = new FirebaseHelper(mRef);

    adapter = new CustomAdapter(this, helper.retrieve());
    lvSectionsListOne.setAdapter(adapter);

    btnCreateSection = (Button) findViewById(R.id.btnCreateSection);
    btnCreateSection.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    if (v == btnCreateSection) {

        getFullSection = "section 1A";
        seats = "20";

        SectionDetails sectionDetails = new SectionDetails(getFullSection, seats);

            if (helper.save(sectionDetails)) {

                adapter = new CustomAdapter(AddSection.this, helper.retrieve());
                lvSectionsListOne.setAdapter(adapter);

                adapter.notifyDataSetChanged();

            }
    }
}
}

我发布了一个类似的问题here,但这个问题有所不同。添加第一个数据时,listview中不会显示任何内容。添加第二个数据时,第一个数据显示在listview中。当添加第三个数据时,第一个数据被第二个数据替换,第二个数据显示在listview中。我尝试添加adapter.notifyDataSetChanged(),但结果仍然相同。

1 个答案:

答案 0 :(得分:3)

从Firebase数据库异步检索(并同步)数据到您的应用程序。这意味着您的sectionDetailsArrayList可能会随时修改。修改数据时,需要告诉适配器,以便更新视图。

private void fetchData(DataSnapshot dataSnapshot) {
    sectionDetailsArrayList.clear();

    SectionDetails sectionDetails = dataSnapshot.getValue(SectionDetails.class);
    sectionDetailsArrayList.add(sectionDetails);

    // tell the adapter that we changed its data
    adapter.notifyDataSetChanged();
}

这应该更新视图。但是,由于您清除了添加或更改的每个孩子的列表,该应用程序将仅显示最新添加/修改的项目。

在Firebase中设置同步数组有点牵扯,因为您必须处理所有事件类型,并且事实上evens可以按任何顺序发生。出于这个原因,我们创建了FirebaseUI library, which contains adapters from the Firebase Database to a ListView and RecyclerView