AsyncTask.class

 avatar
unknown
java
2 years ago
2.9 kB
5
Indexable
package com.maurya.simplefileexplorer;


import android.os.AsyncTask;
import android.view.View;

import com.maurya.simplefileexplorer.Adapters.FileAdapter;
import com.maurya.simplefileexplorer.databinding.FragmentInternalBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileAsyncTask extends AsyncTask<Void, Void, ArrayList<File>> {
    private File storage;
    private int currentPage;
    private int ITEMS_PER_PAGE = 20;
    private List<File> fileList;
    private FileAdapter fileAdapter;
    private FragmentInternalBinding internalStorageBinding;
    private boolean isLoading = false;

    public FileAsyncTask(File storage, int currentPage,
                         List<File> fileList, FileAdapter fileAdapter,
                         FragmentInternalBinding internalStorageBinding) {
        this.storage = storage;
        this.currentPage = currentPage;
        this.fileList = fileList;
        this.fileAdapter = fileAdapter;
        this.internalStorageBinding = internalStorageBinding;
    }

    @Override
    protected ArrayList<File> doInBackground(Void... voids) {
        return findFiles(storage, currentPage, ITEMS_PER_PAGE);
    }

    @Override
    protected void onPostExecute(ArrayList<File> newFiles) {
        super.onPostExecute(newFiles);

        if (newFiles != null) {
            fileList.addAll(newFiles);
            fileAdapter.notifyDataSetChanged();
        } else {

        }
        isLoading = false;
        internalStorageBinding.bottomProgressBarInternal.setVisibility(View.GONE);
    }

    @Override
    protected void onPreExecute() {
        // Perform any setup or initialization before the background task
        internalStorageBinding.bottomProgressBarInternal.setVisibility(View.VISIBLE);
        isLoading = true;
        fileList.add(null);
        fileAdapter.notifyItemInserted(fileList.size() - 1);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // Update the UI or notify components about the progress of the task
    }

    private ArrayList<File> findFiles(File file, int page, int itemsPerPage) {
        ArrayList<File> arrayList = new ArrayList<>();
        File[] files = file.listFiles();

        if (files != null) {
            int startIndex = (page - 1) * itemsPerPage;
            int endIndex = Math.min(startIndex + itemsPerPage, files.length);

            for (int i = startIndex; i < endIndex; i++) {
                File singleFile = files[i];
                if (singleFile.isDirectory() && !singleFile.isHidden()) {
                    arrayList.add(singleFile);
                } else if (singleFile.isFile()) {
                    arrayList.add(singleFile);
                }
            }
        }
        return arrayList;
    }
}
Editor is loading...