Monday, 15 April 2013

External Storage in Android.


External storage:

In this Android tutorial we’ll learn about writing data to external storage (the SD card). We’ll check if the SD is available and if we can write to it. Once we check that the external storage is available and that we are able to write to it, then we will actually save the data. Let’s jump into it!
We now have everything setup for saving external data. Lets setup a couple boolean variables that will initially be set to false. The first will be called “isSDAvail”, which will let our activity know if there is an external SD card available. The next will be called “isSDWritable”, which obviously will let us know if we can write to the external storages.


1)create a new project named as ExternalStorage.

2)Populate the main.xml file as:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical" android:layout_width="fill_parent"
       android:layout_height="fill_parent" android:weightSum="1">
       <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:text="Enter some text to store in sd card" />
       <EditText android:layout_height="wrap_content"
              android:layout_width="match_parent" android:id="@+id/editText1"
              android:layout_weight="0.05">
              <requestFocus></requestFocus>
       </EditText>
       <Button android:layout_height="wrap_content"
              android:layout_width="match_parent"
               android:layout_weight="0.04"
              android:id="@+id/save"
               android:text="SAVE"></Button>
       <Button android:layout_height="wrap_content"
              android:layout_width="match_parent"
               android:layout_weight="0.05"
              android:id="@+id/load"
               android:text="LOAD"></Button>
</LinearLayout>

3)Now in java file match as:
package com.sartaj.externalstorage;// Package Name



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
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.Toast;

public class ExternalStorage extends Activity {
       private EditText textBox;
       private static final int READ_BLOCK_SIZE = 100;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        textBox = (EditText) findViewById(R.id.editText1);
        Button saveBtn = (Button) findViewById(R.id.save);
        Button loadBtn = (Button) findViewById(R.id.load);
       
        saveBtn.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           String str = textBox.getText().toString();
                           try
                           {
                            //---SD Card Storage---
                           File sdCard = Environment.getExternalStorageDirectory();
                           File directory = new File (sdCard.getAbsolutePath() +"/MyFiles");
                           directory.mkdirs();
                           File file = new File(directory, "textfile.txt");
                          
                           FileOutputStream fOut = new FileOutputStream(file);
                           OutputStreamWriter osw = new OutputStreamWriter(fOut);
                           //---write the string to the file---
                           osw.write(str);
                           osw.flush();
                           osw.close();
                           //---display file saved message---
                           Toast.makeText(getBaseContext(),"File saved successfully!",Toast.LENGTH_SHORT).show();
                           //---clears the EditText---
                           textBox.setText("");
                           }
                           catch (IOException ioe)
                           {
                           ioe.printStackTrace();
                           }
                           }
                          
                     });
        loadBtn.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           try
                           {
                           //---SD Storage---
                           File sdCard = Environment.getExternalStorageDirectory();
                     File directory = new File (sdCard.getAbsolutePath() +"/MyFiles");
                           File file = new File(directory, "textfile.txt");
                          
                           FileInputStream fIn = new FileInputStream(file);
                           InputStreamReader isr = new InputStreamReader(fIn);
                           char[] inputBuffer = new char[READ_BLOCK_SIZE];
                           String s = "";
                           int charRead;
                           while ((charRead = isr.read(inputBuffer))>0)
                           {
                           //---convert the chars to a String---
                           String readString =
                           String.copyValueOf(inputBuffer, 0, charRead);
                           s += readString;
                           inputBuffer = new char[READ_BLOCK_SIZE];
                           }
                           //---set the EditText to the text that has been
                           // read---
                           textBox.setText(s);
                    Toast.makeText(getBaseContext(),"File loaded successfully!",Toast.LENGTH_SHORT).show();
                           }
                           catch (IOException ioe) {
                           ioe.printStackTrace();
                           }
                           }
                          
                    
              });
      
    }
   


}            
       
       
   
4)Add uses permission(WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml .


0 comments:

Post a Comment

 

© 2011 Reach 2 Android - Tutorials on Android and PHP - Designed by Mukund | ToS | Privacy Policy | Sitemap

About Us | Contact Us | Write For Us