开发者

Why can't ListView be populated after onCreate in this code?

开发者 https://www.devze.com 2023-03-19 00:18 出处:网络
I have a ListView view I need to populate using data I am fetching from a server. The fetching of the data is done in a AsyncTask background thread.

I have a ListView view I need to populate using data I am fetching from a server. The fetching of the data is done in a AsyncTask background thread.

            ListView view = new ListView(RestaurantInfo.this);
            CustomAdapter adapter = new CustomAdapter(RestaurantInfo.this, R.layout.restaurant_info, R.id.dish_name, data); 
            view.setAdapter(adapter);
            LinearLayout layout = (LinearLayout) findViewById(R.id.restaurant_info_layout);
            Button theView = new Button(RestaurantInfo开发者_如何学C.this);
            layout.addView(theView);

The exact same code works - loads the items into the activity if above code is placed in the onCreate function (which causes the app to block and become unresponsive until the server serves the request). Why does this not work when the same code is placed in the onPostExecute of a AsyncTask?


Do you call adapter.notifyDataSetChanged() when you finish loading your data ? This is needed to notify the listView that it should refresh, and should be done in your AsyncTask's postExecute method.


Dont call these line in onCreate

CustomAdapter adapter = new CustomAdapter(RestaurantInfo.this, R.layout.restaurant_info, R.id.dish_name, data); 
view.setAdapter(adapter);

call them when your Asynch Task finishes

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号