我缺乏對如何做到這一點的一些理解,我見過的大多數例子似乎都不適用於我的情況,或者完全混淆了我。在ViewPager上加載所有片段onCreate
我的問題: 我有4個片段,2個用於數據提交,2個用於數據查看和數據計算。我的代碼能夠從最後兩個片段中提取的唯一方法似乎來自主要的FragmentActivity
。問題是,當活動通過onCreate方法進行時,並且當我嘗試聲明onClickListener
時,我並沒有加載所有片段,因爲該頁面尚未加載,所以我得到一個NullPointerException
。
現在我的setOffscreenPageLimit
設置爲3,所以根本不應該成爲問題,但我似乎無法弄清楚如何在活動開始時加載頁面。
代碼:
導致應用程序強行關閉線是btnEnterChemicals
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_chemicals);
//declarations
...
some declarations
...
//Set up ViewPager and allow app to hold prior pages when off screen
ChemicalsAdapter = new ResultsPagerAdapter(getSupportFragmentManager());
ChemicalsPager = (ViewPager) findViewById(R.id.chemicals_pager);
ChemicalsPager.setAdapter(ChemicalsAdapter);
ChemicalsPager.setOffscreenPageLimit(3);
//When SwipeReviewResults is displayed, fill EditText's with data from other fragments
ChemicalsPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == 2) {
//Pull values from Chemicals 1
...
some assignments
...
//Pull values from Chemicals 2
...
some assignments
...
//Declare rvw text boxes for Meter Review 1
...
some assignments
...
//Declare rvw text boxes for Meter Review 2
...
some assignments
...
//If data isn't null, perform calculations on client entries
if (data != null)
{
//Do calculations before displaying values in review pages
...
some calculations
...
//Display results
...
display results
...
}
//Copy entered data to Chemicals Review 1
...
display results
...
//Copy entered data to Chemicals Review 2
...
display results
...
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
@Override
public void onPageScrollStateChanged(int arg0) { }
});
//Insert data into database
class insertNew implements Runnable
{
...
data submission
...
}
//Declare and set OnClickListener for Entering Results
final Button btnEnterChemicals = (Button) ChemicalsPager.findViewById(R.id.btnEnterChemicals);
btnEnterChemicals.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set and encode url for data submission
...
prepare data
...
//Declare and start thread
Thread thrInsertNew = new Thread(new insertNew(url));
thrInsertNew.start();
}
});
聲明/執行謝謝所有您的幫助提前!