Android Internal Storage

Android provides several storage options to store the data.

Following are the data storage options
1. Shared Preferences
2. Internal Storage
3. External Storage
4. SQLite Database
5. Network Connection

Internal storage helps users to save or read their data from the device Internal memory. The FileInputStream and FileOutputStream classes are used to read and write data into the file.

storing process

A. Write Operation

The openFileOutput() method is called for writing the data in the file using Internal storage. It takes two parameters. First parameter is the file name and second one is file mode.

Syntax:
FileOutputStreamfopStream = openFileOutput(“file_name”, MODE_PRIVATE);

Example

String str = “TutorialRide”;
fopStream.write(str.getBytes());
fopStream.close();

B. Read Operation

The openFileInput() method is called for reading the data from file with the name of the file. It takes one parameter as file name. The file name should be same as you have written in the openFileOutput() method. It returns an instance of FileInputStream class.

Example

int read = -1;
StringBuffersb = newStringBuffer();
FileInputStreamfipStream = openFileInput(“file_name”);
while((read = fibStream.read()) != -1)
{
       sb.append((char)read);
}

1. Shared Preference

  • The SharedPreferences class is used to store the private primitive data (such as int, float, boolean, long and string) in key-value pairs.
  • This class provides a general framework which allows to save and retrieve persistent key-value pairs of primitive data types.
  • The getSharedPreferences() and getPreferences() methods are used to get a SharedPreferences object for the application.
  • The getSharedPreferences() method is used when user needs multiple preferences file which is identified by name.
  • The getPreferences() method is used when user needs only one preferences file for his/her activity. Because this will be the only preferences file for Activity which don't supply a name.

2. Internal Storage

  • Internal storage is used to store private data on the device memory.
  • This storage enables you to read and write data into files that are associated with each application's internal memory.
  • By default, the user can save the files to the internal storage which are private to the application. Neither other applications nor the user can access these files.
  • When the user uninstalls the application, these files are removed from the device memory.
  • When users use MODE-PRIVATE for files on the internal storage, they are never accessible to the other applications.
  • The other modes are
    i) MODE_APPEND
    ii) MODE_WORLD_READABLE
    iii) MODE_WORLD_WRITEABLE

3. External Storage

  • External storage is used to store public data on the shared external storage.
  • This storage can be removable storage media such as an SD card or an internal (non-removable) storage.
  • The user can read and modify the files if they are stored in the external storage.
  • The READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE is used to acquire the system permissions to read or write the files on the external storage.
  • The WRITE_EXTERNAL_STORAGE permission is used when the user needs both read and write files, because it implicitly requires read access as well.

4. SQLite Database

  • SQLite database is used to store the structured data in a private database.
  • The database will be accessible by its name to any class in the application, but not outside the application.
  • Android provides full support to SQLite databases.
  • The SQLiteOpenHelper class is used for creating a database and version management. This class includes two methods onCreate() and onUpgrade() for creating and updating the database.

5. Network Connection

  • Network Connection is used to store the data on the web with your own network server.
  • The user can use the network connection when it's available to store and retrieve the data on your own web-based services.

  • The following packages are used with the classes for performing the network connection
    1. Java.net.*
    2. android.net.*

  • The Java.net.* package provides the classes for implementing the networking applications.

  • This package is divided into two sections,
    i. Low Level API deals with addresses, sockets and interfaces.
    ii. High Level API deals with URIs, URLs and connections.

  • The android.net.* package classes provide network access, beyond the normal java.net.* APIs.

Example : Android Internal Storage

Following internal storage example demonstrates, how the user's data is stored into an Android internal memory.

Write Operation

File name: activity_main.xml

<RelativeLayoutxmlns: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/btnNext"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/btnSave"
android:layout_marginLeft = "35dp"
android:layout_toRightOf = "@+id/btnSave"
android:text = "Next Activity"
android:onClick = "next"
/>

<TextView
android:id = "@+id/textView2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/textView1"
android:layout_below = "@+id/txtUserName"
android:layout_marginTop = "70dp"
android:text = "Password"
android:textSize = "15dp"
/>

<EditText
android:id = "@+id/txtPassword"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/textView2"
android:layout_toRightOf = "@+id/textView1"
android:ems = "10"
android:inputType = "textPassword">

</EditText>

<Button
android:id = "@+id/btnSave"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@+id/textView2"
android:layout_marginTop = "96dp"
android:layout_toLeftOf = "@+id/editText1"
android:text = "Save"
android:onClick = "save"
/>

<TextView
android:id = "@+id/textView1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/btnSave"
android:layout_alignParentTop = "true"
android:layout_marginTop = "30dp"
android:text = "UserName"
android:textSize = "15dp"/>

<EditText
android:id="@+id/txtUserName"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignBottom = "@+id/textView1"
android:layout_alignLeft = "@+id/txtPassword"
android:ems = "10"/>
<requestFocus/>
</RelativeLayout>

File name: MainActivity.java

public class MainActivity extends Activity
{
      EditTextname,password;
      FileOutputStreamfopStream;
      File file = null;
      @Override
      protected void onCreate(Bundle savedInstanceState)
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);//XML file name activity_main.xml
            name = (EditText)findViewById(R.id.txtUserName);
            password = (EditText)findViewById(R.id.txtPassword);
     }
     public void save(View v)
     {
            String txt1 = name.getText().toString();
            String txt2 = password.getText().toString();
            txt1 = txt1+" ";
            try
            {
                  file = getFilesDir();
                  fopStream = openFileOutput ("data.txt",Context.MODE_PRIVATE);
                  fopStream.write(txt1.getBytes ());
                  fopStream.write(txt2.getBytes ());
            }
            catch (Exception e)
            {
                 e.printStackTrace();
            }
            finally
            {
                 try
                 {
                       fopStream.close();
                 }
                 catch (IOException e)
                 {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                 }
            }
            Toast.makeText(getApplicationContext(), "Data Stored Successfully at location "+file, Toast.LENGTH_LONG).show();
     }
     public void next(View v)
     {
          Toast.makeText(getApplicationContext(), "Next Activity called", Toast.LENGTH_LONG).show();
          Intent intent = newIntent(getApplicationContext(), SecondActivity.class);
          startActivity(intent);
     }
}


Output:

android internal storage