I wonder which one of the following two approaches is the best way to load a fragment with the data coming from a web service. Here is the scenario: In Fragment 1, when a button is clicked, Fragment 2 comes to screen and the views in Fragment 2 are filled with the data coming from a web server.
1st approach: Make a request to web service as soon as button is clicked at Fragment 1, keep the data coming from the service, and then pass this data to Fragment 2:
public void onClick() //Fragment 1
{
makeRequest();
}
public void handleResponse(Response response){ //Fragment 1
ServiceData data = (ServiceData) response;
Fragment2 fragment2 = new Fragment2(data);
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction.replace(R.id.container, fragment2).commit();
}
//and
protected void onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) //Fragment 2
{
View v = inflater.inflate(R.layout.fragment_2_layout . . . );
Button b = (Button) v.findViewById(. . . );
b.setText(data.getButtonText);
. . .
return v;
}
2nd approach: When button is clicked in Fragment 1, do not make a request, just start Fragment 2, then at the end of onCreateView of Fragment 2, make a request and then fill the views with data coming from service.
public void onClick() //Fragment 1
{
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction.replace(R.id.container, fragment2).commit();
}
protected void onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) //Fragment 2
{
View v = inflater.inflate(R.layout.fragment_2_layout . . . );
Button b = (Button) v.findViewById(. . . );
. . .
makeRequest();
return v;
}
public void handleResponse(Response response){ //Fragment 2
ServiceData data = (ServiceData) response;
b.setText(response.buttonText);
. . .
}
My concern with 2nd approach: Suppose service request fails, in this case views were created but not filled with data(i.e. button text is not set, imageviews's images are not loaded etc.). is that acceptable?
My concern with 1st approach: Why make a request in Fragment 1 whose data is related to Fragment 2?
So, i wonder which one of these 2 options is the best, or is there any other better way to do this?
Thanks