0% found this document useful (0 votes)
17 views

Android Internal Storage With Examples

This document discusses storing and retrieving data from internal storage in Android. It explains that internal storage is useful for storing private data files locally on a device's internal memory. Files saved to internal storage can only be accessed by the app and will be deleted if the app is uninstalled. The document then provides code examples for writing a file to internal storage using FileOutputStream and reading a file from internal storage using FileInputStream. It also includes a full Android code example app that demonstrates saving user name and password details to internal storage and then retrieving and displaying the details on another activity screen.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Android Internal Storage With Examples

This document discusses storing and retrieving data from internal storage in Android. It explains that internal storage is useful for storing private data files locally on a device's internal memory. Files saved to internal storage can only be accessed by the app and will be deleted if the app is uninstalled. The document then provides code examples for writing a file to internal storage using FileOutputStream and reading a file from internal storage using FileInputStream. It also includes a full Android code example app that demonstrates saving user name and password details to internal storage and then retrieving and displaying the details on another activity screen.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Android Internal Storage with

Examples
In android, we have different storage options such as shared preferences, internal storage, external
storage, SQLite storage, etc. to store and retrieve the application data based on our requirements.

In previous chapters, we learned how to use Shared Preferences and now we will see how to use
the Internal Storage option to store and retrieve the data from the device’s internal memory.

In android, Internal Storage is useful to store the data files locally on the device’s internal memory
using a FileOutputStream object. After storing the data files in device internal storage, we can read
the data file from the device using a FileInputStream object.

The data files saved in the internal are managed by an android framework and it can be accessed
anywhere within the app to read or write data into the file, but it’s not possible to access the file from
any other app so it’s secured. When the user uninstalls the app, automatically these data files will be
removed from the device internal storage.

Write a File to Internal Storage


By using the android FileOutputStream object openFileOutput method, we can easily create and
write data to a file in a device’s internal storage.

Following is the code snippet to create and write a private file to the device's internal memory.

String FILENAME = "user_details";


String name = "suresh";

FileOutputStream fstream = openFileOutput(FILENAME,


Context.MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();

If you observe above code, we are creating and writing a file in device internal storage by
using FileOutputStream object openFileOutput method with file
name and MODE_PRIVATE mode to make the file private to our application. We
used write() method to write the data in file and used close() method to close the stream.

In android, we have different modes such as MODE_APPEND,


MODE_WORLD_READBLE,
MODE_WORLD_WRITEABLE
, etc. to use it in our application based on your requirements.
Apart from the above methods write() and close(), FileOutputStream object is having other
methods, those are

Method Description

getChannel() It returns the unique FileChannel object associated with this file output
stream.

getFD() It returns the file descriptor which is associated with the stream.

write(byte[] b, int off, int It writes len bytes from the specified byte array starting at offset off to
len) the file output stream.

Read a File from Internal Storage


By using the android FileInputStream object openFileInput method, we can easily read the file
from the device’s internal storage.

Following is the code snippet to read data from a file that is in the device’s internal memory.

String FILENAME = "user_details";


FileInputStream fstream = openFileInput(FILENAME);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();

If you observe above code, we are reading a file from device internal storage by using
FileInputStream object openFileInput method with file name. We used read() method to read one
character at a time from the file and used close() method to close the stream.

Apart from the above methods read() and close(), FileInputStream object is having other methods,
those are

Method Description

getChannel() It returns the unique FileChannel object associated with this file output
stream.
Method Description

getFD() It returns the file descriptor which is associated with the stream.

read(byte[] b, int off, int len) It reads len bytes of data from the specified file input stream into an
array of bytes.

Now we will see how to save files directly on the device’s internal memory and read the data files
from device internal memory by using FileOutputStream and FileInputStream objects in android
application with examples.

Android Internal Storage Example


Following is the example of storing and retrieving the data files from the device’s internal memory by
using FileOutputStream and FileInputStream objects.

Create a new android application using android studio and give names as InternalStorageExample.
In case if you are not aware of creating an app in android studio check this article Android Hello
World App.

Once we create an application, open activity_main.xml file from \res\layout folder path and write
the code like as shown below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="UserName" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Save" />
</LinearLayout>

Now we will create another layout resource file details.xml in \res\layout path to get the first
activity (activity_main.xml) details in second activity file for that right click on
your layout folder  Go to New  select Layout Resource File and give name as details.xml.

Once we create a new layout resource file details.xml, open it and write the code like as shown
below

details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_gravity="center"
android:layout_marginTop="170dp"
android:textSize="20dp"/>
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Back" />
</LinearLayout>
Now open your main activity file MainActivity.java from \java\
com.tutlane.internalstorageexample path and write the code like as shown below

MainActivity.java
package com.tutlane.internalstorageexample;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {


EditText uname, pwd;
Button saveBtn;
FileOutputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
saveBtn = (Button)findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString()+"\n";
String password = pwd.getText().toString();
try {
fstream = openFileOutput("user_details",
Context.MODE_PRIVATE);
fstream.write(username.getBytes());
fstream.write(password.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), "Details
Saved Successfully",Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this,DetailsActivity
.class);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

If you observe above code, we are taking entered username and password details and saving it in
device local file and redirecting the user to another activity.

Now we will create another activity file DetailsActivity.java in \java\


com.tutlane.internalstorageexample path to show the details from device internal storage for that
right-click on your application folder  Go to New  select Java Class and give name
as DetailsActivity.java.

Once we create a new activity file DetailsActivity.java, open it and write the code like as shown
below

DetailsActivity.java
package com.tutlane.internalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
* Created by tutlane on 04-01-2018.
*/

public class DetailsActivity extends AppCompatActivity {


FileInputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button back = (Button)findViewById(R.id.btnBack);
try {
fstream = openFileInput("user_details");
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
String details[] = sbuffer.toString().split("\n");
result.setText("Name: "+ details[0]+"\nPassword:
"+details[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.cla
ss);
startActivity(intent);
}
});
}
}

Now we need to add this newly created activity in AndroidManifest.xml file in like as shown below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.internalstorageexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<activity android:name=".DetailsActivity" android:label="Internal
Storage - Details"></activity>
</application>
</manifest>

If you observe above example, we are saving entered details file and redirecting the user to
another activity file (DetailsActivity.java) to show the users details and added all the activities
in AndroidManifest.xml file.

Output of Android Internal Storage Example


When we run above example in android emulator we will get a result like as shown below

If you observe the above result, the entered username and password details are storing in the
device’s local memory and redirecting the user to another activity file to show the user details from
the internal storage file. After that, if we click on the Back button, it will redirect the user to the login
page.
Internal storage and shared preferences are both ways to store data in
Android, but they differ in their purpose, scope, and functionality.

Internal storage refers to a private area within the device's file system
where an application can store private data. This data is stored in the
device's internal memory, and it is not visible to other applications or users
unless the application explicitly exposes it. Internal storage is suitable for
storing large amounts of data that are private to the application, such as
media files, application data, and databases.

Shared preferences, on the other hand, are used to store small amounts of
data in key-value pairs. This data is also private to the application and is
stored in a file in the device's internal storage. Shared preferences are
commonly used to store user preferences, application settings, and other
simple data that the application needs to remember across multiple
sessions.

In summary, the main differences between internal storage and shared


preferences are:

 Purpose: Internal storage is used for storing large amounts of private data,
while shared preferences are used for storing small amounts of simple data.
 Scope: Internal storage is private to the application and not visible to other
applications or users, while shared preferences are private to the
application but can be accessed by other applications if they have the same
user ID.
 Functionality: Internal storage provides file-based access to stored data,
while shared preferences provide key-value access to stored data.

It is important to note that both internal storage and shared preferences


have their own advantages and limitations, and the choice between them
depends on the specific use case and the type of data that needs to be
stored.

You might also like