Android - 更新和删除Firebase数据库

时间:2016-08-11 10:53:24

标签: android listview firebase firebase-realtime-database

我正在尝试更新和删除Firebase数据库中的数据。

SectionDetails型号

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

public SectionDetails() {
}

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

@Exclude
public String getSectionKey() {
    return sectionKey;
}

public String getSectionCode() {
    return sectionCode;
}

public String getSectionSeats() {
    return sectionSeats;
}
}

FirebaseHelper上课

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

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

private void fetchData(DataSnapshot dataSnapshot) {

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

    adapter.notifyDataSetChanged();
}

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) {
            adapter.notifyDataSetChanged();
        }

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

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return sectionDetailsArrayList;
}
}

CustomAdapter上课

public class CustomAdapter extends BaseAdapter {
        DatabaseReference updateRef;
        String key;
        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) {

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

    updateRef = FirebaseDatabase.getInstance().getReference().child(Constants.FIREBASE_COURSES).child("sections");

    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog d = new Dialog(CustomAdapter.this);
            d.setContentView(R.layout.section_custom_dialog);

            Button btnUpdate = (Button) d.findViewById(R.id.btnUpdate);
            Button btnDelete = (Button) d.findViewById(R.id.btnDelete);

            btnUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String code = "1B";
                        final String seats = "20";

                        updateRef.addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {
                                            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                                SectionDetails updateSD = snapshot.getValue(SectionDetails.class);
                                                if (sd.getSectionCode().equals(updateSD.getSectionCode())) {
                                                    key = snapshot.getKey().toString();
                                                }
                                            }

                                        SectionDetails newSD = new SectionDetails(code, seats);
                                        updateRef.child(key).setValue(newSD);
                                        }

                                        @Override
                                        public void onCancelled(DatabaseError databaseError) {

                                        }
                                    });

                    }
            });

            btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                                updateRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                            SectionDetails deleteSD = snapshot.getValue(SectionDetails.class);
                                            if (sd.getSectionCode().equals(deleteSD.getSectionCode())) {
                                                updateSectionRef.child(snapshot.getKey().toString()).removeValue();
                                                break;
                                            }
                                        }
                                        adapter.notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                    }
                                });
                    }
                });

            d.show();
        }
    });


    return convertView;
}
}

MainActivity上课

public class MainActivity extends AppCompatActivity {

DatabaseReference mRef;
FirebaseHelper helper;
CustomAdapter adapter;
ListView lvSectionsListOne;

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

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

数据将按预期从数据库中删除,但删除的数据仍保留在listview内。我添加了adapter.notifyDataSetChanged(),但listview仍未更新。

数据也按预期更新,但单击update按钮时,数据会无限更新。我可以看到listview以及数据库继续附加数据,并且只能通过关闭应用程序来停止。

我已尝试将SectionDetails newSD = new SectionDetails(code, seats)updateRef.child(key).setValue(newSD)移至外部for循环,但数据未更新,因为密钥未传递到{{1}之外的路径}循环。

1 个答案:

答案 0 :(得分:0)

我没有仔细查看您发布的所有代码,可能完全不了解您的处理过程。有两件事可能会导致您描述的一些问题。

FirebaseHelper中,方法onChildChanged()调用fetchData(),将更改的部分详细信息添加到数组列表中。您不应该更新现有的部分细节而不是再次添加它们吗?此外,在onChildRemoved()中,不会从数组列表中删除部分详细信息。他们不需要被移除吗?

CustomAdapter中,按钮的点击监听器会添加匿名ValueEventListeners。因为它们是匿名的,所以当不再需要它们时,您无法删除它们。 ValueEventListeners添加了addValueEventListener() remain active until removed。如果您的目标是获取一次数据,请使用addListenerForSingleValueEvent()