我希望从另一个活动(RemoveStatement)访问一个活动方法(Budgeting.readFromDb())。RemoveStatement是通过BudgetingFragment(Budgeting中的占位符片段)中的意图运行的。
然而,当我尝试获取BudgetingFragment的一个实例(通过getFragmentManager().findFragmentByTag("BudgetingFragment"))来调用getActivity()时,它返回一个null对象。我似乎不明白它为什么这么做,以及如何修复它
我试过以下几件事:
- 将标记添加到backStack
- 在预算片段中替换片段后,调用getSupportFragmentManager().executeEndingTransactions()
如有任何帮助,我们将不胜感激。
预算中更改片段的方法
public void onClickFragment(int id, String arrowDirection){
//Get current Fragment
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.budgetingFragment);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (currentFragment instanceof BudgetingOverviewFragment && arrowDirection == "Left"){
IncomeFragment incomeFragment = new IncomeFragment();
transaction.replace(R.id.budgetingFragment, incomeFragment, "budgetingFragment");
}
else if (currentFragment instanceof BudgetingOverviewFragment && arrowDirection == "Right"){
ExpenseFragment expenseFragment = new ExpenseFragment();
transaction.replace(R.id.budgetingFragment, expenseFragment, "budgetingFragment");
}
else if (currentFragment instanceof IncomeFragment && arrowDirection == "Right"){
BudgetingOverviewFragment overviewFragment = new BudgetingOverviewFragment();
transaction.replace(R.id.budgetingFragment, overviewFragment, "budgetingFragment");
}
else{
BudgetingOverviewFragment overviewFragment = new BudgetingOverviewFragment();
transaction.replace(R.id.budgetingFragment, overviewFragment, "budgetingFragment");
}
transaction.addToBackStack("budgetingFragment");
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
RemoveStatements onCreate()方法中的代码:
FragmentManager fm = getFragmentManager();
//This Fragment is a null pointer
Fragment callingFragment = fm.findFragmentByTag("budgetingFragment");
//This crashes the application as getActivity() is called on a null reference
Budgeting budgeting = (Budgeting) callingFragment.getActivity();
每个活动都有自己的FragmentManager。因此,您的第二个活动找不到任何"budgetingFragment"
。
据我所知,您的意图是将activity1的所选片段检索到activity2中,对吗?
好吧,你不会通过查看activity2的片段管理器来获得它,因为它位于active1不同的上下文中。
建议的方法是聚集所选片段所需的所有数据,并在Intent的定义(链接1或链接2)期间将其传递给activity2。
创建activity2时,您可以获取先前序列化的数据,从而在active2上使用它。此外,您可以在activity2上使用替换事务来扩展新片段,如在activity1中(链接)。请注意,要做到这一点,您需要R.id.budgetingFragment
FrameLayout id在activity2的布局中可用。