问:
BottomNavigationView setSelectedItemId crash
I'm writing an app using BottomNavigationView and Fragment for updating the layout programmatically.

I'm trying to use a Stack to allow the user to click back and return to the previous fragment. I had tried to use addToBackStack after inflating a new fragment but when back is pressed despite the layout is changing correctly the selected item menu does not change with it.

So I decided to create a custom stack of Fragment and change with setSelectedItemId the selected item but this operation makes the application crash. I used that a lot of time normally and I am not able to understand this behavior.

Thanks for the help.

```<code>public class MainActivity extends FragmentActivity {

private FragmentManager fm = getSupportFragmentManager();
private Logger logger = Logger.getLogger("global");
private BottomNavigationView bnv;
private CustomStack customStack = new CustomStack();

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        Fragment centerFragment;
        switch (item.getItemId()) {

            case R.id.navigation_home:
                centerFragment = new Fragment1();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
            case R.id.navigation_map:
                centerFragment = new Fragment2();
                bnv.setSelectedItemId(R.id.navigation_interest);
                return true;
            case R.id.navigation_interest:
                centerFragment = new Fragment3();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
            case R.id.navigation_notifications:
                centerFragment = new Fragment4();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
        }

        return false;
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bnv = (BottomNavigationView) findViewById(R.id.navigation);
    bnv.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    FragmentTransaction ft1 = fm.beginTransaction();
    Board b = new Board();
    ft1.add(R.id.center_layout, new Fragment1()).commit();
    customStack.push(b);
}

public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        customStack.pop();
        replaceCenterLayoutFragment(customStack.top());
    }
    return false;
}

private void replaceCenterLayoutFragment(Fragment f){
    FragmentTransaction ft1 = fm.beginTransaction();
    ft1.replace(R.id.center_layout, f).commit();
    syncMenuItem(f);
}

private void syncMenuItem(Fragment f){
    if(f instanceof Fragment1)
        bnv.setSelectedItemId(R.id.p1);
    if(f instanceof Fragment2)
        bnv.setSelectedItemId(R.id.p2);
    if(f instanceof Fragment3)
        bnv.setSelectedItemId(R.id.p3);
    if(f instanceof Fragment4)
        bnv.setSelectedItemId(R.id.p4);
}
}
</code>```

this is my custom stack

```<code>public class CustomStack {

private ArrayList<Fragment> menu ;
private Logger logger = Logger.getLogger("global");

public CustomStack(){
    menu = new ArrayList<>();
}

public void push(Fragment i){
    menu.add(i);
}

public Fragment pop (){
    if(menu.size() > 0) {
        int s = menu.size() -1;
        Fragment app = menu.get(s);
        menu.remove(s);
        return app;
    }
    else{
        return null;
    }
}

public Fragment top(){
    if(menu.size() > 0)
        return menu.get(menu.size() -1);
    else
        return null;
}

public boolean isEmpty(){
    return menu.size() > 0;
}

 }
</code>```

and the LogCatPage

```07-10 20:31:07.879 28384-28384/? I/art: Late-enabling -Xcheck:jni
07-10 20:31:07.970 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.145 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.187 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.224 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.264 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.311 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.347 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.387 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.427 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.463 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.508 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.509 28384-28384/com.example.longsky.peoople W/System: ClassLoader referenced unknown path: /data/app/com.example.longsky.peoople-2/lib/arm64
07-10 20:31:08.512 28384-28384/com.example.longsky.peoople I/InstantRun: starting instant run server: is main process
07-10 20:31:08.600 28384-28384/com.example.longsky.peoople W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-10 20:31:08.655 28384-28499/com.example.longsky.peoople E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
07-10 20:31:08.655 28384-28499/com.example.longsky.peoople D/AppTracker: App Event: start
07-10 20:31:08.661 28384-28501/com.example.longsky.peoople D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-10 20:31:08.679 28384-28501/com.example.longsky.peoople I/Adreno: QUALCOMM build                   : 183c040, Iff84fb1103
                                                                     Build Date                       : 03/18/16
                                                                     OpenGL ES Shader Compiler Version: XE031.06.00.02
                                                                     Local Branch                     :
                                                                     Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.BF64.1.2.2_RB4.06.00.01.180.031
                                                                     Remote Branch                    : NONE
                                                                     Reconstruct Branch               : NOTHING
07-10 20:31:08.686 28384-28501/com.example.longsky.peoople I/OpenGLRenderer: Initialized EGL, version 1.4
07-10 20:31:10.516 28384-28384/com.example.longsky.peoople D/AndroidRuntime: Shutting down VM
07-10 20:31:10.592 28384-28384/com.example.longsky.peoople E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.longsky.peoople, PID: 28384
                                                                             java.lang.StackOverflowError: stack size 8MB
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.d
07-10 20:31:10.594 28384-28384/com.example.longsky.peoople D/AppTracker: App Event: crash
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: exClass=java.lang.StackOverflowError
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: exMsg=stack size 8MB
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: file=MainActivity.java
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: class=com.example.longsky.peoople.MainActivity
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: method=replaceCenterLayoutFragment line=96
07-10 20:31:10.647 28384-28384/com.example.longsky.peoople D/Error: ERR: stack=java.lang.StackOverflowError: stack size 8MB
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigati
07-10 20:31:10.647 28384-28384/com.example.longsky.peoople D/Error: ERR: TOTAL BYTES WRITTEN: 862560
07-10 20:31:10.695 28384-28384/com.example.longsky.peoople I/Process: Sending signal. PID: 28384 SIG: 9
```

答:
I have found a much simpler solution. BottomNavigation has another listner called

setOnNavigationItemReselectedListener

Just override that listener and leave the method body empty.

```<code>bottomNavigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
        @Override
        public void onNavigationItemReselected(@NonNull MenuItem menuItem) {
            return;
        }
 });
</code>```

Explanation:

My guess is the setSelectedItemId same as before calls the listener, which will call replaceCenterLayoutFragment which will again call setSelectedItemId, but this time as it already called the normal SelectedListener, so it will call the  ReselectedListener.

NavigationItemReselectedListener then just returns void and ends the loop of method calling.

Body:
I'm writing an app using BottomNavigationView and Fragment for updating the layout programmatically.

I'm trying to use a Stack to allow the user to click back and return to the previous fragment. I had tried to use addToBackStack after inflating a new fragment but when back is pressed despite the layout is changing correctly the selected item menu does not change with it.

So I decided to create a custom stack of Fragment and change with setSelectedItemId the selected item but this operation makes the application crash. I used that a lot of time normally and I am not able to understand this behavior.

Thanks for the help.

public class MainActivity extends FragmentActivity {

private FragmentManager fm = getSupportFragmentManager();
private Logger logger = Logger.getLogger("global");
private BottomNavigationView bnv;
private CustomStack customStack = new CustomStack();

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        Fragment centerFragment;
        switch (item.getItemId()) {

            case R.id.navigation_home:
                centerFragment = new Fragment1();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
            case R.id.navigation_map:
                centerFragment = new Fragment2();
                bnv.setSelectedItemId(R.id.navigation_interest);
                return true;
            case R.id.navigation_interest:
                centerFragment = new Fragment3();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
            case R.id.navigation_notifications:
                centerFragment = new Fragment4();
                replaceCenterLayoutFragment(centerFragment);
                customStack.push(centerFragment);

                return true;
        }

        return false;
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bnv = (BottomNavigationView) findViewById(R.id.navigation);
    bnv.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    FragmentTransaction ft1 = fm.beginTransaction();
    Board b = new Board();
    ft1.add(R.id.center_layout, new Fragment1()).commit();
    customStack.push(b);
}

public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        customStack.pop();
        replaceCenterLayoutFragment(customStack.top());
    }
    return false;
}

private void replaceCenterLayoutFragment(Fragment f){
    FragmentTransaction ft1 = fm.beginTransaction();
    ft1.replace(R.id.center_layout, f).commit();
    syncMenuItem(f);
}

private void syncMenuItem(Fragment f){
    if(f instanceof Fragment1)
        bnv.setSelectedItemId(R.id.p1);
    if(f instanceof Fragment2)
        bnv.setSelectedItemId(R.id.p2);
    if(f instanceof Fragment3)
        bnv.setSelectedItemId(R.id.p3);
    if(f instanceof Fragment4)
        bnv.setSelectedItemId(R.id.p4);
}
}

this is my custom stack

public class CustomStack {

private ArrayList<Fragment> menu ;
private Logger logger = Logger.getLogger("global");

public CustomStack(){
    menu = new ArrayList<>();
}

public void push(Fragment i){
    menu.add(i);
}

public Fragment pop (){
    if(menu.size() > 0) {
        int s = menu.size() -1;
        Fragment app = menu.get(s);
        menu.remove(s);
        return app;
    }
    else{
        return null;
    }
}

public Fragment top(){
    if(menu.size() > 0)
        return menu.get(menu.size() -1);
    else
        return null;
}

public boolean isEmpty(){
    return menu.size() > 0;
}

 }

and the LogCatPage

07-10 20:31:07.879 28384-28384/? I/art: Late-enabling -Xcheck:jni
07-10 20:31:07.970 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.145 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.187 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.224 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.264 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.311 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.347 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.387 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.427 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.463 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.508 28384-28384/com.example.longsky.peoople W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm64 --instruction-set-features=smp,a53 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=generic --instruction-set-features=default --dex-file=/data/app/com.example.longsky.peoople-2/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm64/data@app@com.example.longsky.peoople-2@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
07-10 20:31:08.509 28384-28384/com.example.longsky.peoople W/System: ClassLoader referenced unknown path: /data/app/com.example.longsky.peoople-2/lib/arm64
07-10 20:31:08.512 28384-28384/com.example.longsky.peoople I/InstantRun: starting instant run server: is main process
07-10 20:31:08.600 28384-28384/com.example.longsky.peoople W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-10 20:31:08.655 28384-28499/com.example.longsky.peoople E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
07-10 20:31:08.655 28384-28499/com.example.longsky.peoople D/AppTracker: App Event: start
07-10 20:31:08.661 28384-28501/com.example.longsky.peoople D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-10 20:31:08.679 28384-28501/com.example.longsky.peoople I/Adreno: QUALCOMM build                   : 183c040, Iff84fb1103
                                                                     Build Date                       : 03/18/16
                                                                     OpenGL ES Shader Compiler Version: XE031.06.00.02
                                                                     Local Branch                     :
                                                                     Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.BF64.1.2.2_RB4.06.00.01.180.031
                                                                     Remote Branch                    : NONE
                                                                     Reconstruct Branch               : NOTHING
07-10 20:31:08.686 28384-28501/com.example.longsky.peoople I/OpenGLRenderer: Initialized EGL, version 1.4
07-10 20:31:10.516 28384-28384/com.example.longsky.peoople D/AndroidRuntime: Shutting down VM
07-10 20:31:10.592 28384-28384/com.example.longsky.peoople E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.longsky.peoople, PID: 28384
                                                                             java.lang.StackOverflowError: stack size 8MB
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                                at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                                at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                                at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                                at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                                at android.support.d
07-10 20:31:10.594 28384-28384/com.example.longsky.peoople D/AppTracker: App Event: crash
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: exClass=java.lang.StackOverflowError
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: exMsg=stack size 8MB
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: file=MainActivity.java
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: class=com.example.longsky.peoople.MainActivity
07-10 20:31:10.638 28384-28384/com.example.longsky.peoople D/Error: ERR: method=replaceCenterLayoutFragment line=96
07-10 20:31:10.647 28384-28384/com.example.longsky.peoople D/Error: ERR: stack=java.lang.StackOverflowError: stack size 8MB
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                        at android.support.design.widget.BottomNavigationView.setSelectedItemId(BottomNavigationView.java:341)
                                                                        at com.example.longsky.peoople.MainActivity.replaceCenterLayoutFragment(MainActivity.java:96)
                                                                        at com.example.longsky.peoople.MainActivity.access$000(MainActivity.java:15)
                                                                        at com.example.longsky.peoople.MainActivity$1.onNavigationItemSelected(MainActivity.java:39)
                                                                        at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigati
07-10 20:31:10.647 28384-28384/com.example.longsky.peoople D/Error: ERR: TOTAL BYTES WRITTEN: 862560
07-10 20:31:10.695 28384-28384/com.example.longsky.peoople I/Process: Sending signal. PID: 28384 SIG: 9

Body:
I have found a much simpler solution. BottomNavigation has another listner called

setOnNavigationItemReselectedListener

Just override that listener and leave the method body empty.

bottomNavigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
        @Override
        public void onNavigationItemReselected(@NonNull MenuItem menuItem) {
            return;
        }
 });

Explanation:

My guess is the setSelectedItemId same as before calls the listener, which will call replaceCenterLayoutFragment which will again call setSelectedItemId, but this time as it already called the normal SelectedListener, so it will call the  ReselectedListener.

NavigationItemReselectedListener then just returns void and ends the loop of method calling.


来源: stackexchange

问:
Spring boot: 404 error when calling JSP using controller
I'm getting the following error when running my project using Spring Tool Suite,

But in case my problem is I have already added the appropriate dependencies to pom.XML file. So what could be the problem?

My pom.XML file dependencies as follows,

```<code>        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
</code>```

My controller ApplicationController.java as follows,

```<code>package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ApplicationController {

    @RequestMapping("/")
    public String Welcome() {
        return "welcomepage";
    }
}
</code>```

My vives are in src/main/webapp/WEB-INF/view/welcomepage.jsp you can look the tree view below,

And I have already changed the application.properties file as well. But still, I can't understand what is wrong.

My application.properties file as follows,

```<code>spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
</code>```

I just print hello in My welcomepage.jsp,

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hello
</body>
</html>
</code>```

答:
I was able to generate a jar from my application and then run it with java -jar myapp.jar But I only managed to run this jar with the version below spring-boot-starter-parent:

MyApp/pom.xml:

```<code>      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
  </parent>
</code>```

I researched in:
Spring Boot JSP 404

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error when running my project using Spring Tool Suite,

But in case my problem is I have already added the appropriate dependencies to pom.XML file. So what could be the problem?

My pom.XML file dependencies as follows,

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

My controller ApplicationController.java as follows,

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ApplicationController {

    @RequestMapping("/")
    public String Welcome() {
        return "welcomepage";
    }
}

My vives are in src/main/webapp/WEB-INF/view/welcomepage.jsp you can look the tree view below,

And I have already changed the application.properties file as well. But still, I can't understand what is wrong.

My application.properties file as follows,

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

I just print hello in My welcomepage.jsp,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

hello

Body:
I was able to generate a jar from my application and then run it with java -jar myapp.jar But I only managed to run this jar with the version below spring-boot-starter-parent:

MyApp/pom.xml:

      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
  </parent>

I researched in:
Spring Boot JSP 404


问:
igraph package in r: How to label edges for a directed-acyclic-graph
I am very new to r and programming, so my knowledge is limited.  I am using the igraph package and tkplot to make and present a directed acyclic graph.  I managed to make a graph and I am trying to figure out how to add labels to each edge.  My goal is to have a small annotation on the line between each vertices/vertex explaining their relationship.

I have tried inserting text as shown below:

```<code>text(-1, 0,"[1, 2, 3]")
text(0, 1,"[3, 5, 6]")
</code>```

However, this text does not transfer to out of r with tkplot and is hard to line up with the lines between vertices.

this code gave me the exact graph I want minus the text between vertices.

```<code>
g <- graph.formula("ATB" -+ "Microbiome",
                   "Microbiome" -+ "Inflammation A" -+ "IO Response",
                   "Microbiome" -+ "Inflammation B" -+ "IO Response",
                   "Microbiome" -+ "IO Response",
                   "ATB" -+ "IO Response",
                   "Corticosteroids" -+ "IO Response",
                   "Corticosteroids" -+ "Microbiome",
                   "PPI" -+ "IO Response",
                   "PPI" -+ "Microbiome",
                   "H2B" -+ "IO Response",
                   "H2B" -+ "Microbiome",
                   "NSAIDs" -+ "Microbiome",
                   "NSAIDs" -+ "Inflammation B",
                   "NSAIDs" -+ "IO Response",
                   "Corticosteroids" -+ "Inflammation A",
                      simplify = TRUE)

plot.igraph(g, size = 90)

tkplot(g)
</code>```

答:
You can add labels to the edges by assigning an attribute "label" to each edge. You don't say what you want as the labels, so I arbitrarily assigning a letter code to each edge.
Also, your plot statement includes a "size" parameter. That causes an error so I left it off. Did you mean "vertex.size"?

```<code>E(g)$label = LETTERS[1:ecount(g)]
plot(g)
</code>```

Body:
I am very new to r and programming, so my knowledge is limited.  I am using the igraph package and tkplot to make and present a directed acyclic graph.  I managed to make a graph and I am trying to figure out how to add labels to each edge.  My goal is to have a small annotation on the line between each vertices/vertex explaining their relationship.

I have tried inserting text as shown below:

text(-1, 0,"[1, 2, 3]")
text(0, 1,"[3, 5, 6]")

However, this text does not transfer to out of r with tkplot and is hard to line up with the lines between vertices.

this code gave me the exact graph I want minus the text between vertices.

g <- graph.formula("ATB" -+ "Microbiome",
                   "Microbiome" -+ "Inflammation A" -+ "IO Response",
                   "Microbiome" -+ "Inflammation B" -+ "IO Response",
                   "Microbiome" -+ "IO Response",
                   "ATB" -+ "IO Response",
                   "Corticosteroids" -+ "IO Response",
                   "Corticosteroids" -+ "Microbiome",
                   "PPI" -+ "IO Response",
                   "PPI" -+ "Microbiome",
                   "H2B" -+ "IO Response",
                   "H2B" -+ "Microbiome",
                   "NSAIDs" -+ "Microbiome",
                   "NSAIDs" -+ "Inflammation B",
                   "NSAIDs" -+ "IO Response",
                   "Corticosteroids" -+ "Inflammation A",
                      simplify = TRUE)

plot.igraph(g, size = 90)

tkplot(g)

Body:
You can add labels to the edges by assigning an attribute "label" to each edge. You don't say what you want as the labels, so I arbitrarily assigning a letter code to each edge.
Also, your plot statement includes a "size" parameter. That causes an error so I left it off. Did you mean "vertex.size"?

E(g)$label = LETTERS[1:ecount(g)]
plot(g)


问:
Spring boot several threads work incorrect
I'am making my first client-server application. This is an immitation of elevator. I've done server with using spring boot and client part on JavaFX. My elevator must move between floors within 10 seconds.

This is my POST method where i send target floor: (I dont'n know why but integer values don't arrive)

```<code>@PostMapping()
    public String postEndPoint(@RequestBody String floor) {
        return elevatorService.setFloor(Integer.valueOf(floor));
    }
</code>```

Set method:

```<code>public String setFloor(Integer floor) {
        if (!isPressed(floor)) { // if button isn't pressed, add to list
            list.add(floor);
        }
        targetFloor = list.get(list.size() - 1);
        motion();
        if (list.get(list.size() - 1) == currentFloor) { // when we arrive, delete pressed button
            list.remove(list.size() - 1);
        }
        return String.valueOf(floor);
    }

 private boolean isPressed(Integer floor) {
        return list.contains(floor);
    }
</code>```

and the motion logic:

```<code>private void motion() {
        new Thread(() -> {
            try {
                    Thread.sleep(10000);
                    if (currentFloor < targetFloor) {
                        currentFloor++;
                    } else {
                        currentFloor--;
                    }
                    if (currentFloor != targetFloor) {
                        motion();
                }
            } catch (InterruptedException ignored) { }
        }).start();
    }
</code>```

It works good if i click on the desired floor and wait when elevator arrive, but if I call the elevator on several floors at the same time it works incorrect.
Can somebody help me to solve this problem? Thank you.

答:
I am sure your problem is that you are not using atomic values. Change your primitive integers for an Atomic Integer object.

I suggest you read this to learn more about why and how to use atomic values: https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

Body:
I'am making my first client-server application. This is an immitation of elevator. I've done server with using spring boot and client part on JavaFX. My elevator must move between floors within 10 seconds.

This is my POST method where i send target floor: (I dont'n know why but integer values don't arrive)

@PostMapping()
    public String postEndPoint(@RequestBody String floor) {
        return elevatorService.setFloor(Integer.valueOf(floor));
    }

Set method:

public String setFloor(Integer floor) {
        if (!isPressed(floor)) { // if button isn't pressed, add to list
            list.add(floor);
        }
        targetFloor = list.get(list.size() - 1);
        motion();
        if (list.get(list.size() - 1) == currentFloor) { // when we arrive, delete pressed button
            list.remove(list.size() - 1);
        }
        return String.valueOf(floor);
    }

 private boolean isPressed(Integer floor) {
        return list.contains(floor);
    }

and the motion logic:

private void motion() {
        new Thread(() -> {
            try {
                    Thread.sleep(10000);
                    if (currentFloor < targetFloor) {
                        currentFloor++;
                    } else {
                        currentFloor--;
                    }
                    if (currentFloor != targetFloor) {
                        motion();
                }
            } catch (InterruptedException ignored) { }
        }).start();
    }

It works good if i click on the desired floor and wait when elevator arrive, but if I call the elevator on several floors at the same time it works incorrect.
Can somebody help me to solve this problem? Thank you.


问:
autocomplete text search
can any body tell me steps to use it, where i can get simple example for this </p>

答:
JQuery UI Autocomplete

YUI Autocomplete

DOJO Filtering Select

ContentLicense: CC BY-SA 3.0

Title: autocomplete text search


问:
Call specific java main class inside of docker container running on K8s cluster
I am trying to call specific java class, which contain main methods, using Kubernetes. However, every combination of command/args in my deployment yaml ends with an error when creating the container.

deployment.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: reports
spec:
  replicas: 1
  selector:
    matchLabels:
      app: reports
  template:
    metadata:
      labels:
        app: reports
    spec:
      containers:
      - name: reports
        command: ["java -cp reports.jar com.gswsa.is.reports.TestRunner"]
        image: blah/reports:latest
        volumeMounts:
        - mountPath: /tmp/logs/reports
          name: logvolume
</code>```

Dockerfile

```<code>FROM openjdk:8-jdk-alpine
RUN apk add --no-cache tzdata
RUN apk --update add fontconfig ttf-dejavu
ENV TZ America/New_York
VOLUME /tmp/logs/reports
ARG JAR_FILE=target/reports-1.0.0.jar
COPY ${JAR_FILE} /reports.jar
#ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/reports.jar"]
#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=PROD", "/reports.jar"]
</code>```

I expect to be able to create multiple deployment scripts and call them whenever I would like with their specific arguments. If there is a better way, I am all ears! Thanks

答:
You can specify the command line to start in the container only in the Dockerfile. That is, it is fixed for a given container image. However, you can pass environment variables to your container from the deployment and have your command line behave differently.

That is, you can have one single main class in Java and have that do different things based on the environment variable. Or you can have a wrapper shell script that you define as the entry point in your Dockerfile and have that script execute java command line with specific Java class based on the env variable.

Body:
I am trying to call specific java class, which contain main methods, using Kubernetes. However, every combination of command/args in my deployment yaml ends with an error when creating the container.

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: reports
spec:
  replicas: 1
  selector:
    matchLabels:
      app: reports
  template:
    metadata:
      labels:
        app: reports
    spec:
      containers:
      - name: reports
        command: ["java -cp reports.jar com.gswsa.is.reports.TestRunner"]
        image: blah/reports:latest
        volumeMounts:
        - mountPath: /tmp/logs/reports
          name: logvolume

Dockerfile

FROM openjdk:8-jdk-alpine
RUN apk add --no-cache tzdata
RUN apk --update add fontconfig ttf-dejavu
ENV TZ America/New_York
VOLUME /tmp/logs/reports
ARG JAR_FILE=target/reports-1.0.0.jar
COPY ${JAR_FILE} /reports.jar
#ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/reports.jar"]
#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=PROD", "/reports.jar"]

I expect to be able to create multiple deployment scripts and call them whenever I would like with their specific arguments. If there is a better way, I am all ears! Thanks


问:
How to calculate the double integration in R
This is my  r code to calculate beta values for each case which is pretty simple

```<code>data =data.frame(
  "t" = seq(0, 1, 0.001)
)

B3t <- function(t){
  t**3 - 1.6*t**2 +0.76*t+1
}

B2t <- function(t){

  ifelse(t >= 0 & t < 0.342,
         ((t-0.5)^2-0.025),

         ifelse( data$t >=  0.342 & data$t <= 0.658,
                 0,

                 ifelse(t >  0.658 & t <= 1,
                        (-(t-0.5)^2+0.025),
                        0
                 )))

}

B1t <- function(t){
  0
}

X1t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)

  return(a0 + a1*t + a2*(t^2) + a3*(t^3))
}

X2t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)
  a4 = rnorm(1)

  return(a0 + a1 * sin(2*pi*t) + a2 * cos(2*pi*t) + a3 * sin(4*pi*t) + a4 * cos(4*pi*t))
}
</code>```

Now I want to calculate the error term.

I  have one issue:
  Can anyone help me with this question?

How do I solve the double integration in order to calculate the error term.

I know there are functions in r to do integrate but I am not sure how do I implement it here.

I am trying to do functional data analysis problem mentioned below:

What I don't know is how to find the variance in order to find the error term which follows normal distribution N(0, variance)

答:
Here is how I would do it (for one version of beta and X). Note that a double integral is just two single integrals nested into one another. A parameter n defines the number of random samples I am using for estimating the expectation in the integral.

```<code>beta <- function(t){
    return(t*t*t-1.6*t*t+0.76*t+1)
}

myX <- function(a,t){
    pt <- c(1,t,t*t,t*t*t)
    return(sum(a*pt))
}

## computes the expectation by averaging over n samples
myE <- function(n,s,t){
    samp <- sapply(seq(n),function(x){
          a <- rnorm(4)
          myX(a,s)*myX(a,t)})
    return(mean(samp,na.rm=T))
}

## funtion inside the first integral
myIntegrand1 <- function(s,t,n){
   return(beta(s)*myE(n,s,t))
}

## function inside the second integral
myIntegrand2 <- function(t,n){
    v <- integrate(myIntegrand1,0,1,t=t,n=n)
    return(beta(t)*v$value)
}

## computes sigma
mySig <- function(n){
  v <- integrate(myIntegrand2,0,1,n=n)
  return( 0.25*v$value)
}
## tests various values of n (number of samples drawn to compute the expectation)
sapply(seq(3),function(x)
             c("100"=mySig(100),"1000"=mySig(1000),"10000"=mySig(10000)))
## output shows you the level of precision you may expect:
##       [,1]     [,2]     [,3]
##  100  48.61876 47.85445 58.2094
## 1000  52.95681 50.61860 50.61702
## 10000 54.88292 53.02073 54.48635
</code>```

Body:
This is my  r code to calculate beta values for each case which is pretty simple

data =data.frame(
  "t" = seq(0, 1, 0.001)
)

B3t <- function(t){
  t**3 - 1.6*t**2 +0.76*t+1
}

B2t <- function(t){

  ifelse(t >= 0 & t < 0.342,
         ((t-0.5)^2-0.025),

         ifelse( data$t >=  0.342 & data$t <= 0.658,
                 0,

                 ifelse(t >  0.658 & t <= 1,
                        (-(t-0.5)^2+0.025),
                        0
                 )))

}

B1t <- function(t){
  0
}

X1t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)

  return(a0 + a1*t + a2*(t^2) + a3*(t^3))
}

X2t <- function(t){
  a0 = rnorm(1)
  a1 = rnorm(1)
  a2 = rnorm(1)
  a3 = rnorm(1)
  a4 = rnorm(1)

  return(a0 + a1 * sin(2*pi*t) + a2 * cos(2*pi*t) + a3 * sin(4*pi*t) + a4 * cos(4*pi*t))
}

Now I want to calculate the error term.

I  have one issue:
  Can anyone help me with this question?

How do I solve the double integration in order to calculate the error term.

I know there are functions in r to do integrate but I am not sure how do I implement it here.

I am trying to do functional data analysis problem mentioned below:

What I don't know is how to find the variance in order to find the error term which follows normal distribution N(0, variance)

Body:
Here is how I would do it (for one version of beta and X). Note that a double integral is just two single integrals nested into one another. A parameter n defines the number of random samples I am using for estimating the expectation in the integral.

beta <- function(t){
    return(t*t*t-1.6*t*t+0.76*t+1)
}

myX <- function(a,t){
    pt <- c(1,t,t*t,t*t*t)
    return(sum(a*pt))
}

## computes the expectation by averaging over n samples
myE <- function(n,s,t){
    samp <- sapply(seq(n),function(x){
          a <- rnorm(4)
          myX(a,s)*myX(a,t)})
    return(mean(samp,na.rm=T))
}

## funtion inside the first integral
myIntegrand1 <- function(s,t,n){
   return(beta(s)*myE(n,s,t))
}

## function inside the second integral
myIntegrand2 <- function(t,n){
    v <- integrate(myIntegrand1,0,1,t=t,n=n)
    return(beta(t)*v$value)
}

## computes sigma
mySig <- function(n){
  v <- integrate(myIntegrand2,0,1,n=n)
  return( 0.25*v$value)
}
## tests various values of n (number of samples drawn to compute the expectation)
sapply(seq(3),function(x)
             c("100"=mySig(100),"1000"=mySig(1000),"10000"=mySig(10000)))
## output shows you the level of precision you may expect:
##       [,1]     [,2]     [,3]
##  100  48.61876 47.85445 58.2094
## 1000  52.95681 50.61860 50.61702
## 10000 54.88292 53.02073 54.48635


问:
Efficient way to create a sorted, queue whose Iterator repeats back to the beginning in Java
I'm looking for an implementation or method of creating a mutable (with frequent updates), sorted, queue or list, that repeats in iteration. An example would be something [1, 3, 4, 9] where next() cycles through the elements, and returns back to 1 after 9. Elements are removed and added frequently, and need to be correctly sorted.

My initial plan for this was to use a LinkedList or PriorityQueue, but problems grew. I need the Queue to be sorted (preferably on updation rather than on iteration), hence using PriorityQueue, but I also need the queue to repeat when iterating (done manually, not with a loop). I considered making a class that held a Comparator and wrapped the Iterator, which looked a bit like this

public class SortedRepeatingQueue<T> extends LinkedList<T> {
    private final Comparator<T> comparator;
    private Iterator<T> iterator = iterator();

    public SortedRepeatingQueue(Comparator<T> comparator) {
        this.comparator = comparator;
    }

    public T next() {
        Collections.sort(this, comparator);
        if (!iterator.hasNext()) {
            iterator = iterator();
        }
        return iterator.next();
    }
}
```

However, this would create problems if an entry was removed or added during iteration, as the cached Iterator wouldn't be updated, and updating it would require a hefty bit of work making sure we continue at the same index. For example, if we were iterating over [1,2,3,5], were at 3 and then inserted 4, updating the iterator to make sure next() returned 4 instead of 5 would be tricky.
Another option was a simple extension of List where next() takes the first element, returns it and then moves it to the back (eg [1,3,4,5].next() returns 1 and creates [3,4,5,1]). However, this would be overridden by any sorting done on the list.
I also considered a completely custom implementation, but I don't really trust myself to create a safe, fully working implementation of this, and it would be quite time consuming.

I'm looking for any method of handling this that is fast (although speed is not a major priority as n should never really be bigger than 20-30), because I'm completely stumped.

Thanks for any help.

答:
Well, I bit the bullet and wrote my own implementation

/**
 * Implementation of {@link java.util.Queue} that represents a continuous queue of ordered data.
 * Elements are automatically sorted when added, by a given {@link Comparator}
 * This class is useful for something like a turn based game, in which a group of users take turns to perform
 * an action, and then repeat back to the first user.
 * Because of this, direct iteration or looping over WILL REPEAT INDEFINITELY, causing an
 * infinite loop.
 * A more suited example would be something like:
 *

 * var currentPlayingUser;
 * while(game in progress){
 * //wait for the user to take their turn
 * currentPlayingUser = queue.poll();
 * }
 *
 * @param <T> The type of element in the queue
 * @author Alexander Wood http://bristermitten.me
 */
public class SortedRepeatingQueue<T> extends AbstractQueue<T> {

    /**
     * Internal list for this implementation.
     * This list is guaranteed to be sorted at all times
     */
    private final List<T> backingList = new ArrayList<>();
    private Comparator<T> comparator;
    private Itr iterator = iterator();

    public SortedRepeatingQueue(Comparator<T> comparator) {
        this.comparator = comparator;
    }

    /**
     * Return, but do not remove the head element.
     * Due to the cyclic nature, removing the head element would not match the intended functionality.
     * However, this will cycle through the elements. That is, given a SortedRepeatingQueue [1,2,3]
     * poll will return 1, then 2, then 3, then 1, etc
     *

     * This is functionally equivalent to the head element being moved to the tail rather than removed, although
     * is not what happens.
     *
     * @return The "head" element of this SortedRepeatingQueue
     */
    @Override
    public T poll() {
        return iterator.next();
    }

    @Override
    public T peek() {
        return iterator.nextWithoutCycle();
    }

    @Override
    public boolean offer(T t) {
        return add(t);
    }

    public boolean add(T e) {
        backingList.add(e);
        backingList.sort(comparator);
        return true;
    }

    public boolean addAll(Collection<? extends T> c) {
        boolean b = backingList.addAll(c);
        backingList.sort(comparator);
        return b;
    }

    public boolean remove(Object o) {
        return backingList.remove(o);
    }

    public Itr iterator() {
        return new Itr();
    }

    public int size() {
        return backingList.size();
    }

    @Override
    public String toString() {
        return "SortedRepeatingQueue{" +
                "backingList=" + backingList +
                '}';
    }

    private class Itr implements Iterator<T> {
        private int cursor = 0;

        public boolean hasNext() {
            return true;
        }

        public T next() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            return backingList.get(cursor++);
        }

        public T nextWithoutCycle() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            return backingList.get(cursor);
        }

        public void remove() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            backingList.remove(cursor);
        }
    }
}
```

It uses a cursor-based iterator and wraps a sorted ArrayList to achieve exactly the functionality needed. Elements can be inserted or removed and the iterator will update accordingly. Direct iteration in a loop will cause an infinite loop, but that was not the intended purpose. A brief example use case is in the Javadocs, and most methods should have obvious or inherited functionality, and any that don't are documented.

Hopefully this helps someone else if they have my very specific issue

Body:
I'm looking for an implementation or method of creating a mutable (with frequent updates), sorted, queue or list, that repeats in iteration. An example would be something [1, 3, 4, 9] where next() cycles through the elements, and returns back to 1 after 9. Elements are removed and added frequently, and need to be correctly sorted.

My initial plan for this was to use a LinkedList or PriorityQueue, but problems grew. I need the Queue to be sorted (preferably on updation rather than on iteration), hence using PriorityQueue, but I also need the queue to repeat when iterating (done manually, not with a loop). I considered making a class that held a Comparator and wrapped the Iterator, which looked a bit like this

public class SortedRepeatingQueue<T> extends LinkedList<T> {
    private final Comparator<T> comparator;
    private Iterator<T> iterator = iterator();

    public SortedRepeatingQueue(Comparator<T> comparator) {
        this.comparator = comparator;
    }

    public T next() {
        Collections.sort(this, comparator);
        if (!iterator.hasNext()) {
            iterator = iterator();
        }
        return iterator.next();
    }
}

However, this would create problems if an entry was removed or added during iteration, as the cached Iterator wouldn't be updated, and updating it would require a hefty bit of work making sure we continue at the same index. For example, if we were iterating over [1,2,3,5], were at 3 and then inserted 4, updating the iterator to make sure next() returned 4 instead of 5 would be tricky.
Another option was a simple extension of List where next() takes the first element, returns it and then moves it to the back (eg [1,3,4,5].next() returns 1 and creates [3,4,5,1]). However, this would be overridden by any sorting done on the list.
I also considered a completely custom implementation, but I don't really trust myself to create a safe, fully working implementation of this, and it would be quite time consuming.

I'm looking for any method of handling this that is fast (although speed is not a major priority as n should never really be bigger than 20-30), because I'm completely stumped.

Thanks for any help.

Body:
Well, I bit the bullet and wrote my own implementation

/**
 * Implementation of {@link java.util.Queue} that represents a continuous queue of ordered data.
 * Elements are automatically sorted when added, by a given {@link Comparator}
 * This class is useful for something like a turn based game, in which a group of users take turns to perform
 * an action, and then repeat back to the first user.
 * Because of this, direct iteration or looping over <strong>WILL REPEAT INDEFINITELY</strong>, causing an
 * infinite loop.
 * A more suited example would be something like:
 * <p>
 * var currentPlayingUser;
 * while(game in progress){
 * //wait for the user to take their turn
 * currentPlayingUser = queue.poll();
 * }
 *
 * @param <T> The type of element in the queue
 * @author Alexander Wood http://bristermitten.me
 */
public class SortedRepeatingQueue<T> extends AbstractQueue<T> {

    /**
     * Internal list for this implementation.
     * This list is guaranteed to be sorted at all times
     */
    private final List<T> backingList = new ArrayList<>();
    private Comparator<T> comparator;
    private Itr iterator = iterator();

    public SortedRepeatingQueue(Comparator<T> comparator) {
        this.comparator = comparator;
    }

    /**
     * Return, but do not remove the head element.
     * Due to the cyclic nature, removing the head element would not match the intended functionality.
     * However, this will cycle through the elements. That is, given a SortedRepeatingQueue [1,2,3]
     * poll will return 1, then 2, then 3, then 1, etc
     * <p>
     * This is functionally equivalent to the head element being moved to the tail rather than removed, although
     * is not what happens.
     *
     * @return The "head" element of this SortedRepeatingQueue
     */
    @Override
    public T poll() {
        return iterator.next();
    }

    @Override
    public T peek() {
        return iterator.nextWithoutCycle();
    }

    @Override
    public boolean offer(T t) {
        return add(t);
    }

    public boolean add(T e) {
        backingList.add(e);
        backingList.sort(comparator);
        return true;
    }

    public boolean addAll(Collection<? extends T> c) {
        boolean b = backingList.addAll(c);
        backingList.sort(comparator);
        return b;
    }

    public boolean remove(Object o) {
        return backingList.remove(o);
    }

    public Itr iterator() {
        return new Itr();
    }

    public int size() {
        return backingList.size();
    }

    @Override
    public String toString() {
        return "SortedRepeatingQueue{" +
                "backingList=" + backingList +
                '}';
    }

    private class Itr implements Iterator<T> {
        private int cursor = 0;

        public boolean hasNext() {
            return true;
        }

        public T next() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            return backingList.get(cursor++);
        }

        public T nextWithoutCycle() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            return backingList.get(cursor);
        }

        public void remove() {
            if (cursor == backingList.size()) {
                cursor = 0;
            }
            backingList.remove(cursor);
        }
    }
}

It uses a cursor-based iterator and wraps a sorted ArrayList to achieve exactly the functionality needed. Elements can be inserted or removed and the iterator will update accordingly. Direct iteration in a loop will cause an infinite loop, but that was not the intended purpose. A brief example use case is in the Javadocs, and most methods should have obvious or inherited functionality, and any that don't are documented.

Hopefully this helps someone else if they have my very specific issue


问:
Understanding the Life cycle of Activity and Service
Suppose I have multiple activities say Screen A(Main Screen) & Screen B.

Screen A opens Screen B and then Screen B starts a service which sends updates to Screen B. Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

Now I have two question

1) Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

2) Will my service also be cleared or will it continue to run? If it is cleared then can a foreground service with a notification help me to overcome this?

Any help would be grateful.

答:
Android OS will clear the whole app if it needs memory for other application.

If activity is destroyed, services within will be also destroyed.


问:
RegEx for passing space and single quote
I'm fairly new to RegEx's and am having some issues getting my RegEx to do what I'd like it to. I'm attempting to create a RegEx that prevents any special character OTHER THAN single quote ('), dash (-), and period (.).
The RegEx needs to allow spaces, and empty strings.

What I have for now is:

```<code>^[a-zA-Z0-9-.]*$
</code>```

What would I need to add in order to make it work for example the name "Kevin O'Leary"?

I've attempted to allow spaces by adding \s, but it broke other parts of my RegEx.

```<code>^[a-zA-Z0-9-.]*$
</code>```

Expected: Should allow names like Kevin O'Leary
Actual: Does not allow names like Kevin O'Leary

答:
Simply add a quote and a space to the character range:

^[ a-zA-Z0-9'.-]*$
```

The space can simply be a literal space in the pattern. Also, you need to have the - as the last symbol, because it has a special meaning in ranges.

regex101 demo

Body:
I'm fairly new to RegEx's and am having some issues getting my RegEx to do what I'd like it to. I'm attempting to create a RegEx that prevents any special character OTHER THAN single quote ('), dash (-), and period (.).
The RegEx needs to allow spaces, and empty strings.

What I have for now is:

^[a-zA-Z0-9-.]*$

What would I need to add in order to make it work for example the name "Kevin O'Leary"?

I've attempted to allow spaces by adding \s, but it broke other parts of my RegEx.

^[a-zA-Z0-9-.]*$

Expected: Should allow names like Kevin O'Leary
Actual: Does not allow names like Kevin O'Leary

Body:
Simply add a quote and a space to the character range:

^[ a-zA-Z0-9'.-]*$

The space can simply be a literal space in the pattern. Also, you need to have the - as the last symbol, because it has a special meaning in ranges.

regex101 demo


问:
c++ code won't run on Visual Studios due to errors but no errors are shown
I have written a simple program to output different temperature units using conversions given. When I run the code on Visual Studios, it won't run due to build errors but no errors are shown. I have seen similar questions asked but couldn't really see any answer that solved my issue. I was also wondering whether I should be declaring the variables before or after the main function.</p>

```<code>#include <iostream>

using namespace std;

int fahrenheit, i=0;
float celsius, absolute_value;

main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (i = 0; i = 15; i += 1) {
        fahrenheit = i * 20;
        celsius = ((fahrenheit - 30) * 5) / 9;
        absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << celsius << absolute_value;
    }
    system("pause");
    return 0;
}
</code>```

答:
I fixed some coding errors. I think there are still some logical errors but now the code compile and program should run

```<code>#include <iostream>
using namespace std;

int main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (int i = 0; i <= 15; i += 1) {
        int fahrenheit = i * 20;
        float celsius = ((fahrenheit - 30) * 5) / 9;
        float absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << ' ' << celsius << ' ' << absolute_value << '\n';
    }
    system("pause");
    return 0;
}
</code>```

You are missing the includes for iostream and the return type for the main function. I also moved the declaration of the global variables to where the variables are used the first time. The for loop was an endless loop. So I changed i = 15 to i <= 15. Maybe you wanted a loop condition like i < 15. I also added whitespaces and linebreaks between the values.

Body:
I have written a simple program to output different temperature units using conversions given. When I run the code on Visual Studios, it won't run due to build errors but no errors are shown. I have seen similar questions asked but couldn't really see any answer that solved my issue. I was also wondering whether I should be declaring the variables before or after the main function.

#include <iostream>

using namespace std;

int fahrenheit, i=0;
float celsius, absolute_value;

main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (i = 0; i = 15; i += 1) {
        fahrenheit = i * 20;
        celsius = ((fahrenheit - 30) * 5) / 9;
        absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << celsius << absolute_value;
    }
    system("pause");
    return 0;
}

Body:
I fixed some coding errors. I think there are still some logical errors but now the code compile and program should run

#include <iostream>
using namespace std;

int main() {
    cout.width(20);
    cout << "Fahrenheit" << "Celsius" << "Absolute value\n";
    for (int i = 0; i <= 15; i += 1) {
        int fahrenheit = i * 20;
        float celsius = ((fahrenheit - 30) * 5) / 9;
        float absolute_value = celsius + 273.15;
        cout.width(20); /*each item in next output will have width of at least 20*/
        cout << fahrenheit << ' ' << celsius << ' ' << absolute_value << '\n';
    }
    system("pause");
    return 0;
}

You are missing the includes for iostream and the return type for the main function. I also moved the declaration of the global variables to where the variables are used the first time. The for loop was an endless loop. So I changed i = 15 to i <= 15. Maybe you wanted a loop condition like i < 15. I also added whitespaces and linebreaks between the values.


问:
How to write a function using for and if
I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer

I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result

```<code>r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
        r += 1
        return r

a = int(input())
factor(a)
</code>```

for example 18 has 6 factors but I receive just 1.

答:
It was an indentation problem: the function should only return after the loop has finished iterating.

```<code>r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
            r += 1
    return r

a = 18   # int(input())
factor(a)
</code>```

output:

```<code>6
</code>```

Body:
I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer

I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result

r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
        r += 1
        return r

a = int(input())
factor(a)

for example 18 has 6 factors but I receive just 1.

Body:
It was an indentation problem: the function should only return after the loop has finished iterating.

r = 0
def factor(a):
    global r
    for i in range(1, a + 1):
        if a % i == 0:
            r += 1
    return r

a = 18   # int(input())
factor(a)

output:

6