Simultaneously Read and Write in File using AsyncTask Class

AsyncTask is really useful Feature Provided by Android For Doing Back Ground Task without interrupting users. AsyncTask is useful to perform Small operation like Submit user data to the server or Download some information from Server or Write content to the files etc. There are number of uses of AsyncTask in android. one of the Best use is when you download something and progress dialog apper showing you the percentage of download is done is done with help of Async Task.

Today in this Tutorial i am going to use AsyncTask Class to read and write content in file Simultaneously. you can use this for creating your own  Key board application also because Keyboard app also using AsyncTask for predicting next keyword. Asynctask class having 3 main methods that allow you to do background work but you have to override doInBackground() method (must).

  • onPreExecute() - if you want to Perform certain operation before doInBackground method then you can set those things in this method.
  • doInBackGround() - write down the main operation you want to perform in back ground. this method is call when you call execute method of AsyncTask class.
  • onPostExecute() - After doInBackground method the operation or changes you want to perform on UI. for example Progress dialog dismiss or status change etc.
In this tutorial i have merged two things Read and Write in Text file and AsyncTask. because there are number of tutorial available For File Read and Write and Async task. but how to combine both and make use of both for our own requirements. Go through full tutorial and you will get how you can use it in your application.

Steps
  • Create New Project and Name it FileRead.
  • Now Go to main.xml File And Paste the below code.
main.xml



    

        

        
    

    

    

  • I have Uploaded Screen shot below so check out how how it looks.
  • Now go to Main.java file and Paste below code
Main.java
package com.androprogrammer.fileread;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 TextView content;
 EditText text;
 Button ok;
 static String FILENAME = "test.txt";
 File file;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  setIds();
  file = new File(getFilesDir(), FILENAME);

  try {
   if (file.createNewFile()) {
    Toast.makeText(getApplicationContext(), "File Created",
      Toast.LENGTH_LONG).show();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  ok.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    String value = text.getText().toString();
    text.setText("");

    readFromFile rf = new readFromFile(file);
    rf.execute(value);
   }
  });

 }

 public void setIds() {
  content = (TextView) findViewById(R.id.textView);
  text = (EditText) findViewById(R.id.editText);
  ok = (Button) findViewById(R.id.button);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 private class readFromFile extends AsyncTask <String, Integer, String > {

  // static String FILENAME = "test.txt";
  File f;

  public readFromFile(File f) {
   super();
   this.f = f;
   // TODO Auto-generated constructor stub
  }

  @Override
  protected String doInBackground(String... str) {
   String enter = "\n";
   FileWriter writer = null;
   try {
    writer = new FileWriter(f,true);
    writer.append(str[0].toString());
    writer.append(enter);
    writer.flush();

   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } finally {
    try {
     writer.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   return null;

  }

  @Override
  protected void onPostExecute(String s) {
   super.onPostExecute(s);
   String name = "";
   StringBuilder sb = new StringBuilder();
   FileReader fr = null;

   try {
    fr = new FileReader(f);
    BufferedReader br = new BufferedReader(fr);
    while ((name = br.readLine()) != null) {
     sb.append(name);
    }
    br.close();
    fr.close();
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   content.setText(sb.toString());
  }

 }

In the above coding i have created setIds method for setting references and this is coding methodology followed by all Developers and companies.if you follow certain methods of coding your coding style will improve and it is very beneficial for you. one more thing i have Created File in onCreate Method and pass it in AsyncTask class For read and write because from it Some times it gives error and force close app so you can't bear it when you application is online.

Screen Shots






now its your turn lets run the project and check it is working or not. i have compiled and run the project so i hope no error will come but if any post it in below comment section. 
Keep coding ....

0 comments :

Post a Comment