Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaInternal Storage in Android with Example

Internal Storage in Android with Example

The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal storage is private for an application that can not be accessed by other applications. When the app is uninstalled the data stored in the internal by that app is removed. To read and write in the android internal storage we have two methods 

  • OpenFileOutput(): used for creating and saving a file. This method returns a FileOutputStream instance.

Syntax: OpenFileOutput(String filename,int mode)

Parameters: 

mode: 

Context.MODE_PRIVATE: If the file exists then it is overridden else a new file is created. 

Context.MODE_APPEND: if the file exists then the data is appended at the end of the file.

Returns: 

FileOutputStream  object 

  • OpenFileInput(): Used to read data from a file, this returns an FileInputStream instance. 

Syntax: OpenFileInput( String filename)

Returns:

FileInputStream object 

Example

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Internal Storage in Android  Sample GIF

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

The activity_main.xml file has the following widgets 

  1. One EditText for accepting user input
  2. Two Buttons one for reading data and the other for writing
  3. One TextView to display the content of the file

Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="337dp"
        android:layout_height="28dp"
        android:text="  File Content "
        android:textAlignment="center"
        android:textColor="#000"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.52" />
 
    <Button
        android:id="@+id/write_button"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:layout_marginStart="160dp"
        android:layout_marginEnd="159dp"
        android:layout_marginBottom="16dp"
        android:text="Write"
        app:layout_constraintBottom_toTopOf="@+id/read_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.904" />
 
    <Button
        android:id="@+id/read_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:layout_marginEnd="158dp"
        android:layout_marginBottom="48dp"
        android:text="Read"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />
 
    <EditText
        android:id="@+id/userInput"
        android:layout_width="319dp"
        android:layout_height="50dp"
        android:layout_marginStart="46dp"
        android:layout_marginTop="91dp"
        android:layout_marginEnd="46dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <TextView
        android:id="@+id/content"
        android:layout_width="332dp"
        android:layout_height="306dp"
        android:layout_marginStart="33dp"
        android:layout_marginTop="21dp"
        android:layout_marginEnd="33dp"
        android:layout_marginBottom="6dp"
        android:text=""
        android:textAlignment="center"
        android:textColor="#000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.461"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.0" />
 
</androidx.constraintlayout.widget.ConstraintLayout>


Output UI:

Output UI

Step 3: Working with the MainActivity.java file

Inside the MainActivity.java file we are going to do the following things:

Initialize variables: 

Java




private String filename = "demoFile.txt";
read = findViewById(R.id.read_button);
write = findViewById(R.id.write_button);
userInput = findViewById(R.id.userInput);
fileContent = findViewById(R.id.content);


The file will be creating is DemoFile.txt. this can be found in Device File Explorer > data > data > application_package > files 

Read and Write methods:

The following method is used to read data from the internal data. 

Java




private void readData()
{
 
    try
    {
      FileInputStream fin = openFileInput(filename);
      int a;
      StringBuilder temp = new StringBuilder();
      while ((a = fin.read()) != -1)
      {
        temp.append((char)a);
      }
       
      // setting text from the file.
      fileContent.setText(temp.toString());
      fin.close();
     }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  printMessage("reading to file " + filename + " completed..");
}


The method used for creating a file and writing data to internal storage. 

Java




private void writeData()
{
    try
    {
      FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
      String data = userInput.getText().toString();
      fos.write(data.getBytes());
      fos.flush();
      fos.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    userInput.setText("");
    printMessage("writing to file " + filename + "completed...");
}


Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    // declare the variables
    Button read, write;
    EditText userInput;
    TextView fileContent;
 
    private String filename = "demoFile.txt";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        read = findViewById(R.id.read_button);
        write = findViewById(R.id.write_button);
        userInput = findViewById(R.id.userInput);
        fileContent = findViewById(R.id.content);
 
        read.setOnClickListener(this);
        write.setOnClickListener(this);
    }
 
    public void printMessage(String m) {
        Toast.makeText(this, m, Toast.LENGTH_LONG).show();
    }
 
    @Override
    public void onClick(View view) {
        Button b = (Button) view;
 
        // get the button text : in out case either read or
        // write depending on the button pressed.
        String b_text = b.getText().toString();
 
        switch (b_text.toLowerCase()) {
            case "write": {
                writeData();
                break;
            }
            case "read": {
                readData();
                break;
            }
        }
    }
 
    private void writeData() {
 
        try {
            FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
            String data = userInput.getText().toString();
            fos.write(data.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        userInput.setText("");
        printMessage("writing to file " + filename + "completed...");
    }
 
    private void readData() {
        try {
            FileInputStream fin = openFileInput(filename);
            int a;
            StringBuilder temp = new StringBuilder();
            while ((a = fin.read()) != -1) {
                temp.append((char) a);
            }
 
            // setting text from the file.
            fileContent.setText(temp.toString());
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        printMessage("reading to file " + filename + " completed..");
    }
}


Output 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments