Search code examples
androidscreen-orientationandroid-orientation

Counting the number of times my android app opens and handling screen orientation


In detail, I am counting the number of times my app opens with the help of the interface SharedPreferences and showing that count on screen but when ever I change orientation the count still increments.

I do not want to stick the layout in portrait, I want both orientations available for my app the code for the onCreate() is shown below:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate!");

    mPrefs = getPreferences(MODE_PRIVATE);

    int count = mPrefs.getInt(COUNT, 0);

    count = count + 1;
    Editor editor = mPrefs.edit();
    editor.putInt(COUNT, count);
    editor.commit();

    mTextView = new TextView(this);
    mTextView.setTextSize(40);
    mTextView.setText("Count: " + count);
    Log.d(TAG, "Count is " + count);
    setContentView(mTextView);
    // setContentView(R.layout.activity_main);

    mTextView.setOnClickListener(this);

}

Solution

  • You could only increment the count when it hasn't been saved via savedInstanceState because onSaveInstaceState is called when the orientation is changed

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY)){
                count = savedInstanceState.getInt(KEY);
            } 
        } else {
            count = mPrefs.getInt(COUNT, 0);
            count += 1;
            Editor editor = mPrefs.edit();
            editor.putInt(COUNT, count);
            editor.commit();
        }
    }
    
        @Override
        protected void onSaveInstanceState (Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt(KEY, count);
        }