Android File Loading – Load File locally or from network

0
User Management System
Learn Kotlin, Retrofit, MVVM and MySQL using this all-in-one app. It is designed to be beginner friendly.

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.

Android MySQL Retrofit2 Multipart CRUD,Search,Pagination rating

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com . Follow me below; Github , and on my channel: ProgrammingWizards TV

We will be happy to hear your thoughts

Leave a reply

fifty four − = forty four

Reset Password
Compare items
  • Total (0)
Compare
0
Shopping cart