Reading and Writing a file to SD card sample program in Android

This sample android program shows you how write and read a file from SD Card in Android. In this program four buttons are shown and a Edit box. When you type some text into the edit box and click, Save to SD Card button, the text is saved to a text file and saved to the SD Card. When you click clear button, the edit box contents are cleared. When you click, Read Sd card button the file is read from the SD card and the contents are copied to the edit box.

The FileDemo2.java file is as follows:

package com.javasamples;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class FileDemo2 extends Activity {
	// GUI controls
	EditText txtData;
	Button btnWriteSDFile;
	Button btnReadSDFile;
	Button btnClearScreen;
	Button btnClose;

	@Override
	public void onCreate(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(new OnClickListener() {

	public void onClick(View v) {
		// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = 
									new OutputStreamWriter(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(new OnClickListener() {

		public void onClick(View v) {
			// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));
			String aDataRow = "";
			String aBuffer = "";
			while ((aDataRow = myReader.readLine()) != null) {
				aBuffer += aDataRow + "\n";
			}
			txtData.setText(aBuffer);
			myReader.close();
			Toast.makeText(getBaseContext(),
					"Done reading SD 'mysdfile.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(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				txtData.setText("");
			}
		}); // btnClearScreen

		btnClose = (Button) findViewById(R.id.btnClose);
		btnClose.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				finish();
			}
		}); // btnClose

	}// onCreate

}// AndSDcard

The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:


<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"
>







 

Install SDK + PhoneGap for ANDROID

  • 1. Requirements For ANDROID

    • Eclipse 3.4+

    There is also a Terminal version of this tutorial that doesn’t use Eclipse.

  • 2. Install SDK + PhoneGap

    Download and install Eclipse Classic

    Download and install Android SDK

    Download and install ADT Plugin

    Download the latest copy of PhoneGap and extract its contents. We will be working with the Android directory.

  • 3. Setup New Project

    • Launch Eclipse, then under the File menu select New > Android Project

    • In the root directory of the project, create two new directories:
      • /libs
      • /assets/www
    • Copy phonegap.js from your PhoneGap download earlier to /assets/www
    • Copy phonegap.jar from your PhoneGap download earlier to /libs
    • Copy xml folder from your PhoneGap download earlier to /res
    • Make a few adjustments too the project’s main Java file found in the src folder in Eclipse: (view image below)
      • Change the class’s extend from Activity to DroidGap
      • Replace the setContentView() line with super.loadUrl(“file:///android_asset/www/index.html”);
      • Add import com.phonegap.*;
      • Remove import android.app.Activity;

javaSrc

  • You might experience an error here, where Eclipse can’t find phonegap-1.0.0.jar. In this case, right click on the /libs folder and go to Build Paths/ > Configure Build Paths. Then, in the Libraries tab, add phonegap-1.0.0.jar to the Project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.
  • Right click on AndroidManifest.xml and select Open With > Text Editor
  • Paste the following permissions under versionName: (view image below)
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
  • Add android:configChanges="orientation|keyboardHidden" to the activity tag in AndroidManifest. (view image below)
  • Add a second activity under you appliction tag in AndroidManifest. (view image below)
<activity android:name="com.phonegap.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> <intent-filter> </intent-filter> </activity>

manifest

  • 4. Hello World

    Now create and open a new file named index.html in the /assets/www directory. Paste the following code:

    <!--DOCTYPE HTML>
    <html>
    <head>
    <title>PhoneGap</title>
    // <![CDATA[
    javascript
    " charset="utf-8" src="phonegap.js">
    // ]]>
    </head>
    <body>
    <h1>Hello World</h1>
    </body>
    </html>

    *phonegap.js might need to be replaced with phonegap..js

  • 5A. Deploy to Simulator

    • Right click the project and go to Run As and click Android Application
    • Eclipse will ask you to select an appropriate AVD. If there isn’t one, then you’ll need to create it.
  • 5B. Deploy to Device

    • Make sure USB debugging is enabled on your device and plug it into your system. (Settings > Applications > Development)
    • Right click the project and go to Run As and click Android Application
  • Done!

    You can also checkout more detailed version of this guide here.

  •