Blog Archive

Android Internal and External storage example - Store and Retrieve Data

  • Android Internal Storage 
    • Internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed. 
  • Android External Storage
    •  External storage such as SD card can also store application data, there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them. 

In this example we are going to save data from an EditText to both Internal Storage and External Storage, and then try to get the data back from the respective storage places.

android internal external storage example android internal storage example android external storage example

Source for the Screen Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 android:orientation="vertical">

 <TextView android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:text="@string/hello" />
 
 <EditText android:id="@+id/myInputText" 
     android:layout_width="match_parent"
  android:layout_height="wrap_content" 
  android:ems="10" android:lines="5"
  android:minLines="3" android:gravity="top|left" 
  android:inputType="textMultiLine">

  <requestFocus />
 </EditText>
 
 <Button android:id="@+id/saveInternalStorage"
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"
  android:text="Save to Internal Storage" />

 <Button android:id="@+id/getInternalStorage"
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"
  android:text="Display from Internal Storage" />
 
 <Button android:id="@+id/saveExternalStorage"
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"
  android:text="Save to External Storage" />
 
 <Button android:id="@+id/getExternalStorage"
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"
  android:text="Display from External Storage" />
 
 <TextView android:id="@+id/responseText" 
     android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:padding="5dp"
  android:text="" 
  android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Source for the Activity - AndroidStorageActivity.java

package com.as400samplecode;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidStorageActivity extends Activity implements OnClickListener{

 private String filename = "MySampleFile.txt";
 private String filepath = "MyFileStorage";
 File myInternalFile;
 File myExternalFile;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
  File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
  myInternalFile = new File(directory , filename);

  Button saveToInternalStorage = 
   (Button) findViewById(R.id.saveInternalStorage);
  saveToInternalStorage.setOnClickListener(this);

  Button readFromInternalStorage = 
   (Button) findViewById(R.id.getInternalStorage);
  readFromInternalStorage.setOnClickListener(this);

  Button saveToExternalStorage = 
   (Button) findViewById(R.id.saveExternalStorage);
  saveToExternalStorage.setOnClickListener(this);

  Button readFromExternalStorage = 
   (Button) findViewById(R.id.getExternalStorage);
  readFromExternalStorage.setOnClickListener(this);

  //check if external storage is available and not read only  
  if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  
   saveToExternalStorage.setEnabled(false);
  } 
  else {
   myExternalFile = new File(getExternalFilesDir(filepath), filename);
  }

 }

 public void onClick(View v) {

  EditText myInputText = (EditText) findViewById(R.id.myInputText);
  TextView responseText = (TextView) findViewById(R.id.responseText);
  String myData = "";

  switch (v.getId()) {
  case R.id.saveInternalStorage:
   try {
    FileOutputStream fos = new FileOutputStream(myInternalFile);
    fos.write(myInputText.getText().toString().getBytes());
    fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   myInputText.setText("");
   responseText
   .setText("MySampleFile.txt saved to Internal Storage...");
   break;

  case R.id.getInternalStorage:
   try {
    FileInputStream fis = new FileInputStream(myInternalFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = 
     new BufferedReader(new InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null) {
     myData = myData + strLine;
    }
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   myInputText.setText(myData);
   responseText
   .setText("MySampleFile.txt data retrieved from Internal Storage...");
   break;

  case R.id.saveExternalStorage:
   try {
    FileOutputStream fos = new FileOutputStream(myExternalFile);
    fos.write(myInputText.getText().toString().getBytes());
    fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   myInputText.setText("");
   responseText
   .setText("MySampleFile.txt saved to External Storage...");
   break;

  case R.id.getExternalStorage:
   try {
    FileInputStream fis = new FileInputStream(myExternalFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = 
     new BufferedReader(new InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null) {
     myData = myData + strLine;
    }
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   myInputText.setText(myData);
   responseText
   .setText("MySampleFile.txt data retrieved from Internal Storage...");
   break;


  }
 }

 private static boolean isExternalStorageReadOnly() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  

 private static boolean isExternalStorageAvailable() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  

}

References


25 comments :

  1. Awesome dude... Thanks a lot...

    ReplyDelete
  2. works perfect...but don't forget to add the storage permission in the manifest:

    ReplyDelete
    Replies
    1. Hi,
      when i ran this code . it displays a " unfortunately, your app was stopped".
      plz help me what could be the reason.

      Delete
    2. nothing. you made something wrong

      Delete
  3. oh.... and internal should be external in case 4 when pressing "display from external storage" to settext.....trying to make your tutorial perfect ;)

    ReplyDelete
  4. Great Tutorial...........Keep this Good Work..Very Helpfull.

    Thanks

    ReplyDelete
  5. similarly i have stored images in internal storage by path.But i have to store images as bitmap in internal storage.Is it possible if so, please help me..Thankyou

    ReplyDelete
    Replies
    1. Convert your image into bitmap and than convert that bitmap as String and store that String...
      You can retrieve bitmap again via fetching the String. Than convert that String to bitmap again and assign to ImageView.

      Hope it helps. :)

      Delete
  6. thanx for the post :) can you tell me if there is a doc or pdf file in the internal storage then how to read that file by appropriate reader through our application.

    ReplyDelete
  7. Their managers has some of the best customer service skills ever. For example: I called once to ask about changing unit sizes. The person who answered was perfectly nice & helpful.

    ReplyDelete
  8. Hi,
    when i ran this code . it displays a " unfortunately, your app was stopped".
    plz help me what could be the reason.

    ReplyDelete
  9. For all those who are getting "Unfortunately.your app was stopped" , you need to add some permissions in manifest file to read/write external storage.



    ReplyDelete
  10. For some reason, when I click on "save to external storage", it saves the text file to my internal storage inside the Android directory.
    Whatever, I just removed all the code that uses "myInternalFile" since myExternalFile already saves it in my internal storage.

    ReplyDelete
  11. internal storage means does it store into application data

    ReplyDelete
  12. They gave me a bunch of details & storage options, and offered to help more if I would like. If only other Companies had such service, I would never leave them.

    ReplyDelete
  13. Your code is not working sir, can you help me

    ReplyDelete



  14. add then work well .............. sandhu

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"

    add then work well .............. sandhu

    ReplyDelete