amodkanthe
amodkanthe

Reputation: 4530

loading data in fragment using http request

I have a Fragment and I want to load some JSON data into it by making an HTTP request.

What's the right practice to make a request in Activity and pass the data to the Fragment or Load the data in the Fragment directly?

Currently, I am loading the data in the Fragment directly but I have keep checking fragment isAdded() and getActivity() is not null after data is loaded and when going to display it inside fragment.

Upvotes: 3

Views: 2079

Answers (2)

devops
devops

Reputation: 9179

I believe the loading of data belongs to the fragment. Otherwise, if your MainActivity has 5 fragments, your code will be complex and confusing.

You could also define a class that is responsible for loading the data. Something like that (pseudocode!):

public class FragmentCustomerList extends Fragment implements OnCustomersLoadedCallback {

    @Override
    public void onStart() {
        super.onStart();

        showLoadingDataView(); // show data loading spinner

        DataLoader.instance().loadCustomersASYNC(this);
    }

    // OnCustomersLoadedCallback 

    @Overrride
    public void onDataLoaded(List<Customer> customers){

        hideLoadingDataView(); // hide data loading spinner

        showData(customers);
    }

}

Upvotes: 1

Abhishek
Abhishek

Reputation: 1345

It doesn't effect the fragment or activity at all, as the request done in background. It depends on your condition that whether you want to display the content just after the fragment appearance or you can wait inside the fragment. For example :- if you don't want to display the fragment's views so just perform request operation and wait inside the activity, as you get the results just move back to the fragment. Hope this will help you

Upvotes: 0

Related Questions