0

I can't really explain what I'm trying to say through the title, but I'll expand here.

Anyway, I'm still learning how to code so pardon my misuse of a few terms.

I made a simple app that displays an array of strings. It features just two visual parts- a TextView element and a Button element. Pressing the button displays a random fruit from the String Array.

Thing is, when I change orientations, the displayed fruit changes. I know that this happens because the activity is 'remade' whenever the orientation is changed. And I do have an understanding on how to use onSaveInstanceState and its counterpart.

But I have no idea how to save and restore the currently-displayed value in the Display because I'm using Random instead of int. Because of this, I don't think I can rely on using putInt and getInt.

TextView Display;
Button randomize;
String[] fruitArray;
Random counter = new Random();
Random rand = new Random();
int launchCounter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initializeButtons();
    checkAndroidVersion();
    changeFont();

    fruitArray= getResources().getStringArray(R.array.fruits);

    launchCounter = rand.nextInt(10) + 1;

    Display.setText(fruitArray[launchCounter]);

    randomize.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int maxIndex = jokeArray.length;
            int generatedIndex = counter.nextInt(maxIndex);
            Display.setText(fruitArray[generatedIndex]);

        }

    });

4 Answers4

0

Try this snippet:

@Override    
protected void onSaveInstanceState(Bundle icicle) {
  super.onSaveInstanceState(icicle);
  icicle.putString("position", launchCounter);
}
And restore the values in onCreate():

@Override
public void onCreate(Bundle icicle) {
  ...
  if (icicle != null){
    value = icicle.getString("position");
  }
}

Instead of restoring data in onCreate() you could use onRestoreInstanceState(). The difference is explained here: onSaveInstanceState () and onRestoreInstanceState ()

Community
  • 1
  • 1
Yehor Nemov
  • 877
  • 2
  • 16
  • 29
0

You can try defining generatedIndex static globaly or you can use preferences to save the random number.

save your value in Preferences like this:-

SharedPreferences mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSharedPrefs.edit().putInt("KEY", generatedIndex).commit();

during onCreate you can get back the saved value using mSharedPrefs.getInt("KEY", "") and display it in TextView.

cool Boy
  • 316
  • 1
  • 2
  • 9
0

Firstly, you need to @Override your onSaveInstanceState method. You could do the following for your code.

// This bundle will be passed to your onCreate method when it is called
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putInt( "LaunchCounter", launchCounter );
}

Now where you define this line:

launchCounter = rand.nextInt(10) + 1;

You should replace it with the following:

// If this is re-creating then it will not be null.         
// If it has just been initialised, it will be.
if ( savedInstanceState != null ) 
{
    launchCounter = savedInstanceState.getInt( "LaunchCounter" );
} 
else 
{
    launchCounter = rand.nextInt(10) + 1;
}

You can replace the hard-coded strings with a static String reference.

Zyn
  • 614
  • 3
  • 10
0

Because you are storing fruit names in an array, you can store the array index of the fruit currently being displayed when onSaveInstanceState is called. In onRestoreInstanceState, you can then retrieve the index of the current fruit using getInt (String key, int defaultValue).

If you assign -1 to the fruit index variable if no saved instance state exists, and specify it as the default value if none is stored in the saved instance state, you can then either simply generate a new random index if the variable is -1, or assign the correct text to the TextView if it is not.

public class MainActivity extends Activity {

   TextView labelFruit;
   Button buttonCycle;

   String[] fruitArray;
   Random rand = new Random();
   int fruitIndex = -1;

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

        fruitArray = getResources().getStringArray(R.array.fruits);

        labelFruit = (TextView) findViewById(R.id.text_fruit);
        buttonCycle = (Button) findViewById(R.id.button_cycle);

        buttonCycle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fruitIndex = rand.nextInt(fruitArray.length);
                labelFruit.setText(fruitArray[fruitIndex]);
            }
        });
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState == null) {
            fruitIndex = -1;
        } else {
            fruitIndex = savedInstanceState.getInt("FRUIT_INDEX", -1);
        }

        if (fruitIndex == -1) {
            fruitIndex = rand.nextInt(fruitArray.length);
        }

        labelFruit.setText(fruitArray[fruitIndex]);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("FRUIT_INDEX", fruitIndex);
    }
}
David Smith
  • 1
  • 1
  • 2