Reputation: 3968
I've tried this and it works, but I didn't know if this was a bad thing or not, as all the help on data transfers between Activities seems to use intents.
In MainActivity I have:
static PilotRecord pilotRecord = new PilotRecord(); //PilotRecord just contains data item declarations
In MainActivity.onCreate:
pilotRecord.fuel = 100;
In MainActivity.onClick:
Intent intent = new Intent(this, SubActivity.class);
startActivityForResult(intent, 0);
In SubActivity.onCreate I have:
MainActivity.pilotRecord.fuel = 200;
In SubActivity.onClick:
MainActivity.pilotRecord.fuel = 300;
setResult(RESULT_OK);
finish();
When I start MainActivity, the fuel value is 100
If I click in MainActivity, SubActivity is displayed, as expected
If I click in SubActivity, MainActivity is displayed and the fuel value is now 300
If I press the Back button, MainActivity is displayed and the fuel value is now 200
Does anyone know of any potential issues with this as it seems simpler to me than setting up intents etc.
Upvotes: 1
Views: 216
Reputation: 830
If you really want to hack it, create another class that hold all your static variables that needs to be shared.
Upvotes: 1
Reputation: 3748
It is my understanding that what you are doing will result in data loss.
The SubActivity should not be manipulating the data of the activity that called it. I don't think that there is any guarantee that your MainActivity even exists...
The system may decide to kill it at any time and restart it when your SubActivity signals that it is ready to return to the MainActivity.
You should pass back the data in a bundle and let MainActivity modify its data based on the results.
Bundle stats = new Bundle();
stats.putString("fuel","300");
setResult(RESULT_OK, "PilotRecord", stats);
finish();
Also, remember that you should be saving the "Fuel" level to some sort of persistent storage when onPause() is called in your MainActivity.
I would suggest reading the documentation for Activity carefully since it is quite important to implement the correct callbacks.
Upvotes: 3