Insert and Fetch Text from a Text File in Android
Last Updated :
27 Sep, 2021
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.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="50sp"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/edit_text"
android:text="Save"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/button1"
android:text="Show"/>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/button2"/>
</RelativeLayout>
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.
Kotlin
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.Exception
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declaring EditText, Buttons and TextViews from the layout file
val mEditText = findViewById<EditText>(R.id.edit_text)
val mButtonSave = findViewById<Button>(R.id.button1)
val mButtonShow = findViewById<Button>(R.id.button2)
val mTextView = findViewById<TextView>(R.id.text_view)
// What happens when Save Button is pressed
mButtonSave.setOnClickListener {
if(mEditText.text.toString().isNotEmpty()){
// For First time: Creates a text file and writes string into it
// Else: Opens the text file and writes the string
try {
val fileOutputStream = openFileOutput("mytextfile.txt", Context.MODE_PRIVATE)
val outputWriter = OutputStreamWriter(fileOutputStream)
outputWriter.write(mEditText.text.toString())
outputWriter.close()
Toast.makeText(baseContext, "File saved successfully!", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
}
} else {
Toast.makeText(applicationContext, "No input?", Toast.LENGTH_SHORT).show()
}
}
// What happens when show button is pressed
mButtonShow.setOnClickListener {
// Tries to fetch data from the text file
try {
val fileInputStream = openFileInput("mytextfile.txt")
val inputReader = InputStreamReader(fileInputStream)
val output = inputReader.readText()
// Data is displayed in the TextView
mTextView.text = output
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
Output:
You can see that we are able to write and read data from the text file.
Similar Reads
How to Read a Text File in Android? A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing o
3 min read
How to Fetch Audio file From Storage in Android? Selecting an audio file from the phone's storage is required when the user is uploading or sending an audio file in your application. So this article primarily focuses on getting the audio files as a URI from your phone's storage. Step by Step Implementation Step 1: Create a New Project To create a
2 min read
How to Read a File in Android? In android development, data are presents in a form of files, shared preferences, and databases. We have data in different format according to task our app need to do. In the case of a video player or music player app, we have data store in files and how to read those files in Android we learn in th
2 min read
Fetch Text From Editable TextField in Android Jetpack Compose In Android, an EditText is a sub-class of TextView, a UI element used to take text input from the user. EditText is generally used to collect information from the user for storing details or giving inputs for performing a function. However, in Jetpack Compose, we have TextField to collect and displa
3 min read
How to Create Text Stickers in Android? Not only a picture is worth a thousand words but also, they are cooler than monotonous text. In this article, we will learn how to create stickers from the TextView. This will be helpful if you are creating an app in which you want to add some text overlay functionality, for example, an image editin
9 min read
Android - Center Text in a TextView Horizontally and Vertically Many android applications use text view for displaying text within android applications. There are different ways used to align the text view within our XML layout. To align TextView for different screen sizes we cannot use margin from all sides. For aligning the text view for different screen sizes
2 min read
How to Add Hyperlink to TextView in Android? Hello geeks, today we are going to make an application where we will see that how we can add a link to a TextView in Android, and using this concept we will add portals - home and practice (of GeeksforGeeks) in our application. So that, user can directly go to these portals from our application. Wha
3 min read
How to Extract Data from PDF file in Android? PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the
4 min read
How to Make TextView and EditText Selectable in Android? In this article, we are going to implement a very important feature related to TextView. While using any social media app or like using Facebook you may have seen there is a particular type of TextView which you cannot copy like a caption that people write on their posts. You can select the message
3 min read
How to Combine Text and Image on a Button or ImageButton in Android? Image Buttons are used in many android applications for performing some actions. Some of the users of mobile applications sometimes are not aware of the images which are present on that specific buttons. So for informing the user about that button we also add a simple text to our button so that the
4 min read