Thursday, March 26, 2015

Read or Write a serializable ArrayList into a text file in android

You can save your ArrayList in a File and can fetch when needed and its a good practice to not using sharedprefrence for large files,You can use Sqllite database or you can save them in a file for better performance.

Use this method to write a serializable Arraylist in a file 



public static void write(Context context, Object nameOfClassGetterSetter) {
File directory = new File(context.getFilesDir().getAbsolutePath()
+ File.separator + "serlization");
if (!directory.exists()) {
directory.mkdirs();
}

String filename = "AnyName.srl";
ObjectOutput out = null;

try {
out = new ObjectOutputStream(new FileOutputStream(directory
+ File.separator + filename));
out.writeObject(nameOfClass);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


this method will simply write your arrayList at defined location

For eg:

                write(context, ArrayList<getterSetter> );


Use this method to read serializable Arraylist from a file :


                                                                     (type)
public static ArrayList<getterSetterclass> read(Context context) {

ObjectInputStream input = null;
ArrayList<getterSetterclass> ReturnClass = null;
String filename = "AnyName.srl";
File directory = new File(context.getFilesDir().getAbsolutePath()
+ File.separator + "serlization");
try {

input = new ObjectInputStream(new FileInputStream(directory
+ File.separator + filename));
ReturnClass = (ArrayList<getterSetterclass>) input.readObject();
input.close();

} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ReturnClass;
}


this method will return a arrayList with saved data.

For eg:
          ArrayList<getterSetterclass> list =  read(context);





0 comments:

Post a Comment

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design