简体   繁体   English

如何确保每次调用片段时都不会重新检索从服务器检索到的数据

[英]How to make sure that data that has been retrieved from a server is not re-retrieved every time a fragment is called

I am working with fragments and a navigation drawer. 我正在处理片段和导航抽屉。 I have two fragments and a fragment manager to recycle them when I click on the menu items in the navigation drawer. 单击导航抽屉中的菜单项时,我有两个片段和一个片段管理器来回收它们。 I am also receiving data from a server in one of the fragments. 我也在其中一个片段中从服务器接收数据。

However, every time I reinitialize the fragment, the call to the server occurs again. 但是,每次我重新初始化该片段时,都会再次发生对服务器的调用。 I would like to know if there is any way that I can make sure that the server call only occurs in the beginning and when I click the refresh button. 我想知道是否有任何方法可以确保服务器调用仅在开始时以及单击刷新按钮时发生。

I would like to know if there is any way that I can make sure that the server call only occurs in the beginning and when I click the refresh button. 我想知道是否有任何方法可以确保服务器调用仅在开始时以及单击刷新按钮时发生。

Yes , when you click on the refresh button use an ClickListener to trigger the call. 是的,当您单击刷新按钮时,请使用ClickListener来触发呼叫。

If you want the call to occur only when fragment is created you can refer to the fragment life cycle. 如果希望仅在创建片段时才进行调用,则可以参考片段的生命周期。 The better way is to put this call in the onCreate() method. 更好的方法是将此调用放在onCreate()方法中。

However if you don't want to make a call each time the fragment is created i recommend you tu use the SharedPreference to save the information that call have already been made. 但是,如果您不想在每次创建片段时都进行呼叫,我建议您使用SharedPreference保存已进行呼叫的信息。

exemple: 为例:

prefs = PreferenceManager.getDefaultSharedPreferences(this);
        // The seconde value of method getBoolean incates the default value if constant not found
        if (prefs.getBoolean(Constants.CALL_DONE, false)) {
            // Make call
            prefs.edit().putBoolean(Constants.CALL_DONE, true).apply();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM