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();