Search code examples
javaandroidandroid-fragmentsminesweeperandroid-bundle

How to update arguments in a bundle


I'm making a minesweeper game, and i'm having problems with updating the values in a bundle. At first I set the value of the difficulty to 0 and I use the value of difficulty choose other values for the game and place it in the bundle. This is how it looks:

difficulty 0
rows 9
columns 9
mines 10

Then I decide the increase the difficulty, however the values for game doesn't get updated:

difficulty 1
rows 9
columns 9
mines 10

Why aren't the bundled values changing when I select a new difficulty? The source code is posted below.

MainActivity.java:

public class MainActivity extends Activity {

    private int difficulty;
    //...

    private void startGame(){
        Bundle b = new Bundle(3);
        Log.d("difficulty",""+difficulty);
        switch(difficulty){
            case 1:{
                b.putInt("rows",16);
                b.putInt("columns",16);
                b.putInt("mines",40);
            }
            case 2:{
                b.putInt("rows",30);
                b.putInt("columns",16);
                b.putInt("mines",99);
            }
            default:{
                b.putInt("rows",9);
                b.putInt("columns",9);
                b.putInt("mines",10);
            }
        }

        gridFragment = new GridFragment();

        gridFragment.setArguments(b);
        getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();

    }
    //...
}

GridFragment.java:

public class GridFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_grid, container, false);
        Log.d("rows",getArguments().getInt("rows"));
        Log.d("columns",getArguments().getInt("columns"));
        Log.d("mines",getArguments().getInt("mines"));
        return view;
    }
    //...
}

Solution

  • you need to put break after each case. Otherwise it falls through to the next case and so on. In your case all cases ends with default.

    switch (difficulty) {
       case 1:
         ...
         break;
       case 2:
         ...
         break;
    }