How to effectively store data in Android app development is very important. User data should be stored securely and should be easy to manage. In this course, we will learn how to store and manage data in Android through the file system using Kotlin. This article will cover internal storage, external storage, and file input/output (I/O) in depth.
1. Overview of the Android File System
Android has two main storage options: internal storage and external storage. Each storage type differs in terms of access methods and the persistence of stored data.
1.1 Internal Storage
Internal storage is an application-specific area that cannot be accessed by other applications. Data stored here is deleted when the application is uninstalled. Internal storage is suitable for storing sensitive data.
1.2 External Storage
External storage is accessible by general users, not just the application. This typically includes external memory devices like SD cards. Data stored in external storage remains even if the application is deleted. Therefore, it is suitable for storing public data that can be shared with users.
2. Basics of File Input/Output (I/O)
File input/output (Files I/O) allows you to set up processes for reading and writing data. To access the Android file system in Kotlin, you need to perform the following tasks:
- Create and write files
- Read files
- Delete files
2.1 Writing Files
First, let’s look at an example of code to write a file to internal storage.
fun writeToFile(filename: String, data: String) {
// Write file to internal storage
context.openFileOutput(filename, Context.MODE_PRIVATE).use { output ->
output.write(data.toByteArray())
}
}
The above function takes the file name and data as parameters and writes that data to a file in internal storage.
2.2 Reading Files
Now let’s see how to read the file we wrote.
fun readFromFile(filename: String): String {
// Read file from internal storage
return context.openFileInput(filename).bufferedReader().use { it.readText() }
}
This function takes the file name as a parameter and returns the contents of the file as a string.
2.3 Deleting Files
Now let’s learn how to delete a specific file. You can delete a file by passing its name as a parameter.
fun deleteFile(filename: String) {
context.deleteFile(filename)
}
3. Saving Files to External Storage
Now let’s see how to save files to external storage. To access external storage, you must set the appropriate permissions. Below is an example code for saving a file to external storage.
3.1 Requesting Permissions
To write data to external storage, the WRITE_EXTERNAL_STORAGE
permission is required. Therefore, you need to add the following code to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3.2 Writing Files
Below is how to write a file to external storage.
fun writeToExternalFile(filename: String, data: String) {
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val file = File(directory, filename)
file.writeText(data)
}
This code is an example of writing a file to the user’s documents directory.
3.3 Reading Files
The code to read a file from external storage is as follows.
fun readFromExternalFile(filename: String): String {
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val file = File(directory, filename)
return file.readText()
}
3.4 Deleting Files
Here’s how to delete a file from external storage.
fun deleteExternalFile(filename: String) {
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val file = File(directory, filename)
if (file.exists()) {
file.delete()
}
}
4. Example App Project
Now, let’s create a simple Android app using all the above code. We will build an app that allows users to input text and write, read, and delete it from both internal and external storage.
4.1 Setting Up the Android Studio Project
Open Android Studio and create a new project. Choose an appropriate package name and minimum SDK.
4.2 Designing the UI
Open the activity_main.xml file and set up the UI as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input data"/>
<Button
android:id="@+id/btnSaveInternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save to Internal Storage"/>
<Button
android:id="@+id/btnSaveExternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save to External Storage"/>
<Button
android:id="@+id/btnReadInternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read from Internal Storage"/>
<Button
android:id="@+id/btnReadExternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read from External Storage"/>
<Button
android:id="@+id/btnDeleteInternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Internal Storage File"/>
<Button
android:id="@+id/btnDeleteExternal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete External Storage File"/>
<TextView
android:id="@+id/textViewOutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result Output"/>
</LinearLayout>
4.3 Adding Code to MainActivity.kt
Now let’s add the following code to the MainActivity.kt file to manage button click events and handle file I/O operations.
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
private lateinit var textViewOutput: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText = findViewById(R.id.editText)
textViewOutput = findViewById(R.id.textViewOutput)
findViewById
5. Conclusion
Through this course, we have learned how to use the file system in Android. We acquired basic skills to store and read data via internal and external storage, and implement this using Kotlin. These features will significantly help you in managing user data securely in your apps. The next step is to explore more complex data storage methods such as databases.
6. Learn More
Look for additional resources on Android and Kotlin and experiment with more examples. This will enhance your understanding of Android app development and help you address more complex data management issues.