Right Approach to Call Web Service(API) from Fragment class

前端 未结 3 1671
执笔经年
执笔经年 2020-12-28 19:21

I need to know, In which fragment callback method, we should call a web service by which after come back to fragment web service should not call again.

For example.

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 19:36

    onCreate() is tricky.

    Put everything that you want to call just once in onCreate() method. For example your API call, list, adapter initialization.

    So ideally I would do like this

    public void onCreate(Bundle sis) {
    
        getImagesFromServer(); // API Call 
        initialzeLists()
        initializeAdapters()
    
    }
    
    public View onCreateView(LayoutInflater i, ViewGroup c,Bundle sis) {
        recyclerView = findViewById()
        setUpAdapters()
        return rootView;
    }
    

    TRICKY PART

    But if you really want onCreate() to be called once then reuse Fragment. (Don't create a new instance every time).

    How to reuse a Fragment?

    While Adding for first time use add it to backStack with a KEY like this

    currentFragment = FirstFragment.getInstance();
    getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
                .addToBackStack("FIRST_KEY")
                .commit();
    

    And when you want to add it again get the old instance with the KEY like this

    currentFragment = getSupportFragmentManager().findFragmentByTag("FIRST_KEY");
    getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
                .addToBackStack("FIRST_KEY")
                .commit();
    

    Demo project:

    Here is the link to a demo project which loads a list of images using the Volley library. It has a similar implementation.

    Woof - Use fragments the right way

提交回复
热议问题