External Storage

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Android External Storage Example

Like internal storage, we are able to save or read data from the device external memory such as sdcard. The FileInputStream and FileOutputStream classes are used to read and write data into the file.


Example of reading and writing data in the android external storage

activity_main.xml

Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like this:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentRight="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginRight="20dp"  
  14.         android:layout_marginTop="24dp"  
  15.         android:ems="10" >  
  16.   
  17.         <requestFocus />  
  18.     </EditText>  
  19.   
  20.     <EditText  
  21.         android:id="@+id/editText2"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_alignRight="@+id/editText1"  
  25.         android:layout_below="@+id/editText1"  
  26.         android:layout_marginTop="24dp"  
  27.         android:ems="10" />  
  28.   
  29.     <TextView  
  30.         android:id="@+id/textView1"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignBaseline="@+id/editText1"  
  34.         android:layout_alignBottom="@+id/editText1"  
  35.         android:layout_alignParentLeft="true"  
  36.         android:text="File Name:" />  
  37.   
  38.     <TextView  
  39.         android:id="@+id/textView2"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_alignBaseline="@+id/editText2"  
  43.         android:layout_alignBottom="@+id/editText2"  
  44.         android:layout_alignParentLeft="true"  
  45.         android:text="Data:" />  
  46.   
  47.     <Button  
  48.         android:id="@+id/button1"  
  49.         android:layout_width="wrap_content"  
  50.         android:layout_height="wrap_content"  
  51.         android:layout_alignLeft="@+id/editText2"  
  52.         android:layout_below="@+id/editText2"  
  53.         android:layout_marginLeft="70dp"  
  54.         android:layout_marginTop="16dp"  
  55.         android:text="save" />  
  56.   
  57.     <Button  
  58.         android:id="@+id/button2"  
  59.         android:layout_width="wrap_content"  
  60.         android:layout_height="wrap_content"  
  61.         android:layout_alignBaseline="@+id/button1"  
  62.         android:layout_alignBottom="@+id/button1"  
  63.         android:layout_toRightOf="@+id/button1"  
  64.         android:text="read" />  
  65.   
  66. </RelativeLayout>  

Provide permission for the external storage

You need to provide the WRITE_EXTERNAL_STORAGE permission.

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
File: Activity_Manifest.xml
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest   
  3.   
  4. xmlns:android="http://schemas.android.com/apk/res/android"  
  5.     package="com.example.externalstorage"  
  6.     android:versionCode="1"  
  7.     android:versionName="1.0" >  
  8.   
  9.     <uses-sdk  
  10.         android:minSdkVersion="8"  
  11.         android:targetSdkVersion="16" />  
  12. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  13.   
  14.     <application  
  15.         android:allowBackup="true"  
  16.         android:icon="@drawable/ic_launcher"  
  17.         android:label="@string/app_name"  
  18.         android:theme="@style/AppTheme" >  
  19.         <activity  
  20.             android:name="com.example.externalstorage.MainActivity"  
  21.             android:label="@string/app_name" >  
  22.             <intent-filter>  
  23.                 <action android:name="android.intent.action.MAIN" />  
  24.   
  25.                 <category android:name="android.intent.category.LAUNCHER" />  
  26.             </intent-filter>  
  27.         </activity>  
  28.     </application>  
  29.   
  30. </manifest>

Activity class

Let's write the code to write and read data from the android external storage.

File: MainActivity.java

  1. package com.example.externalstorage;  

  2.   

  3. import java.io.BufferedReader;  

  4. import java.io.File;  

  5. import java.io.FileInputStream;  

  6. import java.io.FileNotFoundException;  

  7. import java.io.FileOutputStream;  

  8. import java.io.IOException;  

  9. import java.io.InputStreamReader;  

  10. import java.io.OutputStreamWriter;  

  11.   

  12. import android.os.Bundle;  

  13. import android.app.Activity;  

  14. import android.content.Context;  

  15. import android.view.Menu;  

  16. import android.view.View;  

  17. import android.view.View.OnClickListener;  

  18. import android.widget.Button;  

  19. import android.widget.EditText;  

  20. import android.widget.Toast;  

  21.   

  22. public class MainActivity extends Activity {  

  23.     EditText editTextFileName,editTextData;  

  24.     Button saveButton,readButton;  

  25.     @Override  

  26.     protected void onCreate(Bundle savedInstanceState) {  

  27.         super.onCreate(savedInstanceState);  

  28.         setContentView(R.layout.activity_main);  

  29.           

  30.         editTextFileName=(EditText)findViewById(R.id.editText1);  

  31.         editTextData=(EditText)findViewById(R.id.editText2);  

  32.         saveButton=(Button)findViewById(R.id.button1);  

  33.         readButton=(Button)findViewById(R.id.button2);  

  34.           

  35.         //Performing action on save button  

  36.         saveButton.setOnClickListener(new OnClickListener(){  

  37.   

  38.             @Override  

  39.             public void onClick(View arg0) {  

  40.                 String filename=editTextFileName.getText().toString();  

  41.                 String data=editTextData.getText().toString();  

  42.                   

  43.                 FileOutputStream fos;  

  44.                    try {  

  45.                        File myFile = new File("/sdcard/"+filename);  

  46.                         myFile.createNewFile();  

  47.                         FileOutputStream fOut = new   

  48.   

  49. FileOutputStream(myFile);  

  50.                         OutputStreamWriter myOutWriter = new   

  51.   

  52. OutputStreamWriter(fOut);  

  53.                         myOutWriter.append(data);  

  54.                         myOutWriter.close();  

  55.                         fOut.close();  

  56.                      

  57.             Toast.makeText(getApplicationContext(),filename + "   

  58.   

  59. saved",Toast.LENGTH_LONG).show();  

  60.                       

  61.                      

  62.                    } catch (FileNotFoundException e) {e.printStackTrace();}  

  63.                    catch (IOException e) {e.printStackTrace();}  

  64.                   

  65.             }  

  66.               

  67.         });  

  68.   

  69.         //Performing action on Read Button  

  70.         readButton.setOnClickListener(new OnClickListener(){  

  71.   

  72.             @Override  

  73.             public void onClick(View arg0) {  

  74.                 String filename=editTextFileName.getText().toString();  

  75.                 StringBuffer stringBuffer = new StringBuffer();    

  76.                 String aDataRow = "";  

  77.                 String aBuffer = "";  

  78.                 try {  

  79.                     File myFile = new File("/sdcard/"+filename);  

  80.                     FileInputStream fIn = new FileInputStream(myFile);  

  81.                     BufferedReader myReader = new BufferedReader(  

  82.                             new InputStreamReader(fIn));  

  83.                       

  84.                     while ((aDataRow = myReader.readLine()) != null) {  

  85.                         aBuffer += aDataRow + " ";  

  86.                     }  

  87.                     myReader.close();  

  88.                       

  89.                 } catch (IOException e) {  

  90.                     e.printStackTrace();  

  91.                 }  

  92.                 Toast.makeText(getApplicationContext  

  93.   

  94. (),aBuffer,Toast.LENGTH_LONG).show();  

  95.                   

  96.             }  

  97.               

  98.         });  

  99.     }  

  100.   

  101.     @Override  

  102.     public boolean onCreateOptionsMenu(Menu menu) {  

  103.         // Inflate the menu; this adds items to the action bar if it is present.  

  104.         getMenuInflater().inflate(R.menu.activity_main, menu);  

  105.         return true;  

  106.     }  

  107.   

  108. }