Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

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: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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!