Avoid loading data again when finishing activity

痴心易碎 提交于 2019-12-12 05:38:40

问题


In my main Activity of the app, I download some user data at the onStart(). When I open the Settings and I hit the Back button, I finish the Settings Activity and I return to the main Activity. The problem is that the data is being re-downloaded.

So, how can avoid the re-downloading of data?

I've though about startActivityForResult but I don't know how to use it and I do not understand how it works.

Thank you in advance!


回答1:


Define a static variable in your main activity class like this:

public static bool download = true;

When you are returning from settings change its value to false like:

MainActivity.download = false;

And put your download method inside an if statement like this:

if (download) {
yourdownloadcode();
}



回答2:


That is the usual behavior of Android. When you launch your "Settings Activity" your "Main Activity: calls onStop and the Activity is stopped. Now when you click the back button from the "Settings Activity" the "Main Activity" comes to the forefront and the onStart method is called again. Since you say that you are downloading the data in the onStart method, the data will again get downloaded.

You can avoid that by downloading the data in the onCreate Method.




回答3:


When your main activity become visible after you press Back button on your Settings activity, onStart method is called once again (see Activity Lifecycle). It is why you start re-downloading data once again. So, keep some flag which indicates, that you already started download task. But keep in mind that your main activity can be killed any time after its onPause method get called.




回答4:


If you want to load data only ones you can use Activity onCreate. Here is the activity lifecicle information: http://developer.android.com/reference/android/app/Activity.html

startActivityForResult 

you can use like a callback for your settings screen - if you need to change Main Activity layout after you change configuration on your Settings screen. You can find an example here http://saigeethamn.blogspot.com/2009/08/android-developer-tutorial-for_31.html



来源:https://stackoverflow.com/questions/11842051/avoid-loading-data-again-when-finishing-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!