I have added a background service to my application which creates a notificaion when a new item is added to my application. When pressing the notification the user is taken into the application and the intent passes an object which allows the application to select the newly added item.
The application is for both mobile phones and tablets. When running on phones the item is shown in a separate activity, when on a tablet a dual fragment layout is used and the item is shown on the right fragment.
In the main activity onCreate I check the intent and check if a item has been passed through and display it if it has. This is working fine on the phone but on a tablet the right fragment is not visible and hence the item can not be shown.
This is what I call at the end of onCreate (I had tried it in onStart and onResume)
Bundle data = queryIntent.getExtras();
if (data!=null){
Deal deal = data.getParcelable("notificationDeal");
if (deal!=null){
onDealSelected(deal);
}
}
The method onDealSeletced does the following
public void onDealSelected(Deal deal) {
if (!mDualFragments){
Intent showDealDetails = new Intent(getApplicationContext(), DealDetailsActivity.class);
showDealDetails.putExtra("Deal", deal);
showDealDetails.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(showDealDetails);
Log.d("OnDealSelected", "1");
}
else{ // must be tablet
if (dealDetailsFragment == null)
dealDetailsFragment = (DealDetailsFragment) getFragmentManager().findFragmentByTag("dealDetailsFragment");
if (!dealDetailsFragment.isVisible()){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.right_fragment_container, dealDetailsFragment);
transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
getFragmentManager().executePendingTransactions(); // ensure it is done before we call update deal!
Log.d("OnDealSelected", "2");
}
if (dealDetailsFragment.isVisible()) {
dealDetailsFragment.updateDeal(deal);
Log.d("OnDealSelected", "3");
}
}
}
On a smartphone mDualFragments is false and hence it shows the deal in a new activity and works as expected.
When on a tablet it goes into the else, however it never gets into the final if as the fragment is not visible.
When running the application on a tablet it goes into the second if but after it the fragment is still not visible.
The same method is used at other points in the application (when a deal is not passed through in the intent) and has been working as expected.
You can use setArguments(Bundle bundle) to pass data to the fragment before it is attached (before the commit action). This way when the Fragment initializes itself it can call getArguments and parse the bundle. This way you don’t have to worry about the fragment being visible yet, it can create its views when ready. There is a full example in the Fragment Docs