Print Friendly and PDF
Android provides many kinds of storage for applications to store their data. Thes storage places are shared preferences , internal and external storage , SQLite storage , and storage via network connection. In this chapter we are going to look at the internal storage. Internal storge is the storage of the private data on the device memory. By default these files are private and are accessed by only your application and get deleted , when user delete your application.
Android provides many kinds of storage for applications to store their data. Thes storage places are shared preferences , internal and external storage , SQLite storage , and storage via network connection.

In this chapter we are going to look at the internal storage. Internal storge is the storage of the private data on the device memory.

By default these files are private and are accessed by only your application and get deleted , when user delete your application.

Writing file

In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below:
FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE); 
The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below:


String str = "data";
fOut.write(str.getBytes());
fOut.close();

Reading file

In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its sytanx is given below:
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below:

int c;
String temp="";
while( (c = fin.read()) != -1){
   temp = temp + Character.toString((char)c);
}
//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods provided by the Fileoutputstream class for better writing files. These methods are listed below:


Sr.NoMethod & description
1FileOutputStream(File file, boolean append)
This method constructs a new FileOutputStream that writes to file.
2getChannel()
This method returns a write-only FileChannel that shares its position with this stream
3getFD()
This method returns the underlying file descriptor
4write(byte[] buffer, int byteOffset, int byteCount)
This method Writes count bytes from the byte array buffer starting at position offset to this stream
Apart from the the methods of read and close, there are other methods provided by the FileInputStreamclass for better reading files. These methods are listed below:


Sr.NoMethod & description
1available()
This method returns an estimated number of bytes that can be read or skipped without blocking for more input
2getChannel()
This method returns a read-only FileChannel that shares its position with this stream
3getFD()
This method returns the underlying file descriptor
4read(byte[] buffer, int byteOffset, int byteCount)
This method reads at most length bytes from this stream and stores them in the byte array b starting at offset
ExampleHere is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage.

To experiment with this example , you can run this on an actual device or in an emulator.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Storage under a package com.example.storage. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modifed main activity file src/com.example.storage/MainActivity.java.
package com.example.storage;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

   private EditText et;
   private String data;
   private String file = "mydata";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      et = (EditText)(findViewById(R.id.editText1));

   }

   public void save(View view){
      data = et.getText().toString();
      try {
         FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
         fOut.write(data.getBytes());
         fOut.close();
         Toast.makeText(getBaseContext(),"file saved",
         Toast.LENGTH_SHORT).show();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   public void read(View view){
      try{
         FileInputStream fin = openFileInput(file);
         int c;
         String temp="";
         while( (c = fin.read()) != -1){
            temp = temp + Character.toString((char)c);
         }
         et.setText(temp);
         Toast.makeText(getBaseContext(),"file read",
         Toast.LENGTH_SHORT).show();

      }catch(Exception e){

      }
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}
Following is the modified content of the xml res/layout/activity_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="182dp"
      android:onClick="save"
      android:text="@string/save" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/button1"
      android:layout_alignRight="@+id/button1"
      android:layout_below="@+id/button1"
      android:layout_marginTop="46dp"
      android:onClick="read"
      android:text="@string/read" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/button1"
      android:layout_alignParentTop="true"
      android:layout_marginTop="23dp"
      android:ems="10"
      android:inputType="textMultiLine" >

      <requestFocus />
   </EditText>

</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Storage</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="save">save to intenal storage</string>
   <string name="read">load from intenal storag</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.storage"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.storage.MainActivity"
         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>
Let's try to run our Storage application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Android Internal Stroage Tutorial
Now what you need to do is to enter any text in the field. For example , i have entered soem text. Press the save button. The following notification would appear in you AVD:

Android Internal Stroage Tutorial
Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned:

Android Internal Stroage Tutorial


Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and navigate this path.
data>data>com.example.storage>files>mydata
This has also been shown in the image below.

Android Internal Stroage Tutorial

zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: