Insert and Fetch Text from a Text File in Android
A text file in Android can be used for multiple functional purposes. It can be held privately to store crucial information and sensitive data. It can also be used to store basic information which the application, in various instances, can use. As text files pose no limits on input and storage, they can serve as one of the most efficient methods of storing data.
So in this article, we will show how you could insert and fetch text from a text file in Android.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add an EditText, Two Buttons, and a TextView in the layout file. EditText will take the input string. Button 1 will save the string into a text file when triggered. Button 2 when triggered will display the text file data in the TextView.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
You can see that we are able to write and read data from the text file.