Skip to main content

Save data into file

To save data into file in an android application, you have to follow the steps given bellow.

1. Create an object of the FileOutputStream class using the openFileOutput method.
    Example :  
                   FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);
  
   Here text.txt is the name of the file. You can use any of the file opening mode
   a.    MODE_PRIVATE  :  File is accessible by only the application that create it.
   b.    MODE_APPEND :  Appending an existing file.
   c.    MODE_WORLD_WRITABLE : Allow write permission to all the applications. 

2. Get an object of the OutPutStreamWriter class using the FileOutputStream object.
    Example:
                 OutputStreamWriter osw = new OutputStreamWriter(fou);

3. Write the data using the write() method.
   Example:
                 osw.write(Message);

4. For reading the data from the file, first you need to create an object of the FileInputStream class.
   Example:
                 FileInputStream fis = openFileInput("text.txt");

5. Get an object of the InputStreamReader class .
   Example:
                InputStreamReader isr = new InputStreamReader(fis);

6. Finally read the data from the file as separate block of data having fixed size.

             





activity_main.xml
1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2:    xmlns:tools="http://schemas.android.com/tools"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"  
5:    android:paddingBottom="@dimen/activity_vertical_margin"  
6:    android:paddingLeft="@dimen/activity_horizontal_margin"  
7:    android:paddingRight="@dimen/activity_horizontal_margin"  
8:    android:paddingTop="@dimen/activity_vertical_margin"  
9:    tools:context=".MainActivity" >  
10:    <EditText  
11:      android:id="@+id/msg"  
12:      android:layout_width="wrap_content"  
13:      android:layout_height="wrap_content"  
14:      android:layout_alignParentTop="true"  
15:      android:layout_centerHorizontal="true"  
16:      android:layout_marginTop="20dp"  
17:      android:ems="10"   
18:      android:hint="Enter a message"  
19:      >  
20:      <requestFocus />  
21:    </EditText>  
22:    <Button  
23:      android:id="@+id/LOAD"  
24:      android:layout_width="wrap_content"  
25:      android:layout_height="wrap_content"  
26:      android:layout_alignLeft="@+id/SAVE"  
27:      android:layout_below="@+id/SAVE"  
28:      android:layout_marginTop="46dp"  
29:      android:text="LOAD DATA" />  
30:    <Button  
31:      android:id="@+id/SAVE"  
32:      android:layout_width="wrap_content"  
33:      android:layout_height="wrap_content"  
34:      android:layout_below="@+id/msg"  
35:      android:layout_centerHorizontal="true"  
36:      android:layout_marginTop="23dp"  
37:      android:text="SAVE DATA" />  
38:  </RelativeLayout>  

MainActivity.java
1:  package com.filedemo;  
2:  import java.io.FileInputStream;  
3:  import java.io.FileNotFoundException;  
4:  import java.io.FileOutputStream;  
5:  import java.io.IOException;  
6:  import java.io.InputStreamReader;  
7:  import java.io.OutputStreamWriter;  
8:  import android.app.Activity;  
9:  import android.os.Bundle;  
10:  import android.view.Menu;  
11:  import android.view.View;  
12:  import android.view.View.OnClickListener;  
13:  import android.widget.Button;  
14:  import android.widget.EditText;  
15:  import android.widget.Toast;  
16:  public class MainActivity extends Activity {  
17:       Button save,load;  
18:       EditText message;  
19:       String Message;  
20:       int data_block = 100;  
21:       @Override  
22:       protected void onCreate(Bundle savedInstanceState) {  
23:            super.onCreate(savedInstanceState);  
24:            setContentView(R.layout.activity_main);  
25:            save=(Button) findViewById(R.id.SAVE);  
26:            load = (Button) findViewById(R.id.LOAD);  
27:            message = (EditText) findViewById(R.id.msg);  
28:            save.setOnClickListener(new OnClickListener() {  
29:                 @Override  
30:                 public void onClick(View v) {  
31:                      // TODO Auto-generated method stub  
32:                      Message = message.getText().toString();  
33:                      try {  
34:                           FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);  
35:                           OutputStreamWriter osw = new OutputStreamWriter(fou);  
36:                           try {  
37:                                osw.write(Message);  
38:                                osw.flush();  
39:                                osw.close();  
40:                                Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_LONG).show();  
41:                           } catch (IOException e) {  
42:                                // TODO Auto-generated catch block  
43:                                e.printStackTrace();  
44:                           }  
45:                      } catch (FileNotFoundException e) {  
46:                           // TODO Auto-generated catch block  
47:                           e.printStackTrace();  
48:                      }  
49:                 }  
50:            });  
51:            load.setOnClickListener(new OnClickListener() {  
52:                 @Override  
53:                 public void onClick(View v) {  
54:                      // TODO Auto-generated method stub  
55:                 try {  
56:                      FileInputStream fis = openFileInput("text.txt");  
57:                      InputStreamReader isr = new InputStreamReader(fis);  
58:                      char[] data = new char[data_block];  
59:                      String final_data="";  
60:                      int size;  
61:                      try {  
62:                           while((size = isr.read(data))>0)  
63:                           {  
64:                           String read_data = String.copyValueOf(data, 0, size);       
65:                           final_data+= read_data;  
66:                           data = new char[data_block];  
67:                           }  
68:                           Toast.makeText(getBaseContext(), "Message :"+final_data, Toast.LENGTH_LONG).show();  
69:                      } catch (IOException e) {  
70:                           // TODO Auto-generated catch block  
71:                           e.printStackTrace();  
72:                      }  
73:                 } catch (FileNotFoundException e) {  
74:                      // TODO Auto-generated catch block  
75:                      e.printStackTrace();  
76:                 }       
77:                 }  
78:            });  
79:       }  
80:       @Override  
81:       public boolean onCreateOptionsMenu(Menu menu) {  
82:            // Inflate the menu; this adds items to the action bar if it is present.  
83:            getMenuInflater().inflate(R.menu.main, menu);  
84:            return true;  
85:       }  
86:  }  


Comments

Popular posts from this blog

Android Swipe Views with Tabs

In this post we are going to learn about how to integrate the android tab view with the fragments using ViewPager and ActionBar class. For displaying the tabs on the top of the screen you need to interact with the android action bar, this is because the tab views is connected with the action bar. Ads by Google In this example application we make three tabs called "java", "php" and ".Net" and there are three seperate fragement view for each of these tabs. First you need to add the ViewPager into the activity_main.xml file. <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v4.view.ViewPager> Now create three layout files for the fragments. 1. java_layout.xml <?xml version="1.0" encod

Android MySQL Database Operations

In this post we are going to learn about how to connect to MySQL Database from your Android Application and perform database operations. Here we create an android app that contain some login Activity through which the user can retrieve information from database and a registration Activity through which the user can add information into the database.  First you need to have the following components installed in your development machine.  1. Database : Here we use the MySQL database. 2. Web Server : Here we use the Apache Web Server. 3. Server side Scripting Language :   Here we use PHP for server side scripting. 4. Android Development environment : You must install android sdk and android studio.   I recommend you to download and install WAMPSERVER. The wamp server installer contains the following components. Apache Server Application MySQL Database PHP/phpMyAdmin First we have to create the database and table in MySQL. You can use the phpMyAdmin for mange yo

"please correct the errors on this form" adsense error simple solution

Many of the bloggers now facing the problem with their adsense widgets. Whenever try to add the new  adsense link unit using the blogger widgets, it shows the error " please correct the errors on this form " as shown bellow. In blogger you can add the adsense units in two ways. First one is adding the adsense using the blogger widgets(Most of the beginners doing this) and the second method is to obtain the adsense code from the adsense login page and place it into the targeted position on the blog. To improve the revenue from adsense you have to place the appropriate ad unit into the right position. The adsense link units are very important for increasing the adsense revenue. So due to this error many of the bloggers are unable to place the link units.  Here is the solution for the problem. 1. Login into your adsense and blogger account. 2. Now make sure that only two adsense widgets (units) are present on your blog, this is because Google allows onl