How to display progressbar while load data and fill into recyclerview?

1.6k views Asked by At

I want display progress bar in activity while loading data and when loading complete, progress bar to be hide (GONE)! and try this code : (button click to load data)

private void allMoment() {
    BTN_ALL.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                TBL_MOMENT = new TableMoment(DB_HELPER);
             //   MOMENTS = TBL_MOMENT.MOMENT_LIST();
                new loadTask().execute();
                filterResult();
                EDT_SEARCH.setText("");
            } catch (Exception e) {
                displaySnackBar(v, "خطا:" + "\n" + e.toString());
            }
        }
    });
}

and Task method :

private class loadTask extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
        PROGRESS_LOADER.setVisibility(View.VISIBLE);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        PROGRESS_LOADER.setVisibility(View.GONE);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        MOMENTS = TBL_MOMENT.MOMENT_LIST();
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

and fill recycler with dapter :

private void filterResult() {
    try {
        adapter = new HistoryAdapter(this, MOMENTS);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    } catch (Exception e) {
        displayToast(this, "خطای آداپتر:" + "\n" + e.toString());
    }
}

but data become load and fill into recyclerview and don't show progress bar how to fix this problem ?

2

There are 2 answers

2
from56 On BEST ANSWER

You have :

 new loadTask().execute();
 filterResult();
 EDT_SEARCH.setText("");

This execute() call returns inmediatly, if you execute an AsyncTask waiting for a result you don't have a result until AsyncTask.doInBackground() returns and AsyncTask.onPostExecuted() is called

Is this filterResult(); time consuming ? ... if the main UI thread is blocked then the UI will be not updated.

0
Marcos Guimaraes On

How do you want this progress bar to work? You can search for a gif on the Internet, once you find one that suits your criteria you have to display it when you open the activity. When you populate your recyclerView you set the visibility of the gif as GONE.