Storage in Android

In this article, we will discuss storage in Android. For any android developer, it’s essential to understand the storage and how they can manage it. When you develop an application, then you need a place where you can store application data.

Android provides you several ways to store data, and we will cover most of them through this article. You will see what is internal and external storage in android and what role they play.

Storage in Android

Storage is quite vital for any application. Just imagine you entered some details about yourself in the application. You now closed the application, and when you start it back, you see that the app again asks you the information. If you are a user of this kind of application, you will be irritated by the continuous seeking of details.

Another ubiquitous example is your contacts application. Whenever you get a new contact and save it on your device, it remains saved until you delete it. This becomes very important because we can’t remember all contacts every time.

Therefore, storage is quite crucial while developing any application.

So, now comes the thing that all storage and android provide to us. The storage can generally be application-specific, shared storage, scoped storage, android preferences, or databases. Let’s figure out what each of them is.

1. Application-Specific Android Storage

Application-Specific Android Storage, as the name suggests, is storage-specific to a particular application. In other words, the storage can only be accessed by that application itself, and no other application can access that data storage.

This storage is quite feasible when you wish to secure your application and don’t let other apps access this app data.

Now comes how we can implement Application-Specific Android storage. To implement this, you need to create a directory in your internal or external storage.

a. You need to first access the internal and external storage. You can use the below methods to access:

  • Internal Storage – getFilesDir() or getCacheDir()
  • External Storage – getExternalFilesDir() or getExternalCacherDir()

b. From Android 4.4 (or later), you don’t require user permissions to write or read your application’s data in internal and external storage. However, rules have changed with the coming of Android 11.

c. When the app uses internal storage to store its data, then other applications can’t access it. Whereas if data is stored in external storage, then other applications can access it.

d. When the app gets uninstalled, then the data is also deleted from the storage.

Note: With Android 11 (API level 30), external storage access has been restricted a lot. To ensure the security and privacy of user data Android 11 refrains from providing direct access to external storage to the application.

However, if your target SDK is Android 10 (API Level 29), you can still access external storage using the requestLegacyExternalStorage attribute.

2. Shared Storage in Android

As the name suggests, Shared Storage intends to store data that can be used by several other applications as well. For example, how applications like Instagram, Whatsapp, etc., can access your gallery data.
Usually, this kind of storage is used for data like images, videos, audio, documents, etc.
Let’s see few critical points about shared storage:

  • To access any kind of multimedia data, you can use MediaStore API and Storage Access Framework.
  • To read any kind of multimedia data or documents, you need to acquire two permissions: READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE (Android 10 or later)
  • If you uninstall the app, the data remains there and is not deleted.

3. Scoped Storage in Android

Scoped-Storage is a new kind of storage that is introduced from Android 10. Scoped-Storage gives more control to the user on the application’s data. In other words, the application now doesn’t require any permission to access the data that falls in its scope.

For example, if you created a multimedia application, then the application doesn’t require any permission to access the multimedia files your app built.

Let’s understand few critical points of scoped storage:

  • Scoped-Storage is a new storage technique that is made available from Android 10 onwards.
  • However, if your app wishes to use scoped storage and is below Android 10, it can do so by using the following. You need to set the below flag as true in your Manifest File.

a. DEFAULT_SCOPED_STORAGE (enabled for all apps by default)
b. FORCE_ENABLE_SCOPED_STORAGE (disabled for all apps by default)

  • Apps have access to only app-specific directories on the external storage.

4. Android Preferences

Android Preferences allows storing data in a private database that is restricted to the app itself. It stores data in key-value pairs and is usually used to store small textual data. Following are some of the critical points of Android Preferences:

  • Data is stored in a key-value pair
  • Requires the JetPack Preferences library to access
  • Data access is limited to the app itself, and other applications can’t access it
  • Data in the android preferences are removed when you uninstall the app or clear app data

5. Databases in Android

Databases in android allow you to store extensive data in a structured manner. For this, the android uses the Room Persistence Library. Let’s summarize a few key points about databases in android.

  • Data stored in a structured manner in the database
  • To access any data from the database, we use Room Persistence Library
  • Other applications are restricted to access the data
  • After the uninstallation, the information is also deleted from the database
  • We have SQLite, a well-known database used in Android

Apart from the above storage types, you can also have network storage to store your data on some online databases. Those kinds of storage require the internet connection of your device to be always active.

Internal Storage in Android

Internal Storage is the storage that comes along with your device. It is usually non-removable. The files stored in internal storage are by default private for other applications. In other words, if your application stores its data in internal storage, then other applications can’t access it.

Let’s see how you can write files to internal storage in android:

  • You need to import the FileOutputStream class into your project.
  • Now call the openFileOutput( ) method with the proper file name and mode.
  • Call the write( ) method to write the contents in the file
  • After the file writing is completed then call the close( ) method to close the file.

For example,

val fileName = "YOUR_FILE_NAME"
       val data = "Mohit"
       val fileOutputStreamObj:FileOutputStream
       try {
           fileOutputStreamObj = openFileOutput(fileName, Context.MODE_PRIVATE)
           fileOutputStreamObj.write(data.toByteArray())
       }
       catch (e: Exception)
       {
           e.printStackTrace()
       }

Some of the highly used methods of FileOutputStream class are as follows:

Method Name Description
FileOutputStream(file : File,  append : Boolean) It creates a new FileOutputStream with a file to write upon.
getChannel() The getChannel() method provides a write-only FileChannel that shares its position with this stream
getFD() The getFD() method is to retrieve the underlying file descriptor
write() The write() method is used to write buffers to the actual file.

Let’s see how you can read files from internal storage in android:

  • You need to import the FileInputStream class into your project.
  • Now call the openFileInput( ) method with the proper file name and mode.
  • Call the read( ) method to read the contents in the file
  • After the file reading is completed then call the close( ) method to close the file.

Code:

var fileInputStreamObj: FileInputStream? = null
fileInputStreamObj = openFileInput("YOUR_FILE_NAME")
var inputStreamReaderObj: InputStreamReader =  InputStreamReader(fileInputStreamObj)

 val bufferedReaderObj: BufferedReader = BufferedReader(inputStreamReaderObj)
 val stringBuilder: StringBuilder = StringBuilder()
 var eachText: String? = null

 while ({ eachText = bufferedReader.readLine(); eachText }() != null) {
           stringBuilder.append(eachText)
       }
       
       Log.d("Output", stringBuilder.toString())

Some of the highly used methods of FileInputStream class are as follows:

Method Name Description
available() It gives a count of the number of bytes that can be read or skipped from a file
getChannel() The getChannel() method provides a write-only FileChannel that shares its position with this stream
getFD() The getFD() method is to retrieve the underlying file descriptor
read() The read() method reads the bytes from the file and stores them in a byte array starting at offset.

External Storage in Android

External storage is also used to store files by android. The external storage is removable and expandable. The data stored in external storage is public, and other applications can easily access them if they have read-write permissions on the external storage.

Reading Files from an External Storage:

1. To open a specific file in the external storage, you need to use the getExternalFilesDir( ) method.

2. The getExternalFilesDir( ) takes the parameter as a subdirectory, for example, DIRECTORY_ALARMS, DIRECTORY_MUSIC, etc. If we pass it as null, then we get the root directory

3. For API level 7 or lower, you can use getExternalStorageDirectory() to access the root directory of your external storage.

4. If you wish to write application data, you should do it in the following path.

/Android/data/YOUR_PACKAGE_NAME/files/

The package name is the name of your project package. For instance, in our case, it is ‘com.techvidvan.myapplication’.

Saving files to External Storage

1. Saving files like music, images, videos, documents, etc., are one of the necessary external storage needs. Sometimes internal storage is not sufficient for all of these, so you require external storage to store all these.

2. To store these files, you need to use public directories like Music/, Movies/, Pictures/, Download/.

3. For API Level 8 or later, you need to call the getExternalStoragePublicDirectory() to access the public directory you want. This method can also create a new directory if required.

4. For API Level 7 or below, you need to call the getExternalStorageDirectory() to access the root of your external storage. After getting the root directory, you can access the public directory of your choice.

5. After getting access to the desired directory, you can simply save the file.

Summary

Through this article, you came across storage in android. You saw why storage is so essential in android and came across several storage techniques. You saw each storing pattern’s critical points and came across the changes with the updates in android. Later on, you saw internal and external storage and understood the use of each of them. Along with this, you also saw how you could perform read/write operations on internal and external storage.