我对如何做到这一点缺乏一些了解,而且我见过的大多数例子似乎不适用于我的情况,或者完全让我感到困惑。
我的问题:
我有4个片段,2个用于数据提交,2个用于数据审查和数据计算。我的代码能够从最后两个片段中提取的唯一方法似乎是来自 main FragmentActivity
。问题是,当 Activity 通过 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();
}
});
提前感谢您的所有帮助!