Android File Loading – Load File locally or from network

Best File Loader Libraries for Android

In this lesson we will look at several options of loading a file in android. This can be important if you want to process or extract some data from a file. For example, rather than storing simple texts in a database, you may store them in a text file, then asynchronously load that file from a network or locally and extract that data and render it in your app.

The files can be loaded synchronously or asynchronously. Unless the file is super-tiny, you should always prefer asynchronous loading as it doesn’t block the user interface.

(a). Solution 1: Use File Loader library

This is a beautiful library that allows us load files asynchronously and synchronously. When loading the file from the network, you have the option of using a cached one or forcing download from the network. This may be important in scenarios where you want to load only from the network if a local copy does not exist.

This library is described as "Android library for downloading, saving/caching and retrieving any type of files ( image, video, pdf, apk etc ) easily."

Here are examples:

How to Asynchronously load a file generically

FileLoader.with(this)
                .load("https://upload.wikimedia.org/wikipedia/commons/3/3c/Enrique_Simonet_-_Marina_veneciana_6MB.jpg",false) //2nd parameter is optioal, pass true to force load from network
                .fromDirectory("test4", FileLoader.DIR_INTERNAL)
                .asFile(new FileRequestListener<File>() {
                    @Override
                    public void onLoad(FileLoadRequest request, FileResponse<File> response) {
                        File loadedFile = response.getBody();
                        // do something with the file
                    }

                    @Override
                    public void onError(FileLoadRequest request, Throwable t) {
                    }
                });

How to load file as an Object

FileLoader.with(this)
                .load("http://echo.jsontest.com/key1/value1/key2/value2")
                .fromDirectory("test3", FileLoader.DIR_INTERNAL)
                .asObject(new FileRequestListener<JsonTest>() {
                    @Override
                    public void onLoad(FileLoadRequest request, FileResponse<JsonTest> response) {
                        JsonTest jsonTest = response.getBody();
                        //do something with jsonTest object
                    }

                    @Override
                    public void onError(FileLoadRequest request, Throwable t) {

                    }
                });

How to Load Multiple Files

You can load multiple files while handling progress states. Here is how you can upload from the same directory:

final String[] uris = {"https://images.pexels.com/photos/45170/kittens-cat-cat-puppy-rush-45170.jpeg",
                "https://upload.wikimedia.org/wikipedia/commons/3/3c/Enrique_Simonet_-_Marina_veneciana_6MB.jpg",
                "https://d15shllkswkct0.cloudfront.net/wp-content/blogs.dir/1/files/2017/01/Google-acquires-Fabric.png"};

FileLoader.multiFileDownload(this)
                .fromDirectory(Environment.DIRECTORY_PICTURES, FileLoader.DIR_EXTERNAL_PUBLIC)
                .progressListener(new MultiFileDownloadListener() {
                    @Override
                    public void onProgress(File downloadedFile, int progress, int totalFiles) {
                    }

                    @Override
                    public void onError(Exception e, int progress) {
                        super.onError(e, progress);
                    }
                }).loadMultiple(uris);

And here is how you can load from different directories:

List<MultiFileLoadRequest> multiFileLoadRequests = new ArrayList<>();
        multiFileLoadRequests.add(new MultiFileLoadRequest(uris[0], "test2", FileLoader.DIR_INTERNAL, false));
        multiFileLoadRequests.add(new MultiFileLoadRequest(uris[1], Environment.DIRECTORY_DOWNLOADS, FileLoader.DIR_EXTERNAL_PRIVATE, false));
        multiFileLoadRequests.add(new MultiFileLoadRequest(uris[2], Environment.DIRECTORY_PICTURES, FileLoader.DIR_EXTERNAL_PUBLIC, false));

MultiFileDownloader multiFileDownloader = FileLoader.multiFileDownload(this);
multiFileDownloader.progressListener(new MultiFileDownloadListener() {
            @Override
            public void onProgress(File downloadedFile, int progress, int totalFiles) {

            }

            @Override
            public void onError(Exception e, int progress) {
                super.onError(e, progress);
            }
        }).loadMultiple(true, uris);

How to cancel loading

multiFileDownloader.cancelLoad();

Deleting Files

How to Delete Files

You can also delete multiple files:

final String[] uris = {"https://images.pexels.com/photos/45170/kittens-cat-cat-puppy-rush-45170.jpeg",
                "https://upload.wikimedia.org/wikipedia/commons/3/3c/Enrique_Simonet_-_Marina_veneciana_6MB.jpg",
                "https://d15shllkswkct0.cloudfront.net/wp-content/blogs.dir/1/files/2017/01/Google-acquires-Fabric.png"};
try {
      FileLoader.deleteWith(this).fromDirectory("test2", FileLoader.DIR_INTERNAL).deleteFiles(uris);
    } catch (Exception e) {
      e.printStackTrace();
    }

To delete all files of a given directory:

FileLoader.deleteWith(this).fromDirectory("test2", FileLoader.DIR_INTERNAL).deleteAllFiles();

To delete all files except the specified ones:

FileLoader.deleteWith(this).fromDirectory("test3", FileLoader.DIR_INTERNAL).deleteAllFilesExcept(uris);

Installation

To install file loader:

repositories {
    mavenCentral()
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'com.github.kk121:File-Loader:1.2'
}

Find more info here.

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code