{"id":42,"date":"2017-04-06T10:43:54","date_gmt":"2017-04-06T10:43:54","guid":{"rendered":"http:\/\/abhiandroid.com\/database\/?page_id=42"},"modified":"2019-06-17T05:01:58","modified_gmt":"2019-06-17T05:01:58","slug":"external-storage","status":"publish","type":"page","link":"https:\/\/abhiandroid.com\/database\/external-storage","title":{"rendered":"External Storage Tutorial In Android Studio With Example"},"content":{"rendered":"<p>In this tutorial we gonna study about storage of data\/files in android external storage or you can say the secondary memory\/SD card of your phone. The data is stored in a file specified by the user itself and user can access these file. These files are only accessible till the application exits or you have SD card mounted on your device.<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-44\" src=\"\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Explanation-In-Android-Studio.png\" alt=\"External Storage Explanation In Android Studio\" width=\"363\" height=\"443\" srcset=\"https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Explanation-In-Android-Studio.png 363w, https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Explanation-In-Android-Studio-246x300.png 246w\" sizes=\"auto, (max-width: 363px) 100vw, 363px\" \/><br \/>\n<span style=\"color: #ff0000;\"><strong>Important Note:<\/strong><\/span> It is necessary to add external storage the permission to read and write. For that you need to add permission in android Manifest file.<br \/>\nOpen <strong>AndroidManifest.xml<\/strong> file and add permissions to it just after the package name.<\/p>\n<pre>    &lt;uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" \/&gt;\r\n    &lt;uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" \/&gt;\r\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-45\" src=\"\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Read-And-Write-Permission-In-Android-Studio.png\" alt=\"External Storage Read And Write Permission In Android Studio\" width=\"652\" height=\"148\" srcset=\"https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Read-And-Write-Permission-In-Android-Studio.png 652w, https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Read-And-Write-Permission-In-Android-Studio-300x68.png 300w\" sizes=\"auto, (max-width: 652px) 100vw, 652px\" \/><\/p>\n<p><span style=\"color: #008000;\"><strong>External Storage Availability In Android Studio<\/strong><\/span><\/p>\n<p>To avoid crashing app it is required to check before whether storage SD card is available for read &amp; write operations. getExternalStorageState() method is used to determine the state of the storage media i.e SD card is mounted, is it readable , it is writable etc.. all this kind of information.<\/p>\n<pre>boolean isAvailable= false;\r\nboolean isWritable= false;\r\nboolean isReadable= false;\r\nString state = Environment.getExternalStorageState();\r\nif(Environment.MEDIA_MOUNTED.equals(state)){\r\n\/\/ Read and write operation possible\r\n  isAvailable= true;\r\n  isWritable= true;\r\n  isReadable= true;\r\n} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){\r\n   \/\/ Read operation possible\r\n      isAvailable= true;\r\n      isWritable= false;\r\n      isReadable= true;\r\n  } else {\r\n      \/\/ SD card not mounted\r\n      isAvailable = false;\r\n      isWritable= false;\r\n      isReadable= false; }\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Methods to\u00a0Store Data In Android:<\/strong><\/span><\/p>\n<ul>\n<li><strong>getExternalStorageDirectory()<\/strong> &#8211; Older way to access external storage in API \u00a0Level less than 7. It is absolute now and not recommended. It directly get the reference to the root directory of your external storage or SD Card.<\/li>\n<li><strong>getExternalFilesDir(String type) &#8211;<\/strong>\u00a0It is recommended way to enable us to create private files specific to app and files are removed as app is uninstalled. Example is app private data.<\/li>\n<li><strong>getExternalStoragePublicDirectory() :<\/strong>\u00a0This is\u00a0current recommended way that enable us to keep files public and are not deleted with the app uninstallation. Example images clicked by the camera exists even we uninstall the camera app.<\/li>\n<\/ul>\n<hr \/>\n<h4><strong>External Storage Example In Android Studio<\/strong><\/h4>\n<p>Below is the example to show how user can use external 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 which is saved.<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"http:\/\/www.mediafire.com\/file\/k3htpkmb8479kbf\/ExternalStorageExample.zip\/file\" target=\"_blank\" rel=\"nofollow noopener\">Download Code<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-149\" src=\"\/database\/wp-content\/uploads\/2017\/03\/External-Storage-Example-In-android-Studio.gif\" alt=\"External Storage Example In android Studio\" width=\"271\" height=\"419\" \/><br \/>\n<span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create a new project and name it <span style=\"color: #008000;\">ExternalStorageExample<\/span>.<\/p>\n<p><strong><span style=\"color: #008000;\">Step 2:<\/span><\/strong> Open <span style=\"color: #008000;\">res -&gt; layout -&gt; activity_main.xml (or) main.xml<\/span> and add following code:<\/p>\n<p>In this code simply add textview , edittext and button for onclick functionality.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:id=\"@+id\/activity_main\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:paddingBottom=\"@dimen\/activity_vertical_margin\"\r\n    android:paddingLeft=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingRight=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingTop=\"@dimen\/activity_vertical_margin\"\r\n    tools:context=\"com.example.externalstorageexample.MainActivity\"&gt;\r\n\r\n\r\n    &lt;TextView\r\n        android:id=\"@+id\/textView\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignParentTop=\"true\"\r\n        android:layout_marginTop=\"46dp\"\r\n        android:gravity=\"center\"\r\n        android:text=\"@string\/add_text\"\r\n        android:textSize=\"18sp\"\r\n        android:textStyle=\"bold|italic\" \/&gt;\r\n\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button4\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignLeft=\"@+id\/button\"\r\n        android:layout_alignParentBottom=\"true\"\r\n        android:layout_alignStart=\"@+id\/button\"\r\n        android:layout_marginBottom=\"52dp\"\r\n        android:layout_marginLeft=\"96dp\"\r\n        android:layout_marginStart=\"96dp\"\r\n        android:onClick=\"next\"\r\n        android:text=\"@string\/click_to_view\" \/&gt;\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button2\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_above=\"@+id\/button4\"\r\n        android:layout_alignParentEnd=\"true\"\r\n        android:layout_alignParentRight=\"true\"\r\n        android:layout_marginBottom=\"22dp\"\r\n        android:layout_marginEnd=\"32dp\"\r\n        android:layout_marginRight=\"32dp\"\r\n        android:onClick=\"savePublic\"\r\n        android:text=\"@string\/save_as_public\" \/&gt;\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignBaseline=\"@+id\/button2\"\r\n        android:layout_alignBottom=\"@+id\/button2\"\r\n        android:layout_alignParentLeft=\"true\"\r\n        android:layout_alignParentStart=\"true\"\r\n        android:layout_marginLeft=\"24dp\"\r\n        android:layout_marginStart=\"24dp\"\r\n        android:onClick=\"savePrivate\"\r\n        android:text=\"@string\/save_as_private\" \/&gt;\r\n\r\n    &lt;EditText\r\n        android:id=\"@+id\/editText2\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignParentLeft=\"true\"\r\n        android:layout_alignParentStart=\"true\"\r\n        android:layout_below=\"@+id\/textView\"\r\n        android:layout_marginTop=\"16dp\"\r\n        android:ems=\"10\"\r\n        android:gravity=\"center_vertical|center\"\r\n        android:inputType=\"textMultiLine\" \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong> <\/span>Open <span style=\"color: #008000;\">src -&gt; package -&gt; MainActivity.java<\/span><\/p>\n<p>In this step we open MainActivity and add the functions defined over buttons onclick. The savePrivate and savePublic function get the data from edittext and save it in byte format in file. Also toast is used 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.<\/p>\n<p><span style=\"color: #ff0000;\"><strong>Important Note:<\/strong><\/span> There is a difference while retrieving data with different API level. The permission concept has changed since API 23. Before API level 23 the user was asked during installation, after API level 23 the user is asked during runtime. So an additional runtime permission is added in the application operating over the API level above 23.<\/p>\n<pre>package com.example.externalstorageexample;\r\n\r\nimport android.Manifest;\r\nimport android.content.Intent;\r\nimport android.os.Environment;\r\nimport android.support.v4.app.ActivityCompat;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.View;\r\nimport android.widget.EditText;\r\nimport android.widget.Toast;\r\nimport java.io.File;\r\nimport java.io.FileOutputStream;\r\nimport java.io.IOException;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n    EditText editText;\r\n    private int STORAGE_PERMISSION_CODE = 23;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        editText = (EditText) findViewById(R.id.editText2);\r\n    }\r\n\r\n    public void next(View view) {\r\n        Intent intent = new Intent(MainActivity.this, Main2Activity.class);\r\n        startActivity(intent);\r\n    }\r\n\r\n    public void savePublic(View view) {\r\n        \/\/Permission to access external storage\r\n        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);\r\n        String info = editText.getText().toString();\r\n        File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);\/\/ Folder Name\r\n        File myFile = new File(folder, \"myData1.txt\");\/\/ Filename\r\n        writeData(myFile, info);\r\n        editText.setText(\"\");\r\n    }\r\n\r\n    public void savePrivate(View view) {\r\n        String info = editText.getText().toString();\r\n        File folder = getExternalFilesDir(\"AbhiAndroid\");\/\/ Folder Name\r\n        File myFile = new File(folder, \"myData2.txt\");\/\/ Filename\r\n        writeData(myFile, info);\r\n        editText.setText(\"\");\r\n    }\r\n\r\n    private void writeData(File myFile, String data) {\r\n        FileOutputStream fileOutputStream = null;\r\n        try {\r\n            fileOutputStream = new FileOutputStream(myFile);\r\n            fileOutputStream.write(data.getBytes());\r\n            Toast.makeText(this, \"Done\" + myFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();\r\n        } catch (Exception e) {\r\n            e.printStackTrace();\r\n        } finally {\r\n            if (fileOutputStream != null) {\r\n                try {\r\n                    fileOutputStream.close();\r\n                } catch (IOException e) {\r\n                    e.printStackTrace();\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong><span style=\"color: #008000;\">Step 4<\/span><\/strong>: Open <span style=\"color: #008000;\">res -&gt; layout -&gt; activity_main2.xml (or) main2.xml<\/span> and add following code:<\/p>\n<p>In this activity the layout is just similar with the main.xml.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n    xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n    android:id=\"@+id\/activity_main2\"\r\n    android:layout_width=\"match_parent\"\r\n    android:layout_height=\"match_parent\"\r\n    android:paddingBottom=\"@dimen\/activity_vertical_margin\"\r\n    android:paddingLeft=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingRight=\"@dimen\/activity_horizontal_margin\"\r\n    android:paddingTop=\"@dimen\/activity_vertical_margin\"\r\n    tools:context=\"com.example.externalstorageexample.Main2Activity\"&gt;\r\n\r\n    &lt;TextView\r\n        android:id=\"@+id\/getText\"\r\n        android:layout_width=\"match_parent\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignParentLeft=\"true\"\r\n        android:layout_alignParentStart=\"true\"\r\n        android:layout_alignParentTop=\"true\"\r\n        android:layout_marginTop=\"33dp\"\r\n        android:gravity=\"center\"\r\n        android:text=\"\"\r\n        android:textSize=\"18sp\"\r\n        android:textStyle=\"bold|italic\" \/&gt;\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button3\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_above=\"@+id\/button5\"\r\n        android:layout_alignParentEnd=\"true\"\r\n        android:layout_alignParentRight=\"true\"\r\n        android:onClick=\"getPublic\"\r\n        android:text=\"@string\/show_public_data\" \/&gt;\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button2\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_alignParentLeft=\"true\"\r\n        android:layout_alignParentStart=\"true\"\r\n        android:layout_below=\"@+id\/getText\"\r\n        android:layout_marginTop=\"178dp\"\r\n        android:onClick=\"getPrivate\"\r\n        android:text=\"@string\/show_private_data\"\r\n        tools:ignore=\"UnknownId\" \/&gt;\r\n\r\n    &lt;Button\r\n        android:id=\"@+id\/button5\"\r\n        android:layout_width=\"wrap_content\"\r\n        android:layout_height=\"wrap_content\"\r\n        android:layout_below=\"@+id\/button2\"\r\n        android:layout_centerHorizontal=\"true\"\r\n        android:layout_marginTop=\"59dp\"\r\n        android:onClick=\"back\"\r\n        android:text=\"@string\/back\" \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong> <\/span>Open <span style=\"color: #008000;\">src -&gt; package -&gt; MainActivity2.java<\/span><\/p>\n<p>In this step we open MainActivity2 and add the functions defined over button&#8217;s onclick. The getPrivate and getPublic function retrieve the data from the file, add it to the buffer and further set the text over the textview&#8217;s. The \u00a0back function contain intent to move back to main activity.<\/p>\n<pre>package com.example.externalstorageexample;\r\n\r\nimport android.content.Intent;\r\nimport android.os.Environment;\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.View;\r\nimport android.widget.TextView;\r\nimport java.io.*;\r\n\r\npublic class Main2Activity extends AppCompatActivity {\r\n    TextView showText;\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main2);\r\n        showText = (TextView) findViewById(R.id.getText);\r\n\r\n    }\r\n\r\n    public void back(View view) {\r\n        Intent intent = new Intent(Main2Activity.this, MainActivity.class);\r\n        startActivity(intent);\r\n    }\r\n\r\n    public void getPublic(View view) {\r\n        File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS); \/\/ Folder Name\r\n        File myFile = new File(folder, \"myData1.txt\"); \/\/ Filename\r\n        String text = getdata(myFile);\r\n        if (text != null) {\r\n            showText.setText(text);\r\n        } else {\r\n            showText.setText(\"No Data\");\r\n        }\r\n    }\r\n\r\n    public void getPrivate(View view) {\r\n        File folder = getExternalFilesDir(\"AbhiAndroid\"); \/\/ Folder Name\r\n        File myFile = new File(folder, \"myData2.txt\"); \/\/ Filename\r\n        String text = getdata(myFile);\r\n        if (text != null) {\r\n            showText.setText(text);\r\n        } else {\r\n            showText.setText(\"No Data\");\r\n        }\r\n    }\r\n\r\n    private String getdata(File myfile) {\r\n        FileInputStream fileInputStream = null;\r\n        try {\r\n            fileInputStream = new FileInputStream(myfile);\r\n            int i = -1;\r\n            StringBuffer buffer = new StringBuffer();\r\n            while ((i = fileInputStream.read()) != -1) {\r\n                buffer.append((char) i);\r\n            }\r\n            return buffer.toString();\r\n        } catch (Exception e) {\r\n            e.printStackTrace();\r\n        } finally {\r\n            if (fileInputStream != null) {\r\n                try {\r\n                    fileInputStream.close();\r\n                } catch (IOException e) {\r\n                    e.printStackTrace();\r\n                }\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n\r\n}\r\n<\/pre>\n<p><strong><span style=\"color: #008000;\">Output<\/span>:<\/strong><\/p>\n<p>Now run the app and you will see form on the screen. Add data in the field and save it. Further click next to move to next activity and get data that is saved before as public or private.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial we gonna study about storage of data\/files in android external storage or you can say the secondary memory\/SD card of your phone. The data is stored in a file specified by the user itself and user can access these file. These files are only accessible till the application exits or you have &hellip; <a href=\"https:\/\/abhiandroid.com\/database\/external-storage\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">External Storage Tutorial In Android Studio With Example<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"home.php","meta":{"_acf_changed":false,"footnotes":""},"class_list":["post-42","page","type-page","status-publish","hentry"],"acf":[],"psp_head":"<title>External Storage Tutorial In Android Studio With Example \u2013 Android Database Tutorial In Android Studio: Store Your Data<\/title>\r\n<meta name=\"description\" content=\"In this tutorial learn about external storage of data\/files in android with example in Android Studio. You can also say the secondary memory\/SD card of your phone.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/database\/external-storage\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/pages\/42","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/comments?post=42"}],"version-history":[{"count":3,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/pages\/42\/revisions"}],"predecessor-version":[{"id":344,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/pages\/42\/revisions\/344"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/media?parent=42"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}