android - 如何避免activity再次启动时又一次初始化数据
PHP中文网
PHP中文网 2017-04-17 17:34:18
0
13
1268

本人写了一个activity初始化了一些数据,而在另一个activity改变数据后返回时,发现数据又再一次被初始化,有什么办法可以改变这种情况吗?


初始化数据是在onCreate()

PHP中文网
PHP中文网

认证0级讲师

reply all(13)
迷茫

Put the initialization data operation in the onCreate method. You may put it in onResume.

小葫芦

It is recommended to learn about the content of Activity Lifecycle in the official Android tutorial.
The website address is https://developer.android.com...

Solution:

Put the initialization operation in the OnCreate() 方法中,而不是 OnResume() 或者 OnStart() method of Activity.

You can also set the static global variable identifier to 0, set it to 1 after initialization, and determine whether the variable is 0 before initialization. However, this is not the right way. It is recommended to understand LifeCycle to solve this problem.


Attached is a picture of Lifecycle

黄舟

The first phenomenon is that the data has been initialized again, so the solution is as follows:
1. Think about why the data has been initialized again. As mentioned above, maybe you initialized it in the OnResume(), OnStart() methods
2. Generate The cause of the problem is that the data is initialized multiple times, so you can add the function of multiple calls to the data initialization. Use object-oriented ideas to encapsulate the initialization data, which is a little bit like the single-interest model. The advantage of this is to solve the problem that may occur due to multiple executions. question,

PHPzhong

If every time your Activitydestroy了话,那么你把初始化的程序放到onCreate中自然达不到你想要的结果。所以你还是先打下log看下你Activitylifecycle.

阿神

Every time you enter the page, determine whether the data already exists. If it already exists, use cache and do not request the network to load the data.

Peter_Zhu

By logging and combining it with the android life cycle function, the problem is basically solved

大家讲道理

It means your activity has been killed, consider the reason

Ty80

Usually, onCreate will be called again when the Activity is destroyed. Check the startup mode of the current Activity and the startup mode of another Activity.

黄舟

You can consider the startup mode of your Activity, there are 4 startup modes, there is always one suitable for you

巴扎黑

onSavedInstance()
onRestoreInstance()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template