title: duplicate actions in android application when going to home screen
body: <p><strong>Intro:</strong><br>
  My client require some components across the application like <code>navigationDrawer</code>, <code>toolbar</code>. So I have a <code>MainActivity</code> having two <code>toolbar</code>(top/bottom) and two navigation drawer(left/right). All other screens consist of <code>fragments</code> that I change in <code>MainActivity</code>. I have a little problem that is some of the action are being duplicated.<br>
  <strong>Cases:</strong>
   In some <code>fragments</code> when user perform an action i.e.<br>
  <strong>1:</strong> User press "Add To Cart" <code>button</code> and press home <code>button</code> that is in <code>toolbar</code> Bottom, the code of "Add To Cart" <code>button</code> run twice (once clicking button, once going to home screen) so my item is being added to cart twice.<br>
  <strong>2:</strong> In another fragment I have "apply coupon" <code>checkbox</code> when user check that <code>checkbox</code> an <code>AlertDialog</code> appear and when user go to home screen the <code>AlertDialog</code> again appear in the home screen.</p>
  
  <p>I'm simply recreating the main activity on home button press with <code>recreate();</code></p>
  
  <p>I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.</p>
  
  <p><strong>If I need to show code tell me which part?</strong></p>
  
  <p><strong>Edit</strong>:
  inside <code>onCreateView</code> of fragment Cart Detail</p>
  
  <pre><code>useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  if (isChecked) {
                      createAndShowCustomAlertDialog();
                  }
              }
          });
  </code></pre>
  
  <p>Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.</p>
  
  <p><strong>Edit 2</strong>: MainActivity    </p>
  
  <pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          this.utils = new Utils(this);
          utils.changeLanguage("en");
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          initViews();
          this.context = this;
          setupToolbar(this);
          utils.switchFragment(new MainFrag());
          setOnClickListener();
  
          initRightMenuData();
          initLeftMenuData();
  
          listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
                  false, loggedInIconList);
          listViewExpLeft.setAdapter(listAdapter);
          if (isLoggedIn()) {
              listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
                      loggedInIconList);
          } else {
              listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
                      NotLoggedInIconList);
          }
          listViewExpRight.setAdapter(listAdapterRight);
  
          enableSingleSelection();
          setExpandableListViewClickListener();
          setExpandableListViewChildClickListener();
  
      }
  
      private void setOnClickListener() {
          myAccountTV.setOnClickListener(this);
          checkoutTV.setOnClickListener(this);
          discountTV.setOnClickListener(this);
          homeTV.setOnClickListener(this);
          searchIcon.setOnClickListener(this);
          cartLayout.setOnClickListener(this);
      }
  
      private void setExpandableListViewClickListener() {
          listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
              @Override
              public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
                                          long id) {
  
                  utils.printLog("GroupClicked", " Id = " + id);
                  int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
                  if (!isLoggedIn()) {
                      if (childCount &lt; 1) {
                          if (groupPosition == 0) {
                              utils.switchFragment(new FragLogin());
                          } else if (groupPosition == 1) {
                              utils.switchFragment(new FragRegister());
                          } else if (groupPosition == 2) {
                              utils.switchFragment(new FragContactUs());
                          } else {
                              recreate();
                          }
                          drawer.closeDrawer(GravityCompat.END);
                      }
                  } else {
                      if (childCount &lt; 1) {
                          changeFragment(103 + groupPosition);
                          drawer.closeDrawer(GravityCompat.END);
                      }
                  }
  
                  return false;
              }
          });
  
          listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
              @Override
              public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
  
                  int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
  
                  if (childCount &lt; 1) {
                      MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
                              .getGroup(groupPosition);
                      moveToProductFragment(textChild.getMenuCategoryId());
                      utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
  
                  }
  
                  return false;
              }
          });
      }
  
      private void setExpandableListViewChildClickListener() {
          listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
              @Override
              public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                          int childPosition, long id) {
  
                  MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
                          .getChild(groupPosition, childPosition);
  
                  moveToProductFragment(subCategory.getMenuSubCategoryId());
                  utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
  
                  return true;
              }
          });
          listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
              @Override
              public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                  String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
                  UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
                          .getChild(groupPosition, childPosition);
                  if (str.contains("Information") || str.contains("معلومات")) {
                      Bundle bundle = new Bundle();
                      bundle.putString("id", userSubMenu.getUserSubMenuCode());
                      utils.switchFragment(new FragShowText(), bundle);
                  } else if (str.contains("اللغة") || str.contains("Language")) {
  
                      recreate();
                  } else if (str.contains("دقة") || str.contains("Currency")) {
                      makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
                  }
                  utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
                  drawer.closeDrawer(GravityCompat.END);
  
                  return false;
              }
          });
      }
  
      private void setupToolbar(Context context) {
  
          ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
          ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
  
          String imgPath = Preferences
                  .getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
          utils.printLog("Product Image = " + imgPath);
          if (!imgPath.isEmpty()) {
              Picasso.with(getApplicationContext()).load(imgPath)
                      .into(logoIcon);
          }
          logoIcon.setOnClickListener(this);
  
          AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
          actionbarToggle();
          drawer.addDrawerListener(mDrawerToggle);
  
          drawerIconLeft.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (drawer.isDrawerOpen(GravityCompat.START)) {
                      drawer.closeDrawer(GravityCompat.START);
                  } else {
                      drawer.openDrawer(GravityCompat.START);
                      drawerIconLeft.setScaleX(1);
                      drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
                  }
              }
          });
          drawerIconRight.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (drawer.isDrawerOpen(GravityCompat.END)) {
                      drawer.closeDrawer(GravityCompat.END);
                  } else {
                      drawer.openDrawer(GravityCompat.END);
                  }
              }
          });
      }
  
      private void initViews() {
          drawerIconLeft = findViewById(R.id.drawer_icon_left);
          drawerIconRight = findViewById(R.id.drawer_icon_right);
          logoIcon = findViewById(R.id.logo_icon);
          searchIcon = findViewById(R.id.search_icon);
          cartLayout = findViewById(R.id.cart_layout);
          counterTV = findViewById(R.id.actionbar_notification_tv);
  
          drawer = findViewById(R.id.drawer_layout);
          listViewExpLeft = findViewById(R.id.expandable_lv_left);
          listViewExpRight = findViewById(R.id.expandable_lv_right);
  
          appbarBottom = findViewById(R.id.appbar_bottom);
          appbarTop = findViewById(R.id.appbar_top);
          myAccountTV = findViewById(R.id.my_account_tv);
          discountTV = findViewById(R.id.disc_tv);
          checkoutTV = findViewById(R.id.checkout_tv);
          homeTV = findViewById(R.id.home_tv);
  
          searchView = findViewById(R.id.search_view);
      }
  
      @Override
      public void onBackPressed() {
  
          if (drawer.isDrawerOpen(GravityCompat.START)) {
              drawer.closeDrawer(GravityCompat.START);
          } else if (drawer.isDrawerOpen(GravityCompat.END)) {
              drawer.closeDrawer(GravityCompat.END);
          } else {
              super.onBackPressed();
          }
      }
  
      private void initRightMenuData() {
          headerListRight = new ArrayList&lt;&gt;();
          hashMapRight = new HashMap&lt;&gt;();
  
          String[] notLoggedInMenu = {findStringByName("login_text"),
                  findStringByName("action_register_text"),
                  findStringByName("contact_us_text")};
          String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
                  findStringByName("action_change_pass_text"),
                  findStringByName("order_history_text"),
                  findStringByName("logout"), findStringByName("contact_us_text")};
  
          List&lt;UserSubMenu&gt; userSubMenusList = new ArrayList&lt;&gt;();
          if (isLoggedIn()) {
              for (int i = 0; i &lt; loggedInMenu.length; i++) {
                  headerListRight.add(loggedInMenu[i]);
                  hashMapRight.put(headerListRight.get(i), userSubMenusList);
              }
          } else {
              for (int i = 0; i &lt; notLoggedInMenu.length; i++) {
                  headerListRight.add(notLoggedInMenu[i]);
                  hashMapRight.put(headerListRight.get(i), userSubMenusList);
  
              }
          }
          String responseStr = "";
          if (getIntent().hasExtra(KEY_EXTRA)) {
              responseStr = getIntent().getStringExtra(KEY_EXTRA);
              utils.printLog("ResponseInInitData", responseStr);
              try {
                  JSONObject responseObject = new JSONObject(responseStr);
                  boolean success = responseObject.optBoolean("success");
                  if (success) {
                      try {
                          JSONObject homeObject = responseObject.getJSONObject("home");
                          JSONArray slideshow = homeObject.optJSONArray("slideshow");
                          AppConstants.setSlideshowExtra(slideshow.toString());
                          JSONArray menuRight = homeObject.optJSONArray("usermenu");
  
                          for (int z = 0; z &lt; menuRight.length(); z++) {
                              List&lt;UserSubMenu&gt; userSubMenuList = new ArrayList&lt;&gt;();
                              JSONObject object = menuRight.getJSONObject(z);
                              headerListRight.add(object.optString("name"));
                              JSONArray childArray = object.optJSONArray("children");
  
                              for (int y = 0; y &lt; childArray.length(); y++) {
                                  JSONObject obj = childArray.optJSONObject(y);
                                  userSubMenuList.add(new UserSubMenu(obj.optString("code"),
                                          obj.optString("title"), obj.optString("symbol_left"),
                                          obj.optString("symbol_right")));
                              }
                              hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
                              utils.printLog("AfterHashMap", "" + hashMapRight.size());
                          }
  
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }
                  } else {
                      utils.showErrorDialog("Error Getting Data From Server");
                      utils.printLog("SuccessFalse", "Within getCategories");
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
                  utils.printLog("JSONObjEx_MainAct", responseStr);
              }
          } else {
              utils.printLog("ResponseExMainActivity", responseStr);
              throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
          }
  
      }
  
      private void initLeftMenuData() {
          headerListLeft = new ArrayList&lt;&gt;();
          hashMapLeft = new HashMap&lt;&gt;();
  
          String responseStr = "";
          if (getIntent().hasExtra(KEY_EXTRA)) {
              responseStr = getIntent().getStringExtra(KEY_EXTRA);
              utils.printLog("ResponseInMainActivity", responseStr);
              try {
                  JSONObject responseObject = new JSONObject(responseStr);
                  utils.printLog("JSON_Response", "" + responseObject);
                  boolean success = responseObject.optBoolean("success");
                  if (success) {
                      try {
                          JSONObject homeObject = responseObject.getJSONObject("home");
  
                          JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
                          utils.printLog("Categories", menuCategories.toString());
                          for (int i = 0; i &lt; menuCategories.length(); i++) {
  
                              JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
                              JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
                                      "children");
  
                              List&lt;MenuSubCategory&gt; childMenuList = new ArrayList&lt;&gt;();
                              for (int j = 0; j &lt; menuSubCategoryArray.length(); j++) {
                                  JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
                                  MenuSubCategory menuSubCategory = new MenuSubCategory(
                                          menuSubCategoryObj.optString("child_id"),
                                          menuSubCategoryObj.optString("name"));
                                  childMenuList.add(menuSubCategory);
                              }
                              MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
                                      "category_id"), menuCategoryObj.optString("name"),
                                      menuCategoryObj.optString("icon"), childMenuList);
                              headerListLeft.add(menuCategory);
                              hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
                          }
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }
                  } 
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          } else {
              utils.printLog("ResponseExMainActivity", responseStr);
              throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
          }
      }
  
      private void actionbarToggle() {
          mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
                  R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
  
              public void onDrawerClosed(View view) {
                  super.onDrawerClosed(view);
                  drawerIconLeft.setImageResource(R.drawable.ic_list_black);
                  drawerIconLeft.setScaleX(-1);
              }
  
              public void onDrawerOpened(View drawerView) {
                  super.onDrawerOpened(drawerView);
              }
          };
      }
  
      @Override
      public void onClick(View v) {
          int id = v.getId();
  
          if (id == R.id.logo_icon) {
              recreate();
          } else if (id == R.id.my_account_tv) {
              utils.switchFragment(new Dashboard());
          } else if (id == R.id.disc_tv) {
              utils.printLog("From = Main Act");
              Bundle bundle = new Bundle();
              bundle.putString("from", "mainActivity");
              utils.switchFragment(new FragProduct(), bundle);
  
          } else if (id == R.id.checkout_tv) {
              if (isLoggedIn()) {
                  utils.switchFragment(new FragCheckout());
              } else {
                  AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
                          "Select the appropriate option");
                  alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
                          "As Guest", new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {
                                  utils.switchFragment(new FragCheckout());
                              }
                          });
                  alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                          "Login", new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {
                                  utils.switchFragment(new FragLogin());
                              }
                          });
                  alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                          "Register", new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {
                                  utils.switchFragment(new FragRegister());
                              }
                          });
                  alertDialog.show();
              }
          } else if (id == R.id.home_tv) {
              recreate();
          } else if (id == R.id.search_icon) {
              startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
          } else if (id == R.id.cart_layout) {
              Bundle bundle = new Bundle();
              bundle.putString("midFix", "cartProducts");
              utils.switchFragment(new FragCartDetail(), bundle);
          }
      }
  
      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
                  || requestCode == LANGUAGE_REQUEST_CODE) {
              if (data != null) {
                  String responseStr = data.getStringExtra("result");
                  utils.printLog("ResponseIs = " + responseStr);
  
                  if (responseStr != null) {
                      if (resultCode == Activity.RESULT_OK) {
                          JSONObject response;
                          if (!isJSONString(responseStr)) {
                              try {
                                  response = new JSONObject(responseStr);
                                  if (requestCode == CURRENCY_REQUEST_CODE) {
                                      JSONObject object = response.optJSONObject("currency");
                                      Preferences.setSharedPreferenceString(appContext
                                              , CURRENCY_SYMBOL_KEY
                                              , object.optString("symbol_left")
                                                      + object.optString("symbol_right")
                                      );
                                      recreate();
                                  } else if (requestCode == LANGUAGE_REQUEST_CODE) {
                                      JSONObject object = response.optJSONObject("language");
                                      Preferences.setSharedPreferenceString(appContext
                                              , LANGUAGE_KEY
                                              , object.optString("code")
                                      );
                                      recreate();
                                  }
  
                              } catch (JSONException e) {
                                  e.printStackTrace();
                              }
                          } else {
                              if (requestCode == SEARCH_REQUEST_CODE) {
                                  if (responseStr.isEmpty())
                                      return;
                                  Bundle bundle = new Bundle();
                                  bundle.putString("id", responseStr);
                                  bundle.putString("from", "fromSearch");
                                  utils.switchFragment(new FragProduct(), bundle);
                              } else {
                                  utils.showAlertDialog("Alert", responseStr);
                              }
                          }
                      } else if (resultCode == FORCED_CANCEL) {
                          utils.printLog("WithinSearchResult", "If Success False" + responseStr);
                      } else if (resultCode == Activity.RESULT_CANCELED) {
                          utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
                      }
                  }
              }
          }
      }
  
  }
  </code></pre>
  
  <p>MainFragment</p>
  
  <pre><code>public class MainFrag extends MyBaseFragment {
  
      public MainFrag() {}
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
  
          View view = inflater.inflate(R.layout.frag_main, container, false);
          initUtils();
          initViews(view);
          utils.setupSlider(mPager, indicator, pb, true, true);
  
          RecyclerView.LayoutManager mLayoutManager =
                  new LinearLayoutManager(getActivity()
                          , LinearLayoutManager.VERTICAL, false);
          mRecyclerView.setLayoutManager(mLayoutManager);
          List&lt;String&gt; keysList = prepareData();
          if (keysList.size() &gt; 0 &amp;&amp; !keysList.isEmpty()) {
              mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
          }
  
          return view;
      }
  
      private void initViews(View view) {
          mRecyclerView = view.findViewById(R.id.parent_recycler_view);
          mPager = view.findViewById(R.id.pager);
          indicator = view.findViewById(R.id.indicator);
          pb = view.findViewById(R.id.loading);
      }
  
      private List&lt;String&gt; prepareData() {
          String responseStr = getHomeExtra();
          List&lt;String&gt; keysStr = new ArrayList&lt;&gt;();
          try {
              JSONObject responseObject = new JSONObject(responseStr);
              utils.printLog("JSON_Response", "" + responseObject);
              boolean success = responseObject.optBoolean("success");
              if (success) {
                  JSONObject homeObject = responseObject.optJSONObject("home");
                  JSONObject modules = homeObject.optJSONObject("modules");
  
                  Iterator&lt;?&gt; keys = modules.keys();
                  while (keys.hasNext()) {
                      String key = (String) keys.next();
                      keysStr.add(key);
                      utils.printLog("KeyStr", key);
                  }
                  utils.printLog("ModuleSize", modules.toString());
              } else {
                  utils.printLog("SuccessFalse", "Within getCategories");
              }
          } catch (JSONException e) {
              e.printStackTrace();
              utils.printLog("JSONEx_MainFragTest", responseStr);
          }
          return keysStr;
      }
  }
  </code></pre>
  
  <p>I removed global variables and some method because of length.</p>