Android Temporarily writing and reading files to cache directory

September 18, 2012
By

Cache directory is the application specific directory on the file system where the files in this directory get deleted first when the device runs low on storage.

In this article, we will create an Android application which allows users to input some content into an EditText widget and store those content in a file located in the temporary directory or cache directory. When the application restarts, the contents will be restored from the cache directory if the file exists.

This application is developed in Eclipse ( 4.2.0 ) and ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ).


1. Create a new Android application project namely “FileReadWriteCache”

Create a new Android Application Project

Figure 1 : Create a new Android Application Project


2. Design application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android Support library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>

    <string name="app_name">FileReadWriteCache</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Cache Directory Demo</string>
    <string name="str_btn_save">Save</string>
    <string name="str_hnt_et_content">Enter Content here</string>

</resources>


7. Update the layout activity_main in the file res/layout/activity_main.xml


<RelativeLayout 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" >

    <EditText
        android:id="@+id/et_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:hint="@string/str_hnt_et_content"
        android:minLines="4"
        android:maxLines="4" />

    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_content"
        android:layout_centerHorizontal="true"
        android:text="@string/str_btn_save" />

</RelativeLayout>


8. Update the class MainActivity in the file src/in/wptrafficanalyzer/filereadwritecache/MainActivity.java


package in.wptrafficanalyzer.filereadwritecache;

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.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private final String TEMP_FILE_NAME = "wpta_temp_file1.txt";
    EditText etContent;
    File tempFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Getting reference to btn_save of the layout activity_main */
        Button btnSave = (Button) findViewById(R.id.btn_save);

        /** Getting Cache Directory */
        File cDir = getBaseContext().getCacheDir();

        /** Getting a reference to temporary file, if created earlier */
        tempFile = new File(cDir.getPath() + "/" + TEMP_FILE_NAME) ;

        /** Getting reference to edittext et_content */
        etContent = (EditText) findViewById(R.id.et_content);

        String strLine="";
        StringBuilder text = new StringBuilder();

        /** Reading contents of the temporary file, if already exists */
        try {
            FileReader fReader = new FileReader(tempFile);
            BufferedReader bReader = new BufferedReader(fReader);

            /** Reading the contents of the file , line by line */
            while( (strLine=bReader.readLine()) != null  ){
                text.append(strLine+"\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

        /** Setting content from file */
        etContent.setText(text);

        /** Defining click event listener for the button btn_save */
        OnClickListener saveClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {

                FileWriter writer=null;
                try {
                    writer = new FileWriter(tempFile);

                    /** Saving the contents to the file*/
                    writer.write(etContent.getText().toString());

                    /** Closing the writer object */
                    writer.close();

                    Toast.makeText(getBaseContext(), "Temporarily saved contents in " + tempFile.getPath(), Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        /** Setting the click event listener for the button btn_save */
        btnSave.setOnClickListener(saveClickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


9. Screenshot of the application

Saving contents to a file located in cache directory

Figure 5 : Saving contents to a file located in cache directory


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: ,

5 Responses to Android Temporarily writing and reading files to cache directory

  1. D on April 16, 2014 at 12:42 pm

    Does this require to add WRITE_EXTERNAL_STORAGE permission?

  2. Cute boy on November 22, 2014 at 2:29 am

    Thank very much :)

  3. Mustaner on May 21, 2015 at 6:38 pm

    can you please explain how to store images and text in cache when activity pause/destroy and restore them on create/resume.. instead of making request to the server?thanks

  4. A on July 15, 2015 at 12:12 pm

    how to delete temporarily cache?

  5. parthi on January 14, 2016 at 12:39 pm

    Hi, I need requirement to store files in external cache directory.Not in internal cache directory. How is this possible. kindly help me. Thanks in advance.

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner