After user inputs parameters in MainActivity
for my app (shown below), he taps Search
, which calls MatchesActivity
, which generates output on a new screen (shown further below), which is exited via tapping back
.
But with MatchesActivity
active, every time the device is rotated, Search
is again executed because the Activity
restarts. In the screenshot below, I rotated device from vertical to horizontal to vertical to horizontal back to vertical.
The output is generated in MatchesActivity
that is invoked in onCreate
in MainActivity
like so:
Intent matchesIntent;
matchesIntent = new Intent(MainActivity.this, MatchesActivity.class);
startActivity(matchesIntent);
Here's the essence of onCreate
for MatchesActivity
:
@Override protected void onCreate(Bundle savedInstanceState)
{
MainActivity.dbc.setDbProcesslistener(this); // to know txaMatches has been defined
MainActivity.dbc.findDBMatches(); // generate output
}
I did research. I found some complicated ways of preventing an activity from restarting when the device is rotated. For example .
I'm hoping for a simpler solution. Any ideas?
My solution was simple.
Introduce boolean
variable outputIsShowing
, set it to true
in onCreate
as MatchesActivity
terminates, set it for false
when onCreate
or onResume
are executed in MainActivity
(i.e., when MatchesActivity
terminates), and return immediately in onCreate
for MatchesActivity
if outputIsShowing
is true
.
So if MatchesActivity
is active when device is rotated, outputIsShowing
will be true, so don't execute again.
It may not be best practice, but I've extensively tested it under normal conditions and am happy enough so far. Not sure if anything is lurking out there as a "gotcha".
I plan to go back and study the suggestions made so far since the more general situation is definitely important. And I will have to do so if someone finds fault with what I've done.
@Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// usual details prior to asking for matches
if(outputIsShowing)
return;
MainActivity.dbc.setDbProcesslistener(this); // to know matches was defined
MainActivity.dbc.findDBMatches();
outputIsShowing = true;
}
* EDIT *
Strangely, after embedding TextView
txaMatches
in a ScrollView
to accomplish smooth, accelerated scrolling, I had to remove the references to outputIsShowing
in order to see output after two device orientation changes.
And now, maybe I'll submit another question to address the fact that, very infrequently after screensaver forces waking the device, the output does NOT show if that is where the focus was when screensaver became active. Tapping 'back' to get to user input screen and then immediately tapping Search
restores all to normal until about 100 (give or take) screensaver instances later, the output is again missing.
Such a bug makes me think I ought to follow the advice above.
If I do, or when I figure out the problem, I'll edit this again.