0

I have an activity which contains a recyclerView that loads data from the database. Sometimes when starting the activity I don't see the data until reloading the activity.

What I'm trying to do is show a loading animation for 3 seconds and wait for it to load then show it.

I added this to my xml:

<RelativeLayout
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true" />
</RelativeLayout>

But how can I make my activity wait for 3 seconds (showing the loading animation) and then go back to the activity with loaded data?

  • use callbacks or events, pausing main thread or implementing fix delay is code smell – Pavneet_Singh Jan 30 '20 at 11:06
  • can u explain a bit more, the question is not clear – darwin Jan 30 '20 at 11:19
  • I don't think you should wait for exactly 3 seconds. If you are loading your Recyclerview data from an API it may take less/more time than that depending on your network speed, server, etc. The best way is to cancel your progress dialog once you load your data through a call back. Could u share the code where u r loading the data – p.mathew13 Jan 30 '20 at 11:23
  • Are you aiming to wait AT LEAST 3 seconds or more if needed. Or would you expect that the load will be always less than 3 seconds. Otherwise, @ other commenters: sometimes it is worth setting minimum loading indicator time so that you do not frustrate the user. – Boris Strandjev Jan 30 '20 at 11:24
  • When I start my activity, my recyclerView is empty, now I want to make my activity wait until my recyclerView has the data from the database, but while it's waiting I want to show loading animation. – Jeries Elias Jan 30 '20 at 11:25
  • you can use an asyncTask: https://stackoverflow.com/questions/6450275/android-how-to-work-with-asynctasks-progressdialog – Nikos Hidalgo Jan 30 '20 at 11:40

1 Answers1

0
  1. Create a callback class:

    interface Callback { public void onStart(); public void onComplete(<your_data_type> data); }

  2. Add a callback as an argument to your method, that loads data from database, then you need to call the callback's methods when the events happen:

    public void loadData(Callback callback) { callback.onStart(); <your_data_type> data = /* load data from database */; callback.onComplete(data); }

  3. Pass it an implemented callback to loadData method:

    loadData(new Callback { public void onStart() { // start showing your progress bar } public void onComplete(<your_data_type> data) { // show data in your recycler view // hide your progress bar } });

And of course you need to call loadData() method in a background thread and call the callback's methods in a main thread.

easy_breezy
  • 1,073
  • 7
  • 18