IllegalStateException Fragment already added - Android - android

I am adding fragment like bellow :
#OnClick(R.id.lnNews)
void newsList() {
String tagName = returnStatusFragment(getString(R.string.news_list_fragment));
if (!TextUtils.isEmpty(tagName) && tagName.equals(getString(R.string.news_list_fragment))) {
frameWorkTableFragment.setVisibility(View.VISIBLE);
if (getActivity() != null) {
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
Fragment news = fragmentManager.findFragmentByTag(getString(R.string.news_list_fragment));
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
news,
getString(R.string.news_list_fragment)).commit();
}
//Fragment is opened
} else {
if (getActivity() != null) {
frameWorkTableFragment.setVisibility(View.VISIBLE);
NewsListFragment newsListFragment = new NewsListFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
newsListFragment,
getString(R.string.news_list_fragment))
.addToBackStack(getString(R.string.news_list_fragment))
.commit();
}
}
}
And in the Fragment I wrote doBackPress like bellow :
#Override
public void doBackTabZero(String nameFragment) {
android.support.v4.app.FragmentManager fragmentManagers = getActivity().getSupportFragmentManager();
if (fragmentManagers.getBackStackEntryCount() > 1) {
fragmentManagers.popBackStackImmediate();
} else {
if (nameFragment.equals("SignsFragment")) {
BusDisplayStatusFrameLayout busDisplayStatusFrameLayout = new BusDisplayStatusFrameLayout();
busDisplayStatusFrameLayout.setDisplayStatusFrameLayout(1);
EventBus.getDefault().post(busDisplayStatusFrameLayout);
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentManager.popBackStackImmediate();
fragmentTransaction.remove(SignsFragment.this);
fragmentTransaction.commit();
}
}
}
But get me crash often in this line :
fragmentManagers.popBackStackImmediate();
With this message :
java.lang.IllegalStateException: Fragment already added: NewsFragment{aed4cd1 #3 id=0x7f0a006e NewsFragment}
And in my activity my doBack is like bellow :
private Fragment getCurrentFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
return fragmentManager.findFragmentByTag(fragmentTag);
}
Then :
#Override
public void onBackPressed() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0) {
if (onBackPressedListenerTabWorkTable != null || onBackPressedListenerTabMou != null) {
if (getCurrentFragment().getTag() != null && !TextUtils.isEmpty(getCurrentFragment().getTag())) {
if (getCurrentFragment().getTag().equals("EventsFragment")
|| getCurrentFragment().getTag().equals("WebViewListClassFragment")
|| getCurrentFragment().getTag().equals("SignsFragment")
|| getCurrentFragment().getTag().equals("NewsListFragment")) {
if (viewPagerMainActivity.getCurrentItem() != 0) {
viewPagerMainActivity.setCurrentItem(0);
}
onBackPressedListenerTabWorkTable.doBackTabZero(getCurrentFragment().getTag());
} else if (getCurrentFragment().getTag().equals("SpecialNewsMouFragment")) {
if (viewPagerMainActivity.getCurrentItem() != 1) {
viewPagerMainActivity.setCurrentItem(1);
}
onBackPressedListenerTabMou.doBackTabOne(getCurrentFragment().getTag());
}
}
}
} else {
super.onBackPressed();
onBackPressedListenerTabWorkTable = null;
onBackPressedListenerTabMou = null;
finish();
}
}

Related

Save state of fragment when using bottom navigation

I am using bottom navigation drawer to switch between fragments, the problem is that every time I switch back to a fragment it gets recreated.
How can I save the state of fragment and resume it when switched back to it?
bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener(){
#Override
public void onTabSelected(int position) {
if (position==0){
loadFragment(new Daily());
}
if (position==1){
loadFragment(new Trending());
}
if (position==2){
loadFragment(new Random());
}
}
#Override
public void onTabUnselected(int position) {
}
#Override
public void onTabReselected(int position) {
}
});
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.attach( fragment);
transaction.addToBackStack(null);
transaction.commit();
}
The issue is that you are always creating a new Fragment on any onTabSelected. So in order to fix it, you need to work with your FragmentManager.
Possible solution: use the add and show/hide methods.
Example:
private static final String DAILY_TAG = BuildConfig.APPLICATION_ID + ".DAILY_TAG";
private static final String TRENDING_TAG = BuildConfig.APPLICATION_ID + ".TRENDING_TAG";
private static final String RANDOM_TAG = BuildConfig.APPLICATION_ID + ".RANDOM_TAG";
public void onTabSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
hideFragment(TRENDING_TAG)
hideFragment(RANDOM_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(DAILY_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Daily(), DAILY_TAG)
}
transaction.commitNow()
} else if (position == 1) {
hideFragment(DAILY_TAG)
hideFragment(RANDOM_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(TRENDING_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Trending(), TRENDING_TAG)
}
transaction.commitNow()
} else {
hideFragment(TRENDING_TAG)
hideFragment(DAILY_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(RANDOM_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Random(), RANDOM_TAG)
}
transaction.commitNow()
}
fragments.put(position, fragment);
loadFragment(fragment);
}
private void hideFragment(String tag) {
FragmentManager fragmentManager = getSupportFragmentManager()
Fragment currentFragment = fragmentManager.findFragmentByTag(tag)
if (currentFragment != null) {
fragmentManager.beginTransaction().hide(currentFragment).commitNow()
}
}
PS - The code can be optimized.

Bring a specific fragment to top of other fragments

How can I bring fragment to top of other fragments ?
I added fragment like bellow :
#OnClick(R.id.imbEvents)
void clickEvents() {
String tagName = returnStatusFragment(getString(R.string.events_fragment));
if (!TextUtils.isEmpty(tagName) && tagName.equals(getString(R.string.events_fragment))) {
//Fragment is opened
} else {
if (getActivity() != null) {
frameWorkTableFragment.setVisibility(View.VISIBLE);
EventsFragment eventsFragment = new EventsFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
eventsFragment,
getString(R.string.events_fragment))
.addToBackStack(getString(R.string.events_fragment))
.commit();
}
}
}
I used from bellow code to bring fragment to top but close all last fragments:
getActivity().getSupportFragmentManager().popBackStack(tagName, 0);
Method of returnStatusFragment is :
private String returnStatusFragment(String tagName) {
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
Fragment tempFragment = fragmentManager.findFragmentByTag(tagName);
if (tempFragment != null) {
return tempFragment.getTag();
} else {
return "";
}
}
My doBackTabZero:
#Override
public void doBackTabZero(String nameFragment) {
android.support.v4.app.FragmentManager fragmentManagers = getActivity().getSupportFragmentManager();
Log.i("ASDSADASDSASD", "3 " + nameFragment + " " + fragmentManagers.getBackStackEntryCount());
if (fragmentManagers.getBackStackEntryCount() > 1) {
fragmentManagers.popBackStackImmediate();
} else {
if (nameFragment.equals("EventsFragment")) {
BusDisplayStatusFrameLayout busDisplayStatusFrameLayout = new BusDisplayStatusFrameLayout();
busDisplayStatusFrameLayout.setDisplayStatusFrameLayout(1);
EventBus.getDefault().post(busDisplayStatusFrameLayout);
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentManager.popBackStackImmediate();
fragmentTransaction.remove(EventsFragment.this);
fragmentTransaction.commit();
}
}
}
replace this
getActivity().getSupportFragmentManager().popBackStack(tagName, 0);
with
Fragment eventsFragment = fragmentManager.findFragmentByTag(getString(R.string.events_fragment));
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
eventsFragment,
getString(R.string.events_fragment)).commit();//don't add to back stack again
onBackPressed
#Override
public void doBackTabZero(String nameFragment) {
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
if(fragmentManager.getBackStackEntryCount() > 1 ){
fragmentManager.popBackStackImmediate();
}else{
super.onBackPressed();
}
}

issue in initializing fragment from the activity in xamarin android?

This is my Activity class:
private void pushFragment(Fragment fragment)
{
if (fragment == null)
return;
FragmentManager fragmentManager = SupportFragmentManager;
if (fragmentManager != null)
{
FragmentTransaction ft = fragmentManager.BeginTransaction();
if (ft != null)
{
ft.AddToBackStack("");
ft.Replace(Resource.Id.rootLayout, fragment);
ft.Commit();
}
}
}
public override void OnBackPressed()
{
if (FragmentManager.BackStackEntryCount > 0)
{
FragmentManager.PopBackStack();
//Finish();
}
else
{
base.OnBackPressed();
}
}
When I click on the close icon of the layout it will call pushFragment(new ParentFragment());
The close button on top of the right, when clicked must go to fragment but it's not working?

Activity state loss, Illegal state exception in some devices

I'm using BottomBar menu's in my android application. And there are 5 menus in the BottomBar. This is the main activity
public class MainActivity extends BaseActivity {
private static final String TAG = "MainActivity";
private static final String COMMAND_RESET_PASSWORD = "reset-password";
private static final String COMMAND_REFERRAL = "referral";
private static final int HOME = 0;
private static final int MAP = 1;
private static final int DEAL = 2;
private static final int NOTIFICATION = 3;
private static final int SETTINGS = 4;
private BottomBar mBottomBar;
private int mCurrentTab = HOME;
private BottomBarBadge mNotificationBadge;
private boolean mActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
mActive = true;
super.onCreate(savedInstanceState);
initBottomBar(savedInstanceState);
Intent intent = getIntent();
handleIntent(intent);
}
private void initBottomBar(Bundle savedInstanceState) {
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.useFixedMode();
mBottomBar.noTabletGoodness();
mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
switch (menuItemId) {
case R.id.bottomBarHome:
showStoreList();
break;
case R.id.bottomBarMap:
showMap();
break;
case R.id.bottomBarDeal:
showDeals();
break;
case R.id.bottomBarSettings:
showSettings();
break;
case R.id.bottomBarNotification:
if (mNotificationBadge != null) {
mNotificationBadge.hide();
Sample.getApp().clearBadge();
}
showNotifications();
break;
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
switch (menuItemId) {
case R.id.bottomBarHome:
if (mCurrentTab != HOME)
showStoreList();
break;
case R.id.bottomBarMap:
if (mCurrentTab != MAP)
showMap();
break;
case R.id.bottomBarDeal:
if (mCurrentTab != DEAL) {
showDeals();
}
break;
case R.id.bottomBarNotification:
if(mCurrentTab != NOTIFICATION) {
if (mNotificationBadge != null) {
mNotificationBadge.hide();
mNotificationBadge.setDealItemCount(0);
Sample.getApp().clearBadge();
}
showNotifications();
}
break;
case R.id.bottomBarSettings:
if (mCurrentTab != SETTINGS)
showSettings();
break;
}
}
});
mNotificationBadge = mBottomBar.makeBadgeForTabAt(3, R.color.sample_badge_color, Sample.getApp().getBadgeCount());
}
public void hideBottomBar() {
if (mBottomBar != null) mBottomBar.hide();
}
public void showBottomBar() {
if (mBottomBar != null) mBottomBar.show();
}
#Override
protected void onResume() {
super.onResume();
handleCommands();
if (mNotificationBadge != null) {
mNotificationBadge.setDealItemCount(Sample.getApp().getBadgeCount());
}
}
public void showPointPopUp() {
PointDialogFragment fragment = new PointDialogFragment();
fragment.setShowsDialog(true);
fragment.show(getSupportFragmentManager(),TAG);
}
private void showStoreList() {
mCurrentTab = HOME;
Fragment fragment = Fragment.instantiate(this, StoreListFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
}
private void showMap() {
String storeId = Sample.getApp().getMallId();
Store store = mStoreCache.getMall(storeId);
if (store != null && store.isMapAvailable()) {
Bundle args = new Bundle();
args.putString(Sample.EXTRA_STORE_ID, Sample.getApp().getMallId());
args.putBoolean(Sample.EXTRA_COMMAND, true);
Fragment fragment = Fragment.instantiate(this, SampleMapFragment.class.getName(), args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
} else {
Fragment fragment = Fragment.instantiate(this, StoreMapFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
}
mCurrentTab = MAP;
}
private void showDeals() {
mCurrentTab = DEAL;
String storeId = Sample.getApp().getMallId();
Bundle args = new Bundle();
if (storeId != null)
args.putString(Sample.EXTRA_STORE_ID, storeId);
Fragment fragment = Fragment.instantiate(this, DealsFragment.class.getName(), args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
}
private void showNotifications(){
mCurrentTab = NOTIFICATION;
Fragment fragment = Fragment.instantiate(this, NotificationFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
}
private void showSettings() {
mCurrentTab = SETTINGS;
Fragment fragment = Fragment.instantiate(this, ProfileFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.commitAllowingStateLoss();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_content_frame;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.d(TAG, "inside onNewIntent");
if (mActive) {
handleIntent(getIntent());
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mBottomBar.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
mActive = false;
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
Branch branch = Branch.getInstance();
if (BuildConfig.DEBUG) {
branch.setDebug();
}
Log.d(TAG, "inside branch no error");
branch.initSession((referringParams, error) -> {
if (error == null) {
try {
Log.d(TAG, "parsed data from referringParams");
if (referringParams.has("data")) {
String link = referringParams.getJSONObject("data").getString("link");
if(link != null && !link.isEmpty()){
Uri uri = Uri.parse(link);
if(uri.getScheme().equals("sample")){
List<String> pathSegments = uri.getPathSegments();
String command = "";
String argument = null;
if (!pathSegments.isEmpty() && pathSegments.size() == 1) {
command = uri.getHost();
argument = pathSegments.get(0);
}
if(COMMAND_REFERRAL.equals(command) && argument != null){
Sample.getApp().currentUser().setReferralCode(argument);
}else {
Intent activityIntent = new Intent(MainActivity.this, LinkHandlerActivity.class);
activityIntent.setData(uri);
startActivity(activityIntent);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, this.getIntent().getData(), this);
}
public void showSignUpInPage() {/*line 319 */
Bundle args = new Bundle();
args.putString(Sample.TYPE, Sample.SIGN_UP);
Fragment fragment =
Fragment.instantiate(this, SignUpInFragmentMain.class.getName(),args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();/***This is the 319th line***/
}
public void forgotPassword(){
Fragment fragment =
Fragment.instantiate(this, ForgotPasswordFragment.class.getName());
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
}
private void handleCommands() {
if (!mActive || Sample.getApp().getNotificationCommand() == null) {
return;
}
switch (Sample.getApp().getNotificationCommand()) {
case Sample.COMMAND_DEAL:
showStoreDetail(Sample.getApp().getStoreId());
break;
case Sample.COMMAND_MALL_DEAL:
showMallDetail(Sample.getApp().getStoreId());
break;
case Sample.COMMAND_REGISTER:
showSignUpInPage();
break;
case Sample.COMMAND_DEFAULT:
break;
case Sample.COMMAND_MAP:
mBottomBar.selectTabAtPosition(1, true);
break;
}
Sample.getApp().setNotificationCommand(null);
}
private void handleIntent(Intent intent) {
if (!mActive) {
return;
}
Uri uri = intent.getData();
if (uri != null) {
Fragment fragment;
List<String> pathSegments = uri.getPathSegments();
String command;
String argument;
if (pathSegments.isEmpty()) {
return;
}
if (pathSegments.size() == 1) {
command = uri.getHost();
argument = pathSegments.get(0);
} else {
command = pathSegments.get(1);
argument = pathSegments.size() > 2 ? pathSegments.get(2) : null;
Log.d(TAG,pathSegments.toString());
}
Bundle args = new Bundle();
switch (command) {
case COMMAND_RESET_PASSWORD:
String uid = pathSegments.size() > 2 ? pathSegments.get(2) : null;
String token = pathSegments.size() > 3 ? pathSegments.get(3) : null;
args.putString(Sample.EXTRA_PASSWORD_TOKEN, token);
args.putString(Sample.EXTRA_PASSWORD_UID, uid);
Fragment resetPasswordFragment =
Fragment.instantiate(this, ResetPasswordFragment.class.getName(), args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, resetPasswordFragment)
.addToBackStack(null)
.commit();
break;
case COMMAND_REFERRAL:
if(argument != null)
Sample.getApp().currentUser().setReferralCode(argument);
break;
}
}
}
private void showStoreDetail(String storeId) {
Sample.getApp().setStoreId(null);
Bundle args = new Bundle();
args.putString(Sample.EXTRA_STORE_ID, storeId);
Fragment fragment = Fragment.instantiate(this, StoreDetailFragment.class.getName(), args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
}
private void showMallDetail(String storeId) {
Sample.getApp().setStoreId(null);
Bundle args = new Bundle();
args.putString(Sample.EXTRA_STORE_ID, storeId);
Fragment fragment = Fragment.instantiate(this, MallDetailFragment.class.getName(), args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
}
}
when switching between tabs(Bottombar menu's) results in app crash in some devices. But I couldn't reproduce the exception.
This is the stacktrace
Non-fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.beco.ibeco/com.beco.ibeco.app.MainActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3000)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3031)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.FragmentManagerImpl.popBackStack(FragmentManager.java:781)
at com.beco.ibeco.app.MainActivity$1.onMenuTabSelected(MainActivity.java:74)
at com.beco.ibeco.app.views.bottombar.BottomBar.notifyMenuListener(BottomBar.java:1239)
at com.beco.ibeco.app.views.bottombar.BottomBar.updateSelectedTab(BottomBar.java:1199)
at com.beco.ibeco.app.views.bottombar.BottomBar.selectTabAtPosition(BottomBar.java:437)
at com.beco.ibeco.app.MainActivity.handleCommands(MainActivity.java:347)
at com.beco.ibeco.app.MainActivity.onResume(MainActivity.java:154)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6119)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3031)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Can anyone help me.!
Quick solution is to use .commitAllowingStateLoss(); instead of .commit(); for all FragmentTransactions you are doing for current activity.
There is a bug related to it : https://issuetracker.google.com/issues/36932872
To save the instance and add something to your outState Bundle you can use the following:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("WORKAROUND_FOR_BUG_KEY","WORKAROUND_FOR_BUG_VALUE");
super.onSaveInstanceState(outState);
}
Also try to add this line if it doesn't work:
transaction.commitAllowingStateLoss();
I have faced this problem
I use .commitAllowingStateLoss(); instead of .commit(); for those FragmentTransactions which fragment state has loss.
In another class you can use .commit();

On click Blank Area Next Fragment Automaticall call

I have 3 fragments open on condition of First fragments list item Click >> Second fragment open and so on Second. But when I click on first fragment's blank space it automatically open second fragment and click on second fragment's blank space it goes to third fragment
This is class I have maintain for fragment transaction
public static void addABCDHomeFragment(FragmentManager fragManager, String categoryName) {
FragmentTransaction ft = fragManager.beginTransaction();
Fragment abcdHomeFragment = fragManager.findFragmentByTag(ABCD_HOME_FRAGMENT);
if (abcdHomeFragment == null || abcdHomeFragment.isRemoving()) {
ABCDHomeFragment homeFragment = new ABCDHomeFragment(categoryName);
ft.add(R.id.frame_layout, homeFragment, ABCD_HOME_FRAGMENT);
ft.addToBackStack(ABCD_HOME_FRAGMENT);
ft.commit();
} else if (abcdHomeFragment != null && abcdHomeFragment.isAdded()) {
fragManager.popBackStack();
ABCDHomeFragment homeFragment = new ABCDHomeFragment(categoryName);
ft.replace(R.id.frame_layout, homeFragment, ABCD_HOME_FRAGMENT);
ft.addToBackStack(ABCD_HOME_FRAGMENT);
ft.commit();
}
}
public static void addProductListFragment(FragmentManager fragmentManager,String categoryId ,
String parent , int option) {
FragmentTransaction ftproductlist = fragmentManager.beginTransaction();
Fragment plistFragment = fragmentManager.findFragmentByTag(PRODUCT_LIST_FRAGMENT);
ProductListFragment productListFragment = new ProductListFragment(categoryId,parent,option);
if (plistFragment != null && plistFragment.isAdded() && plistFragment.isVisible()) {
fragmentManager.popBackStack();
ftproductlist.add(R.id.frame_layout, productListFragment,PRODUCT_LIST_FRAGMENT);
ftproductlist.addToBackStack(PRODUCT_LIST_FRAGMENT);
ftproductlist.commit();
} else {
ftproductlist.replace(R.id.frame_layout, productListFragment, PRODUCT_LIST_FRAGMENT);
ftproductlist.addToBackStack(PRODUCT_LIST_FRAGMENT);
ftproductlist.commit();
}
}
public static void removeProductListFragment(FragmentManager fragmentManager) {
FragmentTransaction ftproductlist = fragmentManager.beginTransaction();
Fragment productListFragment = fragmentManager.findFragmentByTag(PRODUCT_LIST_FRAGMENT);
if (productListFragment != null && productListFragment.isAdded()) {
ftproductlist.remove(productListFragment);
fragmentManager.popBackStack();
ftproductlist.commit();
}
}
public static void addProductDetailFragment(FragmentManager fragManager,String productId,String parent, String productName) {
FragmentTransaction ftproduct = fragManager.beginTransaction();
Fragment productDetailFragment = fragManager.findFragmentByTag(PRODUCT_DETAIL_FRAGMENT);
if (productDetailFragment == null || productDetailFragment.isRemoving()) {
ProductDetailFragment dtailFragment = new ProductDetailFragment(productId, parent,productName);
ftproduct.add(R.id.frame_layout, dtailFragment, PRODUCT_DETAIL_FRAGMENT);
ftproduct.addToBackStack(PRODUCT_DETAIL_FRAGMENT);
ftproduct.commit();
} else if (productDetailFragment != null && productDetailFragment.isAdded()) {
fragManager.popBackStack();
ProductDetailFragment dtailFragment = new ProductDetailFragment(productId,parent,productName);
ftproduct.replace(R.id.frame_layout, dtailFragment,PRODUCT_DETAIL_FRAGMENT);
ftproduct.addToBackStack(PRODUCT_DETAIL_FRAGMENT);
ftproduct.commit();
}
}

Categories

Resources