将新数据添加到Firebase后,为什么我的ListView没有刷新?

时间:2015-06-26 18:29:02

标签: android listview firebase

将字符串推送到firebase后,我无法重新加载ListView。重新启动应用程序时ListView会更新。我在notifyDataSetChanged()使用了ListAdapter函数。这就是我正在做的事情:

myFirebaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d("App",dataSnapshot.getValue().toString());
            names = dataSnapshot.getValue().toString();



            String[] planets = new String[] { names, "Venus", "Earth", "Mars",
                    "Jupiter", "Saturn", "Uranus", "Neptune"};
            ArrayList<String> planetList = new ArrayList<String>();
            namesList.addAll( Arrays.asList(planets) );

            // Create ArrayAdapter using the planet list.
            listAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, android.R.id.text1, namesList);

            mainListView.setAdapter(listAdapter);
            listAdapter.notifyDataSetChanged();


        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

2 个答案:

答案 0 :(得分:0)

每次创建新的listadapter时。只需使用旧的。这里存在冲突,因为您正在创建新的适配器并将其设置为调用notifyDatachanged的同时。这不符合逻辑。不要绑定新的适配器。

答案 1 :(得分:0)

Firebase工程师,

我建议您查看我最近制作的simple chat example(您要做的是详细here)或我们更完整的Android Chat example,这些都展示了如何使用模型对象绑定到ArrayAdapters和ListViews。

TL; DR是你想做更像这样的事情:

// Create instance variables to be used from inside your activity
private ArrayList<Map<String, Object>> mMessages;
private Firebase mRef;

...

// Some time later, instantiate your instance variables
this.mMessages = new ArrayList<Message>();

// Set up ListAdapter
ListAdapter messageAdapter = new ArrayAdapter(this , R.layout.message_layout , mMessages);
this.setListAdapter(messageAdapter);

// Set up Firebase
Firebase.setAndroidContext(this);
this.mRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");

// Add listener to your Firebase database reference
this.mRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        // Create objects and add to ArrayList, which should fire ArrayAdapter methods and update the ListView
        Map<String, Object> data = (Map<String, Object>)dataSnapshot.getValue();
        MainActivity.this.mMessages.add(data);
    }

    ...
    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});