本人写了一个activity初始化了一些数据,而在另一个activity改变数据后返回时,发现数据又再一次被初始化,有什么办法可以改变这种情况吗?
初始化数据是在onCreate()
PHP中文网2017-04-17 17:36:18
I understand it this way, do you see it right?
For example, two activities, A and B, have some data that can be modified by both A and B. We call this part of the data shared data.
First A initializes the shared data, then A starts B, and B modifies the shared data. When B returned, he checked the shared data in A and found that it was still the initial initialization data, not the modified data in B that we expected.
A possible reason is: after A started B, A was destroyed. This can be confirmed by tracing the log information.
When B returns, the system starts A again, but A will execute onCreate() again, and the shared data is initialized again in onCreate(). If you look at it at this time, it is still the original initialization data.
Solution: Use onSavedInstance() to save shared data, and use the saved shared data in onCreate().
I use a string FileUri as an example of shared data:
Where to save data:
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
if(FileUri!=null){
outState.putString("FileUri", imageFileUri.toString());
}
super.onSaveInstanceState(outState);
}
Use saved data:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null ) {
String str=savedInstanceState.getString("FileUri");
if(str!=null)
{
FileUri = Uri.parse(str);
}
}
else {
//初始化共享数据
}
//其他初始化工作
}
伊谢尔伦2017-04-17 17:36:18
First of all, you need to confirm whether the initialization data is only placed in onCreate? If so, then this Activity should be recycled due to an abnormal situation. Entering this Activity again will re-initialize the data!
PHPz2017-04-17 17:36:18
If you just don’t let it initialize, it will be OK as long as it is kept alive. As for the subsequent activity to operate the data and communicate with the first activity, it will be OK