I am trying to create a basic application that just counts how many times the user changes the orientation to landscape from portrait and displays the count on screen. I have:
public class MainActivity extends Activity {
int count = 0;
private static boolean inLandscape = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.count);
tv.setText(getResources().getString(R.string.count) + ' ' + count);
if (!inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
inLandscape = true;
count++;
Log.e("Debug","In Landscape " + count);
}
else if (inLandscape && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
inLandscape = false;
}
The problem is, in my debug statement count is always 1, and the text never changes on the screen. Doing some research, I think this is because the activity gets trashed and recreated every time the orientation changes. How do I maintain the variable value throughout orientation change?
I tried using the savedInstanceState with
if (savedInstanceState.containsKey("count"))
count = savedInstanceState.getInt("count");
savedInstanceState.putInt("count", count);
but this gives a NullPointerException at the containsKey
line.