There is a method that is responsible for loading data using Retrofit 2.
Fragments have several states.
I need to start the fragment, load the data immediately, without any pressing.
What is the condition to execute the method?
I tried onCreate, onViewCreated, onCreateView, onAttach, but the method was not implemented everywhere.
I already thought that the method may not work correctly, so I added a message to the Log in 1 line of the method, but it also does not appear in the log. What am I doing wrong?
Code:
public class SmartphoneMainTab extends Fragment { private ProgressBar progressBar; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.tab_smartphone_main, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); progressBar = (ProgressBar)view.findViewById(R.id.progressBar); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); } public void LoadData(int id){ Log.e("Start","start"); progressBar.setVisibility(ProgressBar.VISIBLE); Retrofit retrofit = new Retrofit.Builder() .baseUrl(APIUrl.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); APIService service = retrofit.create(APIService.class); Call<Smartphone> call = service.getSmartphone(id); call.enqueue(new Callback<Smartphone>() { @Override public void onResponse(Call<Smartphone> call, Response<Smartphone> response) { Smartphone smartphone = response.body(); Log.e("smartphone",smartphone.brand); if(smartphone.getBrand()!=null){ Toast.makeText(getContext(),smartphone.brand,Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Smartphone> call, Throwable t) { Log.e("Ошибка",t.getMessage()); progressBar.setVisibility(ProgressBar.INVISIBLE); Toast.makeText(getActivity(),t.getMessage(),Toast.LENGTH_SHORT).show(); } }); } }