in my code lets say that I want to display some string in a fragment, and method getPlayerList takes 2 seconds(data from API), but method 'onCreateView' is returning the view before 'getPlayerList' finishing its execution.
I tried to implement it in many ways, but every thing was useless because I can't change 'return view;' place ^^".
is there any method instead of 'onCreateView' that suits my situation ?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_tab4, container, false);
String result = getPlayerList();
//displaying the 'result' on this view
return view; }
Do not request and wait in main thread. first of all keep that view variable as a field instead of local. then move your request to onViewCreated
method. and finally use callback instead of return value and do all request things in background thread. you can use Volley or Retrofit for high level networking. also because you have to wait until get result from server fill the UI with placeholder your empty strings before you set them.
check this example in MVP structure from google. the view created in method but the value of ui set in another method later. for example see the showDescription
method that set the description textview
https://github.com/googlesamples/android-architecture/blob/todo-mvp/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailFragment.java
also for callback see this public void success
method in Retroift.
https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
you get value in a method and you can set that value with the fields of view.