Thursday, May 31, 2012

How to store ArrayList in File exmaple in android




Array List stored/ synchronized with Object File instead of using Sqlite Database.

Purpose:
The Array List Object stored into file as Object File permanently. The Array List object initializes with the Object File. So for this method we are avoiding following problems.

  • No needs to use the SQlite Database for the entire Array list storage.
  • No need to read the Text file and parse and load into the Array list, if we are storing as normal text file.

Source Code:

package cem.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity {
      final static int READ=1;
      final static int WRITE=2;
      private List<HashMap<String, String>> ListMaps=
            new ArrayList<HashMap<String, String>>();
      private String FileName="CData";
      private String F_Path="";
     
      Button add_b,save_b;
      EditText d_name_et;
      TextView dip_tv;
     
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        add_b =(Button)findViewById(R.id.d_add);
        d_name_et=(EditText)findViewById(R.id.d_name);
        save_b =(Button)findViewById(R.id.d_save);
        test_b=(Button)findViewById(R.id.d_test);
        add_b.setOnClickListener(ButtonClickL);
        save_b.setOnClickListener(ButtonClickL);       
        dip_tv =(TextView)findViewById(R.id.d_dip);
       // F_Path=this.getApplicationContext().getFilesDir().getParent()+"/"+FileName;
        F_Path=FileName;
        Log.d("F_Path", " File Path :"+F_Path);
        load_data();
       
    }
   
   
    public void Add_Data(){
      Log.d("Add", "Add Data Calling");        
      HashMap<String, String> map= new HashMap<String, String>();        
      map.put("Name",d_name_et.getText().toString() );
      ListMaps.add(map);
      d_name_et.setText("");
      Disp_Data();
    }
    public void Save_Data(){
      Log.d("Save", "Save Data Calling");
     
      try {
                  writeListToFile((ArrayList<HashMap<String, String>>) ListMaps);
            } catch (Exception e) {
                  Log.d("Save", "writeListToFile  call error");
            }

    }
   
    public void Disp_Data(){
      Log.d("Disp_Data()", "Disp_Data() Calling--->");
      String CurData="";
      for (int i=0; i < ListMaps.size();i++){
            HashMap<String, String> map=ListMaps.get(i);
            CurData =CurData+map.get("Name")+"\n";
      }
     
      dip_tv.setText(CurData);     
    }
   
           
    public void load_data(){
      if(loadListFromFile((ArrayList<HashMap<String, String>>) ListMaps) !=
            null){
            ListMaps = loadListFromFile((ArrayList<HashMap<String, String>>)
                        ListMaps);
      }
     
      Disp_Data();
    }
   
    public void File_Read_Write(int type){
      if (type==READ){
           
      }else if (type==WRITE){
           
      }
    }
   
    private void writeListToFile(ArrayList<HashMap<String, String>> masterlistrev){
      if(null == FileName)
          throw new RuntimeException ("FileName is null!");

        File myfile = getFileStreamPath(FileName);
        try {
            if(myfile.exists() || myfile.createNewFile()){
                FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(masterlistrev);
                fos.close();
            }
        } catch (Exception e) {
         e.printStackTrace();
        }

     }

    private ArrayList<HashMap<String, String>> loadListFromFile(

         ArrayList<HashMap<String, String>> masterlistrev) {
      if(null == FileName)
          return null;
     
      File myfile = getFileStreamPath(FileName);
      try {
            if(myfile.exists()){
                  FileInputStream fis = openFileInput(FileName);
                  ObjectInputStream ois = new ObjectInputStream(fis);
                  masterlistrev = (ArrayList<HashMap<String, String>>) ois.readObject();
                  fis.close();
            }else {
                  return null;
            }
       } catch (Exception e) {
          e.printStackTrace();
       }
       return masterlistrev;
      }
   


    private OnClickListener ButtonClickL= new OnClickListener() {
      public void onClick(View v) {
            if(v==add_b){
                  Add_Data();
            }else if(v== save_b){
                  Save_Data();
            }
      }
    };
}



7 comments:

  1. Thank U for the useful info...

    ReplyDelete
  2. Hello Ashok. Would this method be applicable if I want to use an ArrayList consisting of custom objects? My object is a mix of booleans and floats and its stored in an ArrayList.

    ReplyDelete
  3. Say any array list as Object and Stored that object into the file

    ReplyDelete
  4. nice also check this out if you want to read write and delete using random access http://androidjavaio.blogspot.co.uk/2014/01/a-simple-android-java-io-class-using.html

    ReplyDelete
  5. how to implement Sqlite arratlist data store to .txt file?

    ReplyDelete
  6. This code is insanely sloppy.

    ReplyDelete