他のアクティビティ(RemoveStatement)からアクティビティメソッド(Budgeting.readFromDb())にアクセスしたいと思います。 RemoveStatementは、BudgetingFragment(Budgeting内のプレースホルダフラグメント)のインテントを通して実行されます。Android:別のアクティビティからフラグメントアクティビティのインスタンスを取得
しかし、getActivity()を呼び出すためにBudgetingFragment(getFragmentManager()、findFragmentByTag( "budgetingFragment")を介して)のインスタンスを取得しようとすると、nullオブジェクトが返されます。なぜこれをやっているのか、どうやって解決するのか分かりません。
私は、次のことを試してみました:
- はコールgetSupportFragmentManager(backStack に
- をタグを追加)budgetingFragment内のフラグメントを交換した後executePendingTransactionsを()。。
これを解決するための助けがあれば幸いです。予算内
方法フラグメント
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();
したがって、断片化されたインスタンスまたは予算作成アクティビティのインスタンスを取得する最良の方法は何ですか? Budgeting ActivitiesのフラグメントマネージャーのインスタンスをRemoveStatement – JoeScott1232
に渡すことをお勧めしますか?フラグメントは互いに認識してはいけません(疎結合)。ホストアクティビティのフラグメントに引数を設定し、[callbacks](http://developer.android.com/training/basics/fragments/communicating.html) –