There is a similar question here, Activity using ViewPager, PagerAdapter and AsyncTask causes a blank view, but my problem is more than that.
I have a ViewPager that contains a ListView. This ListView is populated by an asyncTask. The listview displays the data, but not correctly. The first page is always blank, and the second page contains BOTH pages data.
I’ve simplified my asynctask to be sure tit wasnt something there that was causing the issue.
@Override
public Object instantiateItem(View pager, int position){
// Log.d("PAGER", Integer.toString(position));
ctx = pager.getContext();
v = new ListView(ctx);
new CreateArrayListTask().execute(URLS[position]);
((ViewPager)pager).addView(v, 0);
return v;
}
CreateArrayListTask
private class CreateArrayListTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... params) {
linkArray.add("Item 1");
linkArray.add("Item 2");
return linkArray;
}
onPostExecute
protected void onPostExecute(ArrayList<String> linkArray) {
ArrayAdapter<String> a = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, linkArray);
v.setAdapter(a);

The
ListViewon the second page is doubly populated precisely because of my answer given in the other question.You are assuming
instantiateItemwill be called only for the currently active page, whereas it will actually be called to preload for offscreen pages too. The referencevto the view will be overwritten by the second call toinstantiateItem.Have a look at this example project to see one way how to do it with fragments: https://github.com/antonyt/ListFragmentViewPagerExample/tree/master/src/com/example/listfragment
Activity:
Fragment: