Lesson 14 – Storing data in a text file in the internal memory

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

Another possibility of storing data on our Android device is the use of a text file that will be stored in the internal storage of the computer (the other possibility is to store it on an SD Card)

Problem 1:

Create a program that allows you to store notes in an EditText control and when you press a button, store the EditText data in a text file called “notes.txt“.
Each time you enter the program check if there is the text file “notes.txt“, proceed to read and store data in the EditText.

Create a project in Android Studio and define it as name: Project016.

To create the visual interface first we have a button at the bottom of the cell and then the “Text” tab select an object from the EditText class (“Multiline Text”) and we have it at the top of the screen:

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

Starting with version 2.3.0 of Android Studio, the properties of each object appear the most used in the main screen. If we want to see all the properties that the object has, we must select the option “View all properties” that appears at the bottom of the properties window.

Once all the properties appear we initialize the background property of the EditText with the value #ffff00 (corresponding to the yellow color):

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

Finally, we proceed to resize the EditText by means of the mouse and set the gravity property by ticking the top and left values so that the data entered by the operator appear in the upper left and not centered:

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

We can see the simplified properties window again by pressing the two arrows icon at the top right of the properties window.

The source code in Kotlin’s application:

package com.coding180.project016

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import java.io.BufferedReader
import java.io.IOException
import java.io .InputStreamReader
import android.widget.Toast
import android.app.Activity
import java.io.OutputStreamWriter

class MainActivity: AppCompatActivity () {

    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
// coding180.com
        val et1 = findViewById (R.id.et1) as EditText

        if(fileList().contains("notes.txt")) {
            try {
                val file = InputStreamReader(openFileInput("notes.txt"))
                val br = BufferedReader(file)
                var line = br.readLine()
                val all = StringBuilder()
                while (line != null) {
                    all.append(line + "\n")
                    line = br.readLine()
                }
                br.close()
                file.close()
                et1.setText(all)
            }
                catch (e:IOException) {
                }
            }

            val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
                try {
                    val file = OutputStreamWriter(openFileOutput("notes.txt", Activity.MODE_PRIVATE))

                    file.write (et1.text.toString())
                    file.flush ()
                    file.close ()
                } catch (e : IOException) {
                }
                Toast.makeText(this, "data were recorded", Toast.LENGTH_SHORT).show()
                finish ()

            }
    }
}

Let’s first look at how we write data to a text file. This is done in the lambda function that we passed to the setOnClickListener method of button1:

Within a try catch block we create an object from the OutputStreamWriter class and pass it the data that the openFileOutput function returns (this function is named after the text file to be created):

        Botton1.setOnClickListener {
            Try {
                Val file = OutputStreamWriter (openFileOutput ("notes.txt", Activity.MODE_PRIVATE))

We recorded in the text file the contents of et1, confirmed the recording by calling the flush method and finally closed the text file created:

                File.write (et1.text.toString ())
                File.flush ()
                File.close ()
            } Catch (e: IOException) {
            }

We ended the program by showing a message that the data was recorded:

            Toast.makeText (this, "The data was recorded", Toast.LENGTH_SHORT) .show ()
            Finish ()

On the other hand, every time the program starts, we check if the text file “notes.txt” exists by calling the fileList () method that returns an object of the List class with all the text files in the application, and from From this list we call the contains method that returns true if there is the file name that we passed as reference:

        If (fileList (). Contains ("notes.txt")) {

In the case that the file exists we proceed to open it to read by creating an object of class InputStreamReader:

            Try {
                Val file = InputStreamReader (openFileInput ("notes.txt"))

We create an object of class BufferedReader to make the reading of the file more efficient:

                Val br = BufferedReader (file)

Then inside a repetitive structure we proceed to read each line of the text file and save the data in memory in an object of class StringBulder:

                Var line = br.readLine ()
                Val all = StringBuilder ()
                While (line! = Null) {
                    Todo.append (line + "\ n")
                    Line = br.readLine ()
                }
                Br.close ()
                File.close ()

We show the data retrieved from the file in EditText:

                Et1.setText (all)
            } Catch (e: IOException) {
            }

Each time we run the program we will see the last saved notes:

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

Problem 2:

Make a program to manage a calendar of daily activities. The file names will correspond to the dates we entered. Then when we query a date we check if there is a text file that matches that date.

Create a project in Android Studio and define it as name: Project017.

The visual interface to create will be as follows:

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

That is to say we have a “TextView” where it says date. An EditText of type “Date” where the date is loaded. Then another EditText of type “Multiline Text” and finally two buttons:

  TextView (ID = "tv1" text = "Date")
  EditText of type "Date" (ID = "et1", hint = "Enter date")
  Button (text = "Record", ID = "button1")
  Button (text = "Retrieve" ID = "button2")
  EditText of type "Multiline Text" (id = "et2", background = "#ffff00")

The source code of the application:

package com.coding180.project017


import android.app.Activity
import android.support.v7.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.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter

class MainActivity: AppCompatActivity () {
// coding180.c0m
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)

        val et1 = findViewById (R.id.et1) as EditText
        val et2 = findViewById (R.id.et2) as EditText
        val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
            val filename = et1.text.toString (). replace ('/', '-')
            try {
                val file = OutputStreamWriter (openFileOutput (filename, Activity.MODE_PRIVATE))
                file.write (et2.text.toString ())
                file.flush ()
                file.close ()
            } catch (e: IOException) {
            }
            Toast.makeText (this, "The data was recorded", Toast.LENGTH_SHORT) .show ()
            et1.setText ("")
            et2.setText ("")
        }

        val button2 = findViewById (R.id.button2) as Button
        button2.setOnClickListener {
            var filename = et1.text.toString (). replace ('/', '-')
            if (fileList (). contains (filename)) {
                try {
                    val file = InputStreamReader (openFileInput (filename))
                    val br = BufferedReader (file)
                    var line = br.readLine ()
                    val all = StringBuilder ()
                    while (line!= null) {
                        all.append (line + "\n")
                        line = br.readLine ()
                    }
                    br.close ()
                    file.close ()
                    et2.setText (all)
                } catch (e: IOException) {
                }
            } else {
                Toast.makeText (this, "No data recorded for that date", Toast.LENGTH_LONG) .show ()
                et2.setText ("")
            }
        }
    }
}

The lambda function that is executed when we press the button 1 first has to extract the date entered in the first EditText and replace the bars of the date by scripts since this character can not be used within a filename in Android:

        button1.setOnClickListener {
            Val filename = et1.text.toString (). Replace ('/', '-')

We create an object of the class OutputStreamWriter and the constructor of this class we send the data that returns the own openFileOutput method of the class AppCompatActivity that we passed as parameter the name of the text file and the opening mode.

            Try {
                Val file = OutputStreamWriter (openFileOutput (filename, Activity.MODE_PRIVATE))

Then if the file was created correctly we proceed to call the write method and we pass the String to record, in this case, we extract the data from EditText:

                File.write (et2.text.toString ())

After writing with the write method we call the flush method to flip all the data that may have been left in the buffer and proceed to the closed of the file:

                File.flush ()
                File.close ()

Each time you record a data is generated a text file for that date, if there was already a file with the same name (ie the same date) the previous one is pressed.

To recover the data of a certain date the lambda function is executed that we pass to button 2:

val button2 = findViewById (R.id.button2) as Button
        button2.setOnClickListener {
            var filename = et1.text.toString (). replace ('/', '-')
            if (fileList (). contains (filename)) {
                try {
                    val file = InputStreamReader (openFileInput (filename))
                    val br = BufferedReader (file)
                    var line = br.readLine ()
                    val all = StringBuilder ()
                    while (line!= null) {
                        all.append (line + "\n")
                        line = br.readLine ()
                    }
                    br.close ()
                    file.close ()
                    et2.setText (all)
                } catch (e: IOException) {
                }
            } else {
                Toast.makeText (this, "No data recorded for that date", Toast.LENGTH_LONG) .show ()
                et2.setText ("")
            }
        }
    }
}

The first thing we do is to retrieve from EditText the date entered by the operator to search for and replace the bars by hyphens (remember that we recorded scripts in the load since the bar of a date is not a valid character in a file on Android):

            Var filename = et1.text.toString (). Replace ('/', '-')

We check if there is a file with this date:

            If (fileList (). Contains (filename)) {

If the file exists we proceed to open it, read it and load the et2 with the file data:

                Try {
                    Val file = InputStreamReader (openFileInput (filename))
                    Val br = BufferedReader (file)
                    Var line = br.readLine ()
                    Val all = StringBuilder ()
                    While (line! = Null) {
                        Todo.append (line + "\ n")
                        Line = br.readLine ()
                    }
                    Br.close ()
                    File.close ()
                    Et2.setText (all)
                } Catch (e: IOException) {
                }

The runtime visual interface should be similar to this:

 

Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory - Lesson 14 - Storing data in a text file in the internal memory -

About The Author

Related posts

Leave a Reply