Lesson: 15 – Store(Save) data in a text file on an SD card

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

In the previous concept, we saw how to create and read a text file in the internal memory of the Android team. In some situations, it might be useful to store the data on an SD card (keep in mind that not all Android devices have this feature) because of their increased capacity or the ease of sharing files with other people by delivering the SD card.

Issue:

Make a program that allows to enter the name of a file and the content. Allow to record the entered data at the push of a button. Provide a second button to retrieve data from the text file.

Have the files are recorded on an SD card.

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

The visual interface to implement is as follows:

Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -

We can see in the “Component Tree” window that the interface contains two EditText and two Button, the values that we should start its properties are:

  EditText of type "Plaint Text" (ID = "et1", hint = "Enter file name", text = "")
  EditText of type "Multiline Text" (ID = "et2", background = "# ff0000")
  Button (ID = "button1", text = "Save")
  Button (ID = "button2", text = "Retrieve")

The first step is to modify the AndroidManifest.xml file to allow access to the SD card from our application we do this from the Android Studio text editor

In the app / manifests folder we can open the file “AndroidManifest.xml” and add the access permission line to the external memory of the device:

Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -

We need to add the following permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Be careful that it should be outside the application element but within the element manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coding180.project018">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The source code in Kotlin is:

package com.coding180.project018


import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import java.io.*

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
        val et2 = findViewById (R.id.et2) as EditText

        val button1 = findViewById (R.id.button1) as Button
        button1.setOnClickListener {
            try {
                val card = Environment.getExternalStorageDirectory ()
                val file = File (card.getAbsolutePath(), et1.text.toString ())
                val osw = OutputStreamWriter (FileOutputStream (file))
                osw.write (et2.text.toString ())
                osw.flush ()
                osw.close ()
                Toast.makeText (this, "The data was recorded correctly", Toast.LENGTH_SHORT) .show ()
                et1.setText ("")
                et2.setText ("")
            } catch (ioe: IOException) {
                Toast.makeText (this, "Could not burn", Toast.LENGTH_SHORT) .show ()
            }
        }

        val button2 = findViewById (R.id.button2) as Button
        button2.setOnClickListener {
            val card = Environment.getExternalStorageDirectory ()
            val file = File (card.absolutePath, et1.text.toString ())
            try {
                val fIn = FileInputStream (file)
                val file = InputStreamReader (fIn)
                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) {
                Toast.makeText (this, "Could not read", Toast.LENGTH_SHORT) .show ()
            }
        }
    }
}

The method to write the data to a text file located on an SD card starts by getting the root directory of the card through the getExternalStorageDirectory () method, it returns an object of class File.

                val card = Environment.getExternalStorageDirectory ()

We create a new object of class File indicating the path of the unit SD and the name of the file to create:

                val file = File (card.getAbsolutePath (), et1.text.toString ())

Finally similar to the access of an internal file we created an object of the class OutputStreamWriter:

                val osw = OutputStreamWriter (FileOutputStream (file))

We recorded the contents of EditText:

                osw.write (et2.text.toString ())

We closed the file:

            osw.flush ();
            osw.close ();
            Toast.makeText (this, "The data was recorded correctly", Toast.LENGTH_SHORT) .show ();
            et1.setText ("");
            et2.setText ("");
        }
        catch (IOException ioe)
        {
            Toast.makeText (this, "Could not record",
                    Toast.LENGTH_SHORT) .show ();

        }
    }

To read the file again we obtain the reference of the SD card to obtain the path of the storage unit, the rest of the algorithm is similar to that seen with an internal file:

button2.setOnClickListener {
            val card = Environment.getExternalStorageDirectory ()
            val file = File (card.absolutePath, et1.text.toString ())
            try {
                val fIn = FileInputStream (file)
                val file = InputStreamReader (fIn)
                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) {
                Toast.makeText (this, "Could not read", Toast.LENGTH_SHORT) .show ()
            }
        }

….

Important.

If we try with the Nexus 5x emulator in Android Studio when we try to record it will show the notification “Could not record”, this because the cell phone does not allow to extend the memory using sd cards.

The solution to try is to create another virtual device. The steps to create another virtual device in Android Studio are as follows:

  1. From the Android Studio options menu, go to Tools-> Android-> AVD Manager.Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -
  2. A dialog appears with all the virtual machines created so far (in the early versions of Android Studio creates a virtual machine for the Nexus 5x)Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -
    Press the “Create Virtual Device” button.
  3. In this new dialog we must select that we will create a virtual device of type “Phone” and for example, we will choose a generic of 5.1 inches:Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - AVD
  4. The following dialog selects the virtual machine image that we have: 

    Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -

  5. In the new dialog we give a name to the AVD, for example: Android480x800: 

    Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -

  6. Press the “Show Advanced Settings” button.
    We have configured the SD card property with a value of 100 or more:
    Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -
    Finally we have configured our new virtual machine that allows to store data on an SD card.
    When we run a project again we have to select this new virtual machine to start:Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card - Lesson: 15 - Store(Save) data in a text file on an SD card -

 

About The Author

Related posts

Leave a Reply