Search code examples
javaandroidsharedpreferencesinputstreamfileoutputstream

Save Media Files to SharedPreferences/Files Android


I want to download and save a .ttf or .otf file for custom fonts in my Android App. Is it possible to save this in SharedPreferences?

Not the file path, but the file itself.

Edit: I asked for this method because OutputStream kept giving me 'Permission Denied' error. I am open to any suggestion that would help me save the downloaded .ttf to files and retrieve it later.

Thanks!

Edit: I have added the Input Output Stream code below, which gives me a permission denied error when running. Please let me know if I can fix something here.

class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int lenghtOfFile = connection.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream(), 8192);
        File file = new File(Environment.getExternalStorageDirectory(), "downloadedFont.ttf");
        OutputStream output = new FileOutputStream(file);

        byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();

    } catch (Exception e) {
        Log.e("Error", e.getMessage() + e.getCause());
    }
    return null;
}

@Override
protected void onPostExecute(String file_url) {
    loadFont();
}

public static void loadFont() {
    File file = new File(Environment.getExternalStorageDirectory().toString() + "/downloadedFont.ttf");
    if(file.exists()){
        Log.d("LOAD", "File exists");
        Typeface typeFace = Typeface.createFromFile(file);
        ContextHelper.setDownloadedFontType(typeFace);
    }
    else {
        download();
    }
}

public static void download() {
    Log.d("DOWNLOAD", "In the download.");
    new DownloadFileFromURL().execute("https://www.dropbox.com/s/y980vywiprd8eci/riesling.ttf?raw=1");
}
}

The following is how the method is called in an Activity.

DownloadFileFromURL.loadFont();

Solution

  • After much searching, I found the answer in the depths of StackOverflow:

    public static void downloadFont(String url, Context context) {
        DownloadManager.Request request1 = new DownloadManager.Request(Uri.parse(url));
        request1.setDescription("Sample Font File");
        request1.setTitle("Font.ttf");
        request1.setVisibleInDownloadsUi(false);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request1.allowScanningByMediaScanner();
            request1.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        }
        request1.setDestinationInExternalFilesDir(context, "/File", "Font.ttf");
    
        DownloadManager manager1 = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Objects.requireNonNull(manager1).enqueue(request1);
    
        if (DownloadManager.STATUS_SUCCESSFUL == 8) {
            File file = new File(context.getExternalFilesDir("/File").toString() + "/Font.ttf");
            if(file.exists()){
                Typeface typeFace = Typeface.createFromFile(file);
            }
        }
    }
    

    Many thanks to this answer which helped solve my problem so concisely.