Loading data into a fragment using an http request

I have Fragment

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

What's the good practice to make a request to Activity

and pass data to Fragment

or load data to Fragment

directly?

I am currently loading data in Fragment

directly, but I keep checking the fragment isAdded()

and getActivity()

not null

after loading the data and displaying it inside the fragment.

+3


source to share


2 answers


I believe the data load belongs to the chunk. Otherwise, if your MainActivity has 5 fragments, your code will be complicated and confusing.

You can also define a class responsible for loading data. Something like this (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);
    }

}

      

+1


source


It does not affect the fragment or the activity at all as it would a request made in the background. It depends on your condition: whether you want to display the content immediately after the fragment appears, or you can wait inside the fragment. For example: - if you don't want to display the views of the fragments, just do the query operation and wait inside the activity, as you will get the result, just go back to the fragment. Hope this helps you.



0


source







All Articles