Code to create .txt file in SDCard , and store data in .txt file and read data from .txt file in Android.

Note: here in my requirement iam facing some problem while opening the .txt file . because whenever I tried to open .txt file , its showing all supported applications to open that file (like Office suite, Think office , Basic Html..).But I need to directly open the .txt file without showing any option.
For that iam doing showing the text in EditText after getting text from .txt file and inserting the text in .txt file after enter and submit the text in Edittext.code looks like this :

In your MainActivity put this below code  ,after button click we will create the text file and invoke the other screen. Like this :


openDocLayout= (LinearLayout) findViewById(R.id.openDocLayout);
                  openDocLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {                        
                              System.out.println("-------file path---------"+Globals.DOC_FILE_PATH);
                              File file=new File(Globals.DOC_FILE_PATH);
                             
                              if(!file.exists()){
                                    System.out.println("--------file not exists-----------");
                                    try {
                                          OutputStream fo = new FileOutputStream(file);
                                          Writer out = new OutputStreamWriter(fo, "UTF-7");
                                          //out.write(buffer.toString());
                                          out.close();
                                          fo.close();
                                }
                                catch (IOException e) {
                                    Log.e("", "File write failed: " + e.toString());
                                }
                              }                      
                             
                               if(file.exists()){                                  
                                     System.out.println("--------file exists-----------");
                                     startActivity(new Intent(UtilMenu.this, FileEnteredEditText.class));                           
                               }                           
                        }
                  });

Create Activity like this :
And use this variable : Globals.DOC_FILE_PATH=”/mnt/sdcard2/ApplnData/notes.txt”;

FileEnteredEditText.java:

package com.sfa_test;

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.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class FileEnteredEditText extends Activity{
      ProgressDialog progressDialog=null;
      EditText fileEditText=null;
      RelativeLayout enterTextMainLayout=null;
     
     
      @Override
      protected void onCreate(Bundle savedInstanceState) {       
            super.onCreate(savedInstanceState);
            setContentView(R.layout.enter_text_file);
           
            getAllIds();
           
            fileOperations(true,"Please Wait Gathering Data..!!");
      }
     
      private void getAllIds() {
            // TODO Auto-generated method stub
            fileEditText=(EditText)findViewById(R.id.fileEditText);    
            enterTextMainLayout=(RelativeLayout)findViewById(R.id.enterTextMainLayout);
            enterTextMainLayout.setOnClickListener(new View.OnClickListener() {                
                  @Override
                  public void onClick(View v) {
                        System.out.println("--------layout clicked------------");
                        // TODO Auto-generated method stub
                        InputMethodManager inputMethodManager = (InputMethodManager) FileEnteredEditText.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
                      inputMethodManager.hideSoftInputFromWindow(FileEnteredEditText.this.getCurrentFocus().getWindowToken(), 0);
                  }
            });
      }

      public void finishEnterEditText(View v){
            try {
                  fileOperations(false,"Please wait Saving data into File..!");
            } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }
     
      public void backBtnClick(View v){
            finish();
      }
     
     
      private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(Globals.DOC_FILE_PATH));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("TAG", "File write failed: " + e.toString());
        }       
    }

    private String readFromFile() {        
        String ret = "";        
        try {
            //InputStream inputStream = openFileInput(Globals.DOC_FILE_PATH);
            
           // if ( inputStream != null ) {
                //InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(Globals.DOC_FILE_PATH)));
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();
                
                while ( (receiveString = bufferedReader.readLine()) != null ) {                     
                    stringBuilder.append(receiveString);
                    stringBuilder.append("\n");
                }                
               // inputStream.close();
                ret = stringBuilder.toString();
           // }
        }
        catch (FileNotFoundException e) {
            Log.e("TAG", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("TAG", "Can not read file: " + e.toString());
        }
        return ret;
    }
   
    public void fileOperations(final boolean isReadFromFile,String progressMessage){
     
      progressDialog=ProgressDialog.show(this, "", progressMessage);         
            AsyncTask<Void, Void, Void> asyncTask=new AsyncTask<Void, Void, Void>(){

                  protected void onPreExecute() {
                        if(progressDialog.isShowing()){
                              progressDialog.dismiss();                            
                        }
                        progressDialog.show();
                  };
                 
                  @Override
                  protected Void doInBackground(Void... params) {
                        // TODO Auto-generated method stub
                        if(isReadFromFile){                            
                        runOnUiThread(new Runnable() {                             
                              @Override
                              public void run() {
                                    // TODO Auto-generated method stub
                                    fileEditText.setText(readFromFile()+" ");
                              }
                        });              
                        }else{
                              writeToFile(fileEditText.getText().toString());
                        }                      
                        return null;
                  }
                 
                  protected void onPostExecute(Void result) {
                        if(isReadFromFile){
                              progressDialog.dismiss();
                        }else{
                              progressDialog.dismiss();
                              finish();
                        }
                  };               
            };         
            asyncTask.execute((Void[])null);
    }
   
   

}

-------------------------------
enter_text_file.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/enterTextMainLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:clickable="true" >

    <!--
    <ScrollView android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    -->

    <RelativeLayout
        android:id="@+id/reltivLoutSub"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_marginRight="-15dip"
        android:background="@drawable/greenbg" >

        <Button
            android:id="@+id/backButton11"
            android:layout_width="80dip"
            android:layout_height="35dip"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:layout_marginLeft="15dip"
            android:background="@drawable/back"
            android:onClick="backBtnClick" />

        <com.sfa_test.CusFntTextView
            android:id="@+id/tvNotesTitle"
            android:layout_width="300dp"
            android:layout_height="40dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="300dp"
            android:gravity="center"
            android:text="Notes"
            android:textColor="@android:color/white"
            android:textSize="11pt" />

        <Button
            android:id="@+id/button1"
            android:layout_width="80dip"
            android:layout_height="35dip"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:layout_marginRight="30dip"
            android:background="@drawable/save"
            android:onClick="finishEnterEditText" />
    </RelativeLayout>

    <View
        android:id="@+id/viewId"
        android:layout_width="fill_parent"
        android:layout_height="2dip"
        android:layout_below="@+id/reltivLoutSub"
        android:background="@color/greentext" />

    <!--
    <EditText
        android:id="@+id/fileEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:padding="10dip"
        android:text="sdfsdf"
        android:gravity="top"
        android:minHeight="400dip"       
        android:scrollbars="vertical"
        android:background="#00000000"
        android:inputType="textMultiLine"
        >
        <requestFocus />
    </EditText>
    -->

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/viewId"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="15dip"
        android:fillViewport="true" >

        <EditText
            android:id="@+id/fileEditText"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:background="@anim/border"
            android:ellipsize="end"
            android:fadeScrollbars="false"
            android:gravity="top|left"
            android:inputType="textMultiLine"
            android:padding="10dip"
            android:scrollbarStyle="outsideOverlay"
            android:scrollbars="vertical"
            android:textColor="@color/black" >

            <requestFocus />
        </EditText>
    </ScrollView>

    <!--
    </LinearLayout>
    </ScrollView>
    -->

</RelativeLayout>
Border.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >   
<solid android:color="#ffffff" />   
<stroke android:width="1dip" android:color="#000d0f"/>   
</shape>
--------------------------------------------------
In AndroidManifest.xml:
<activity android:name=".FileEnteredEditText"
                  android:theme="@android:style/Theme.Translucent.NoTitleBar"
                  ></activity>



Comments

Popular posts from this blog

Custom Dialog with no title and full screen in Android

code to display .pdf,.text,.DOC,.DOCX,.doc extension files exists in SDCard

Best working code to set Date limits on Date Picker Dialog,in Android