How to save user data Persistently in File in Android

person folder_openAndroidaccess_time May 22, 2015

In this tutorial we are going to show how to save user data persistently in file in Android.You can store the data persistently in a file in the internal memory of the Android device by either creating a textfile during the runtime or creating a static resource.
See flowing Steps :

  1. First it will create one Textfile ( Eg : friends_details.txt) by OpenFileOutput(“friends_details.txt”, MODE_PRIVATE). This will create the textfile in given name.
  2. MODE_PRIVATE is used to creates or replaces the file that would be private for your application.
  3. MODE_APPEND is used to allows you to write data to the end of the file,provided the file already exists.

1. Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.datapersistentfile"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.stackandroid.datapersistentfile.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>

2. Activity layout file

<LinearLayout 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:orientation="vertical"
    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="com.stackandroid.datapersistentfile.MainActivity" >
    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="User Name:"
        android:textSize="16sp" />
    <EditText
        android:id="@+id/edName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="enter name"
        android:textSize="16sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/txtAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="User Age:"
        android:textSize="16sp" />
    <EditText
        android:id="@+id/edAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="enter age"
        android:textSize="16sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/txtSex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="User Sex:"
        android:textSize="16sp" />
    <EditText
        android:id="@+id/edSex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="enter user sex"
        android:textSize="16sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/txtMail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="User Mail:"
        android:textSize="16sp" />
    <EditText
        android:id="@+id/edMail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="enter user mail"
        android:textSize="16sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/submitDetail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:gravity="center"
        android:text="Store data in File"
        android:textSize="18dp" />
</LinearLayout>
 

This xml file is in res–>menu–>main.xml . It will show the icon in ActionBar.

 <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.datapersistentfile.MainActivity" >
    <item
        android:id="@+id/viewdata"
        android:icon="@drawable/data"
        android:showAsAction="always"
        android:title="View Data"/>
</menu>

3. Main Activity code

package com.stackandroid.datapersistentfile;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.datapersistentfile.R;
public class MainActivity extends Activity {
	EditText editName, editAge, editSex, editMail;
	Button btnSubmit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		editName = (EditText) findViewById(R.id.edName);
		editAge = (EditText) findViewById(R.id.edAge);
		editSex = (EditText) findViewById(R.id.edSex);
		editMail = (EditText) findViewById(R.id.edMail);
		btnSubmit = (Button) findViewById(R.id.submitDetail);
		btnSubmit.setOnClickListener(new OnClickListener() {
			String detail;
			@Override
			public void onClick(View v) {
				if (editName.getText().toString() != ""
						&& editSex.getText().toString() != "") {
					detail = editName.getText().toString() + " , "
							+ editAge.getText().toString() + " , "
							+ editSex.getText().toString() + " , "
							+ editMail.getText().toString() + "-";
				} else {
					Toast.makeText(getApplicationContext(), "Fill all details",
							Toast.LENGTH_LONG).show();
				}
				try {
					FileOutputStream fout = openFileOutput(
							"friends_details.txt", MODE_APPEND);
					OutputStreamWriter outstr = new OutputStreamWriter(fout);
					outstr.write(detail);
					outstr.flush();
					outstr.close();
					fout.close();
					Toast.makeText(getApplicationContext(),
							"Data inserted" + getFilesDir(), Toast.LENGTH_LONG)
							.show();
					editName.setText("");
					editAge.setText("");
					editMail.setText("");
					editSex.setText("");
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.viewdata:
			try {
				viewData();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	private void viewData() throws IOException {
		FileInputStream fis = openFileInput("friends_details.txt");
		InputStreamReader isr = new InputStreamReader(fis);
		BufferedReader bufferedReader = new BufferedReader(isr);
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			sb.append(line);
			seperatorDialog(line.toString());
		}
	}
	private void seperatorDialog(String sb) {
		String[] temp;
		String delimiter = "-";
		temp = sb.split(delimiter);
		StringBuilder sb1 = new StringBuilder();
		for (int i = 0; i < temp.length; i++)
			sb1.append(temp[i] + "\r\n ");
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.viewdata);
		dialog.setTitle("Read data from textfile ");
		TextView text = (TextView) dialog.findViewById(R.id.viewData);
		text.setText(sb1.toString());
		dialog.show();
	}
}

4. Demonstration

datapersistent_1
datapersistent_1

Here we entered the data and submit that to store in textfile.

datapersistent_2
datapersistent_2

Here the data inserted successfully in that textfile.

datapersistent_3
datapersistent_3

This screen shows the data what we stored in the textfile while clicking image in Actionbar.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">