duplicate actions in android application when going to home screen

java android android-fragments android-activity fragment

44 观看

2回复

4737 作者的声誉

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases: In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.

I'm simply recreating the main activity on home button press with recreate();

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.

If I need to show code tell me which part?

Edit: inside onCreateView of fragment Cart Detail

useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    createAndShowCustomAlertDialog();
                }
            }
        });

Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.

Edit 2: MainActivity

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 < 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 < 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 < 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<>();
        hashMapRight = new HashMap<>();

        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<UserSubMenu> userSubMenusList = new ArrayList<>();
        if (isLoggedIn()) {
            for (int i = 0; i < loggedInMenu.length; i++) {
                headerListRight.add(loggedInMenu[i]);
                hashMapRight.put(headerListRight.get(i), userSubMenusList);
            }
        } else {
            for (int i = 0; i < 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 < menuRight.length(); z++) {
                            List<UserSubMenu> userSubMenuList = new ArrayList<>();
                            JSONObject object = menuRight.getJSONObject(z);
                            headerListRight.add(object.optString("name"));
                            JSONArray childArray = object.optJSONArray("children");

                            for (int y = 0; y < 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<>();
        hashMapLeft = new HashMap<>();

        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 < menuCategories.length(); i++) {

                            JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
                            JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
                                    "children");

                            List<MenuSubCategory> childMenuList = new ArrayList<>();
                            for (int j = 0; j < 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);
                    }
                }
            }
        }
    }

}

MainFragment

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<String> keysList = prepareData();
        if (keysList.size() > 0 && !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<String> prepareData() {
        String responseStr = getHomeExtra();
        List<String> keysStr = new ArrayList<>();
        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<?> 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;
    }
}

I removed global variables and some method because of length.

作者: Inzimam Tariq IT 的来源 发布者: 2017 年 12 月 27 日

回应 2


0

87 作者的声誉

决定

You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.

作者: Akash Khatri 发布者: 2017 年 12 月 27 日

0

4737 作者的声誉

From the hint of @Akash Khatri I use to switch to mainFragment and its fine now. Actually @Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.

I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

作者: Inzimam Tariq IT 发布者: 2018 年 2 月 22 日
32x32