Android choose file from internal storage

In this tutorial we are going to learn about internal storage of data/files in Android App using example or you can say the primary memory of your phone. It is also important to note that the data is stored in a file specified by the user but user can not access that file, also this file can only be accessed by the application itself.

Android choose file from internal storage

Table of Contents

  • 1 Important Points About Internal Storage In Android:
  • 2 Modes of Internal Storage
  • 3 Write data to file in Internal Storage:
  • 4 Internal Storage Example In Android Studio

Important Points About Internal Storage In Android:

  • The stored data in memory is allowed to read and write files.
  • When files are stored in internal storage these file can only be accessed by the application itself not by other applications.
  • These files in storage exist till the application stays over the device, as you uninstall associated files get removed automatically.
  • The files are stored in directory data/data which is followed by the application package name.
  • User can explicitly grant the permission to other apps to access files.
  • To make the data private i.e you can use MODE_PRIVATE as discussed below about the modes.
  • Technique is best suited when data can only be access by the application neither by the user nor by other apps.
  • The data is stored in a file which contains data in bit format so it’s required to convert data before adding it to a file or before extracting from a file.

Modes of Internal Storage

MODE_PRIVATE — In private mode the data stored earlier is always overridden by the current data i.e every time you try to commit a new write to a file which removes or override the previous content. We have used MODE_PRIVATE in the example at the end of this article.
MODE_APPEND — In this mode the data is append to the existing content i.e keep adding data.


Write data to file in Internal Storage:

  • Define the filename as string and also define data you wanna write to file as string or in any format generated from app or any other source.
  • Use FileOutputStream method by creating its object as defined.
  • Convert data into byte stream before writing over file because file accepts only byte format further close the file using file object.
String File_Name= "Demo.txt"; //gives file name
String Data="Hello!!"; //define data

FileOutputStream fileobj = openFileOutput( File_Name, Context.MODE_PRIVATE);
byte[] ByteArray = Data.getBytes(); //Converts into bytes stream
fileobj.write(ByteArray); //writing to file
fileobj.close(); //File closed

Internal Storage Example In Android Studio

Below is the example to show how user can used internal memory for data storage. Here we are creating two activities, the first activity contain the form that will store data in file and second is used to load data that is saved before.

Download Code

Android choose file from internal storage

Step 1: Create a new project and name it InternalStorageDemo.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this code simply add textview , edittext and button with onclick functionality.



    

    

    

    

    

Step 3:Open src -> package -> MainActivity.java

In this step we open MainActivity and add the functions defined over button onclick i.e save or next. The save function get the data from edittext and save it in byte format inside file. Here we also used Toast to display the path where file is stored with file name. The next function uses intent to move to the next activity associated with it.

package com.example.internalstoragedemo;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    EditText editname,editpass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editname = (EditText) findViewById(R.id.editName);
        editpass= (EditText) findViewById(R.id.editPass);
    }

    public void  save(View view)  // SAVE
    {
        File file= null;
        String name = editname.getText().toString();
        String password = editpass.getText().toString();

            FileOutputStream fileOutputStream = null;
            try {
                name = name + " ";
                file = getFilesDir();
                fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
                fileOutputStream.write(name.getBytes());
                fileOutputStream.write(password.getBytes());
                Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
                editname.setText("");
                editpass.setText("");
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    public void  next( View view)   //NEXT
    {
        Toast.makeText(this,"NEXT", Toast.LENGTH_SHORT).show();
        Intent intent= new Intent(this, Main2Activity.class);
        startActivity(intent);

    }
}

Step 4: Open res -> layout -> activity_main2.xml (or) main2.xml and add following code:

In this activity the layout is just similar with the main.xml.



    

    

    

    

    

Step 5:Open src -> package -> MainActivity2.java

In this step we open MainActivity2 and add the functions defined over button’s onclick i.e load or back. The load function retrieve the data from the file, add it to the StringBuffer and further set the text over the textview’s. The  back function contain intent to move back to main activity.

package com.example.internalstoragedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;

public class Main2Activity extends AppCompatActivity {

    TextView getname, getpass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        getname = (TextView)findViewById(R.id.getname);
        getpass = (TextView)findViewById(R.id.getpass);
    }
    public void  load(View view)
    {
        try {
           FileInputStream fileInputStream =  openFileInput("Code.txt");
            int read = -1;
            StringBuffer buffer = new StringBuffer();
           while((read =fileInputStream.read())!= -1){
               buffer.append((char)read);
           }
            Log.d("Code", buffer.toString());
            String name = buffer.substring(0,buffer.indexOf(" "));
            String pass = buffer.substring(buffer.indexOf(" ")+1);
            getname.setText(name);
            getpass.setText(pass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Toast.makeText(this,"Loaded", Toast.LENGTH_SHORT).show();
    }

    public void  back( View view)
    {
        Toast.makeText(this,"Back", Toast.LENGTH_SHORT).show();
        Intent intent= new Intent(this, MainActivity.class);
        startActivity(intent);
    }
}

Output:

Now run the app and you will see login form on the screen. Add data in the fields and save it. Further click next to move to next activity and load data that is saved before.

Bonus Tip

You can view the file which contain data that you stored, if you noticed that while saving a toast appears with the path where file is stored let’s locate that file.

Important Note: The file will only be viewable if you run the App using Android Studio emulator and not in genymotion or any other external alternative emulator.

How do I navigate to storage on Android?

You can also get a quick summary of storage utilization from the Settings app, under the Storage > Manage Storage submenu. Alternatively, try using apps like DiskUsage to visualize which files and folders are taking up the most space on your device.

How do I select files from external storage on Android?

You are not getting a file, on external storage or elsewhere. You are getting a Uri ..
use ContentResolver and openInputStream() to get an InputStream on the content represented by the Uri..
create a FileOutputStream on your desired file..
use Java I/O to copy the bytes from the InputStream into the FileOutputStream..