-1

I have 3 Fragments inside a ViewPager. I call an API in onCreate() of the first Fragment which returns JSON data (second and third Fragments are empty).

The problem is that onCreateView() is always executed before getting data from API, so I need to swipe two times to right which will call onPause() method of the first Fragment, and then I need to come back to the first Fragment which will call onCreateView() of first Fragment and this time because data has been loaded from the Internet, it will show data.

How can I overcome this problem and force the first Fragment to show data on the first onCreateView() call?

Mehrdad Salimi
  • 1,400
  • 4
  • 16
  • 31
  • 1
    is not a problem, and you need to handle it. Explicitly handle it. Either showing a "loading ... " while waiting, and handle the server side errors, or using some data model (I recommend Architectural Components) which loads the view for you on UI once ready (and meanwhile you would need to handle the empty state) – Alessio Oct 29 '18 at 09:56
  • Is there a way to stop `onCreateView()` until data loaded from the Internet? Is this what using `Architectural Component` will provide me? – Mehrdad Salimi Oct 29 '18 at 10:00
  • Why donw vote? Please give a clue! – Mehrdad Salimi Oct 29 '18 at 10:01
  • I also think this question shouldn't be downvoted (I guess it's because it's so basic that if you google you'll find the answer immediately). No, you don't want to stop onCreateView() because Android will kill your app otherwise. Like I wrote, you need to handle the case explicitly. Architectural Component will provide you reactiveness, that is that your UI views will refresh once your dataset is loaded. But you really need to understand what you're doing here IMHO, because it's basic Android – Alessio Oct 29 '18 at 10:08
  • @Alessio It's already half a day that I am trying to find the solution by searching Google and finally decided to ask a question. Anyway, thanks for your help. I will read my code again to better understand it and also will read about `Architectural Component`. – Mehrdad Salimi Oct 29 '18 at 10:13

1 Answers1

1

You need to make the API calls in AsyncTasks, in background, and in onPostExecute(Result) method do your UI updates.

AncaS
  • 110
  • 7