Android Save And Load Downloading File Locally

On February 17, 2014, in Android, by James Liu

This is the session 3 of Android Wallpaper App tutorial. In my last android tutorial, I have shown an example to download images from internet. After downloading complete, I save the images into internal app folders, which can only access by this app. In most case, developers want to save the downloaded file in external storage, for example, sd card. Hence, I decide to start this topic here. In this android example, I will cover following topics:

  • How to save file in android internal temp folder?
  • How to save file in android internal app folder?
  • How to save file in external storage like sd-card?
  • How to load file from external storage like sd-card?

This example will base on my last android tutorial app, Android Wallpaper Manager app. In this app, I will download the wallpaper and save it locally. There are two purpose to saving images offline. First is caching the images locally so that it will load fast next time. Second is saving the wallpapers which users like so that they can use them as wallpaper later.

This Android Wallpaper App example includes four tutorials:

Get Cache Folder in Android

In this tutorial, I will cover both usage, saving image as cache and saving image as app data in sd-card. Let’s check following example source code first.

public File getCacheFolder(Context context) {
	File cacheDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(Environment.getExternalStorageDirectory(), "cachefolder");
            if(!cacheDir.isDirectory()) {
            	cacheDir.mkdirs();
            }
        }
        
        if(!cacheDir.isDirectory()) {
            cacheDir = context.getCacheDir(); //get system cache folder
        }
        
	return cacheDir;
}

The above example code is doing 3 things. First, it will check if your android device equips external storage such as sd-card. If it does, it will search your cache folder in sd-card path and get a file object which points to the cache folder “cachefolder” in sc-card folder. If the cache folder doesn’t exist, it will create a new folder named “cachefolder” in your sdcard. If all above jobs failed, it will get android internal cache folder. Please keep in mind, files in android internal cache folder will be deleted when the device runs low on storage. There is no guarantee when these files will be deleted. For cache usage, you’d better to look the size of your cache folder regularly and always keep your cache folder in a reasonable maximum size such as 1MB internally or 10MB externally.

Get App Data Folder in Android

The following code will show you how to get and create a app data folder in your sdcard or in android internal app data folder if sdcard is not available.

public File getDataFolder(Context context) {
	File dataDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        	dataDir = new File(Environment.getExternalStorageDirectory(), "myappdata");
            if(!dataDir.isDirectory()) {
            	dataDir.mkdirs();
            }
        }
        
        if(!dataDir.isDirectory()) {
        	dataDir = context.getFilesDir();
        }
        
	return dataDir;
}

The above code will give your a data folder in your sdcard if sdcard is available in your android device. Otherwise, it will return the path of directory holding application files. Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system.

Write File into Android Cache Folder

Now, let’s talk about how to use the above functions. First of all, I will show you how to save a file in Android cache folder. Please look the following code:

		URL wallpaperURL = new URL(wallpaperURLStr);
		URLConnection connection = wallpaperURL.openConnection();
		InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);
		File cacheDir = getCacheFolder(MainActivity.this);
		File cacheFile = new File(cacheDir, "localFileName.jpg");
		FileOutputStream outputStream = new FileOutputStream(cacheFile);
				
		byte buffer[] = new byte[1024];
		int dataSize;
		int loadedSize = 0;
	        while ((dataSize = inputStream.read(buffer)) != -1) {
	            loadedSize += dataSize;
	            publishProgress(loadedSize);
	            outputStream.write(buffer, 0, dataSize);
	        }
	            
	        outputStream.close();

Above code is an example code from my Android Wallpaper app. It downloads a image from internet and save it in android cache folder. If you want to save the image as Android App data, please replace function getCacheFolder with getDataFolder.

Load File from Android Cache Folder

Now you know how to save the file in android locally. I will show you how to load file from android internal storage or from android sdcard. Still, I will use my app example code. The following code will load a image from Android sdcard and show it in an Imageview.

File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
ImageView imageView = (ImageView)this.findViewById(R.id.preview);
imageView.setImageBitmap(wallpaperBitmap);

Try Example Android App

You can download and install this android app by click the following link, or scan the following QR code to download and install on your android phone simply. If you feel it is helpful, please support me by clicking the banner inside the app.
Download and Run This Example on Your Android Phone

chart

Get Full Source Code at $4.99


You will get whole source code at $4.99 in version 1.2. It is fully functional, and embedded the Google AdMob module by default. With this source code, you can do everything you want:

  • Load your own images;
  • Monetize the app with your own AdMob publish id;
  • Use the source code in your own project;
  • Publish this app with your Google Play account;
Tagged with:  

6 Responses to “Android Save And Load Downloading File Locally”

  1. gokul says:

    how can i apply to custom list view?each image ll have differnet url.

  2. Tom says:

    Hello – Can you explain, why you use in the following code line the value 10240 ?

    InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);

    Size size of the buffer array is 1024.

    BR

  3. Bhargav says:

    Hello,

    I trying to download a pdf file on button click in my application. So can u give me suggestion which server is best to use…? Thanks in advance.

Leave a Reply

Premium WordPress Themes

WordPress Blog