Data storage-SD Card File handling
File accessing in Android SD card Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or a non-removable storage. Files saved to the external storage are world readable and can be modified by the user when they enable USB mass storage to transfer files on a computer
Checking Media Availability
Before you do any work with the external storage, you should always call getExternalStorageState() to check the state of the media
- Mounted
- Missing
- Read-only
- Some other state
Example: Checking Media State
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but
// all we need to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that
represents the external storage directory where you should save your files This method takes a type parameter that specifies the type of subdirectory you want, such as
DIRECTORY_MUSIC and DIRECTORY_RINGTONES
This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music).If the user uninstalls your application, this directory and all its contents will be deleted.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage.You should then write your data in the following directory: /Android/data/<package_name>/files/(where <package_name> is your Java-style package name,such as "com.example.android.app") If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage.These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and
others.
In API Level 8 or greater Use getExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others.This method will create the appropriate directory if necessary.In API Level 7 or lower Use getExternalStorageDirectory()to open a File that represents the root of the external storage, then save your shared files in one of the following directories: Music/, Podcasts/, Ringtones/, Alarms/, Notifications/,Pictures/, Movies/, Download/
The Demonstrative project portrays accessing external mass storage such as SD card to manage files and folders
1.Create Android project with details as listed in the table below.
Property name | Property value |
Project name | SRM_ExternalStorage_Tutorial |
Package name | in.ac.srmuniv |
Activity name | StorageAndroidActivity |
Layout xml name | main |
2.Copy the code to the file main.xml in res/layout folder
<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText
android:id="@+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="@+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:text="1. Write SD File" />
<Button
android:id="@+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:text="2. Clear Screen" />
<Button
android:id="@+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:text="3. Read SD File" />
<Button
android:id="@+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:text="4. Close"/>
</LinearLayout>
3.Copy the code in StorageAndroidActivity.java. Activity.
package in.ac.srmuniv;
import in.ac.srmuniv.R;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class StorageAndroidActivityextends Activity {
private static finalString TAG = "Dir";
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
@Override
public voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(newOnClickListener() {
public voidonClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/navin.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
newOutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(newOnClickListener() {
public voidonClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/navin.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
newInputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'nawin.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(newOnClickListener() {
public voidonClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(newOnClickListener() {
public voidonClick(View v) {
// clear text box
finish();
}
}); // btnClose
File sddir = new File("/sdcard/SRMDirectory");
if(sddir.mkdirs()) {
Toast toast = Toast.makeText(this,
"Directory successfully created!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else{
Log.e(TAG, "Create dir in sdcard failed");
Toast toast = Toast.makeText(this,
"Directory creation failed!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
4.Modify the Androidmanifest.xml to add permission to use SD card
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.ac.srmuniv"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".StorageAndroidActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
5.Run the application in the emulator.
6.Enter some text into the EditText view and then click ‘writeSD’ button(see Figure 6-2). To save typed contents in EditText tp SD card
Figure 2 Screen shot of ap[plication
7.Typed content can be written or read from ‘navin.txt’ file in External SD card
Figure 3 Shows screen shot of storing data to SD card file
CODE EXPLANATION
File object has the constructor which takes string argument of the file path here “/sdcard/navin.txt"refers to relative path to root directory.Binding the FileOutput Stream object to OutputStreamWriter object eables to write character data to be written to the file in SD card.
File myFile = new File("/sdcard/navin.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = newOutputStreamWriter(fOut);
myOutWriter.append(txtData.getText()); myOutWriter.close();
fOut.close();
Similarly reading from file in SD card is done here BufferedReader and InputStreamReader are used .
File myFile = new File("/sdcard/navin.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = newBufferedReader(
newInputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
A Directory can be be created calling mkdirs() method of File object
File sddir = new File("/sdcard/SRMDirectory");
if(sddir.mkdirs()) {
Toast toast = Toast.makeText(this,
"Directory successfully created!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
The following figure shows the DDMS perspective of SD card file storage .Select mnt/in.ac.srmuniv you can find the created file you can pull the file from the DDMS perspective and save in system for viewing the contents. Figure 4 Shows DDMS perspective of created file in SD Card