0

I am new to Android.

I have to update a ListView with chatAdapter.notifyDataSetChanged();

Everything works as expected, ListView is updated.

Then I need to call ListView getChildAt(index), however it is always null, unless I wait for some times

Here is code snippet below:

chatAdapter.notifyDataSetChanged();
            if (requestType == RequestType.FirstRequest){
                if (chatMessages.size() != 0) {
                    //scroll to bottom
                    chatListView.setSelection(chatMessages.size() - 1);

                    Log.i(TAG, "" + chatListView.getChildAt(0));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Log.i(TAG, "" + chatListView.getChildAt(0));
                        }
                    }, 3000);
                }
            }    

The first Log always returns null, however, I am able to get child if I wait 3 seconds. It seemed that after I called chatAdapter.notifyDataSetChanged(), it took some time to inflate those child views. How do I properly call getChildAt(index) in this case?

Tony Lin
  • 275
  • 3
  • 14
  • chatAdapter.notifyDataSetChanged() will refresh the listview. call chatListView.getChildAt(0) only when listview is refreshed. – Coder Dec 10 '14 at 08:26
  • take a look here: http://stackoverflow.com/questions/14119128/how-to-know-when-gridview-is-completely-drawn-and-ready – JLONG Dec 10 '14 at 08:30

1 Answers1

3
chatListView.post(new Runnable(){

    @Override
    public void run(){
        //your code to execute after list redraw
    }
});

Runnable passed to post method will be excecuted after all pending operations of ListView (or any other View). in this case - list redrawing

snachmsm
  • 17,866
  • 3
  • 32
  • 74