Site icon TechVidvan

Storage in Android

android-storage

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:

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:

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:

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

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:

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.

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:

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:

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.

Exit mobile version