Identify if an activity has just been started
I have 2 activities.
Activity 1 is the 'Homepage' which consists of one spinner.
Activity 2 will be started once an item from the spinner has been selected in Activity 1. The value of the item will also be passed into Activity 2.
Actvity 2 also has the same spinner as Actvity 1.
I would like to make a variable (referenced as TABLE_NAME
in the code below) whose value will be the selection made in Activity 1 when Activity 2 is initally started but after that the variable value will be the selection made in Activity 2.
Is there an easy way to identify if an activity has just been started?
I've tried to show what I want in the code below:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if(this activity was just started)
{Intent sender=getIntent();
String TABLE_NAME=sender.getExtras().getString("TABLE_NAME");}
else
{TABLE_NAME = parent.getItemAtPosition(pos).toString();}
Cursor cursor = getStats(TABLE_NAM开发者_Python百科E);
showStats(cursor);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
The following code...
Intent sender=getIntent(); String
TABLE_NAME=sender.getExtras().getString("TABLE_NAME");
... should be moved from your onItemSelected
selected function, and instead be done in the onCreate
function of your Activity 2.
And of course, while doing that you must also call your getStats
/showStats
after this is done in onCreate
as well (or preferably, these two should be refactored into a separate function, as you will be calling this both from onCreate
and onItemSelected
).
If this is within android (which is the tag that is on the post), you can put a hook in the 'onCreate()' method in which you save what activity you are in to the Database table. The onCreate method is called every time an activity is created/re-created.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this is where you would identify the activity has been called, perhaps spinning off a thread to handle a database call:)
}
精彩评论