2012-03-19 48 views
1

我試圖在ASyncTask中獲取一些數據,並且一旦它完成將數據傳遞給viewpager內的任何片段。但我得到以下異常:在ASyncTask中設置op ViewPager

java.lang.IllegalStateException:ViewPager尚未綁定。

我不得不以下代碼:

OnCreateView 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

     setContentView(R.layout.simple_tabs);  
     team_id = this.getIntent().getIntExtra("index", 0) + 1; 
     new getTeam().execute(); 
    } 

的AsyncTask:

@Override 
    protected Void doInBackground(Void... arg0) { 
     team = api.getTeamByID(team_id); 
     return null;  
    } 

@Override 
     protected void onPostExecute(Void result) { 
      mAdapter = new TeamFragmentAdapter(getSupportFragmentManager()); 

      mPager = (ViewPager)findViewById(R.id.pager); 
      mPager.setAdapter(mAdapter); 

      mIndicator = (TabPageIndicator)findViewById(R.id.indicator); 
      mIndicator.setViewPager(mPager); 

      progressDialog.dismiss(); 
     } 

TeamFragmentAdapter:

class TeamFragmentAdapter extends FragmentPagerAdapter implements TitleProvider { 

     ArrayList<Fragment> fragments = new ArrayList<Fragment>(); 
     ArrayList<String> titels = new ArrayList<String>(); 

     public TeamFragmentAdapter(FragmentManager fm) { 
      super(fm); 
      fragments.add(new TeamInformatieFragment(team)); 
      titels.add("Informatie");    
      fragments.add(new ContactFragment()); 
      titels.add("Informatie"); 
     } 



     @Override 
     public Fragment getItem(int position) { 
      return fragments.get(position); 
     } 

     @Override 
     public int getCount() { 
      return fragments.size(); 
     } 

     @Override 
     public String getTitle(int position) { 
      return titels.get(position); 
     } 
    } 

當我移動的內容 「OnPostExecute(無效結果)」,以OnCreateView它的工作原理......但我必須在碎片創建之前獲取所有數據。

你能告訴我發生了什麼事嗎? !:(

回答

8

FIXED我不得不所有的佈局東西從的AsyncTask移動到OnPostExecute 它看起來像這樣:

@Override 
     protected void onPostExecute(Void result) { 
      setContentView(R.layout.simple_tabs); 

      mAdapter = new TeamFragmentAdapter(getSupportFragmentManager()); 

      mPager = (ViewPager)findViewById(R.id.pager); 
      mPager.setAdapter(mAdapter); 

      mIndicator = (TabPageIndicator)findViewById(R.id.indicator); 
      mIndicator.setViewPager(mPager); 
      invalidateOptionsMenu(); 
      progressDialog.dismiss(); 
     } 
+0

不明白,但它似乎工作:?/任何解釋這裏? – cV2 2013-09-03 19:31:07

+0

@ cV2是的,因爲它改變了佈局,所以它必須在UI線程上運行,AsyncTask的onPostExecute是UIThread。:) – Reinherd 2014-01-20 12:28:27

+0

是啊,謝謝你的迴應,但是爲什麼不能在onCreate中設置UI呢?只需在onPostExecute()中進行適應... 爲什麼要在onPostExecute中設置完整的佈局? (這是真正的問題):)期待你的答案 – cV2 2014-01-21 14:54:20