在android listview上刷新Firebase数据

时间:2017-04-28 21:00:53

标签: android listview firebase firebase-realtime-database

在我的Android应用程序中,我有一个listview,其中包含来自firebase数据库的项目。当我从列表视图中删除项目时,它也正确地从firebase数据库中删除。问题是我不知道删除操作后谁刷新listview。删除后有人可以帮我检索数据吗?

这是从listview中删除项目的代码

mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {


            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
            dialogBuilder.setTitle("Delete List___" );
            dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Post post = (Post)parent.getItemAtPosition(position);

                    DatabaseReference del = FirebaseDatabase.getInstance().getReference().child("user-posts").child(getUid())
                            .child(post.getPostId());

                    del.setValue(null);


                }
            });

            dialogBuilder.show();
            return false;
        }
    });

这是我从数据库中检索数据时的代码。

mDatabase.child(getUid()).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Post post = dataSnapshot.getValue(Post.class);
            mAdapter.add(post);

        }

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

            Log.d(TAG,"dataCHANGE");
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {


            Log.d(TAG,"dataREMOVE "+ dataSnapshot.getKey());
        }

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

            Log.d(TAG,"dataMOVE");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {


        }
    });

1 个答案:

答案 0 :(得分:2)

方法onChildRemoved将返回已删除节点的密钥,因此您只需将其添加到该方法:

String key = dataSnapshot.getKey();
for (Post pt : <list_of_the_adapter> {

    if (key.equals(pt.getPostId())) {
        <list_of_the_adapter>.remove(pt);
        <adapter>.notifyDataSetChanged();

        break;
    }
}