更新Listview项目Android Firebase的值

时间:2016-02-29 20:46:49

标签: java android listview firebase onitemclicklistener

我有点像菜鸟,所以放轻松! 我希望能够更新我存储在Firebase中的字符串的值。 我使用onItemClickListener,以便当单击列表视图中的特定项目时,它会将值更新为当前值+“atnding”。

我知道为了做到这一点,我必须从listview项中获取当前值,然后使用setter在单击该项时将其更新为新值。我只是不知道如何实际做到这一点。

提前致谢。

    new Firebase("https://amber-fire-8056.firebaseio.com/")
            .addChildEventListener(new ChildEventListener() {
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    adapter.add((String) dataSnapshot.child("text").getValue());
                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                    adapter.remove((String) dataSnapshot.child("text").getValue());
                }


                public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                    adapter.add((String) dataSnapshot.child("text").getValue());
                    System.out.println("Events Have Been Updated");
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(FirebaseError firebaseError) {
                }
            });

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String val =(String) parent.getItemAtPosition(position);


                    Toast.makeText(MainFBActivity.this, "Attending Event", Toast.LENGTH_SHORT).show();


                }
            });

1 个答案:

答案 0 :(得分:1)

欢迎!

而不是试图自己纠缠ListViewAdapter you should use FirebaseUI

FirebaseUI提供了一个名为FirebaseListAdapter的类,它将为您处理子事件:

ListView messagesView = (ListView) findViewById(R.id.messages_list);

Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://<my-firebase-app>.firebaseio.com/messages");

FirebaseListAdapter<ChatMessage> adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class, android.R.layout.two_line_list_item, ref) {
    @Override
    protected void populateView(View view, ChatMessage chatMessage, int position) {
        ((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
        ((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getMessage());

    }
};
messagesView.setAdapter(adapter);

FirebaseListAdapter处理幕后的子事件,并使基础数组与远程更改保持同步。您需要担心的是填充populateView内的视图。