Android: Write and Get Object - android

I want to write a serializable object to file in internal memory. Then, I want to load that object back from that file later. How could I do this in Android?

First of all your object must implement Serializable. Don't forget to add a serialVersionUID on the serializable class.
Then if you don't want to save specific field of the object mark it as transient.
Be sure all fields are serializable.
Next create a file in the internal memory and create an ObjectOutputStream to save your object. If you want to save in a specific folder you can create a path like this:
File path=new File(getFilesDir(),"myobjects");
path.mkdir();
Then you can use that path to save your object:
File filePath =new File(path, "filename");
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
Reading is similar:
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);
MyObjectClass myObject = (MyObjectClass ) in.readObject();
in.close();

Related

How to serialize hashmap in android

I want to serialize and deserialize very big hashmaps in android.
I'm using this code:
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(map);
objectOutputStream.close();
fileOutputStream.close();
But the output file I get is very big (300MB). How can I reduce the size?
I tried serializing a json string instead, that minimized it to about 150MB which is still way too big .

Android: ObjectInputStream throws ClassCastException when reading arraylist

I have an arraylist of a certain POJO object that implements serializable. When I write the object to disk I do it like so:
File outputDir = context.getCacheDir();
File outputFile = new File(outputDir, getCacheKey() );
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
oos.writeObject(arraylistOfMyObjects);
oos.close();
and when I later want to read back this list into an arraylist of the object, I do it like so:
File outputDir = context.getCacheDir();
File outputFile = new File(outputDir, getCacheKey() );
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(outputFile)));
final ArrayList<myObject> list = (ArrayList<myObject>) ois.readObject();
ois.close();
I'm receiving frequent exceptions on the line where I cast the inputstream to an arraylist, with the error looking like this:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.io.ObjectStreamClass
Why are these errors occurring and how can I change my code to resolve them?
Interestingly enough the error doesn't occur every time I run the app, but only every now and again for whatever weird reason.
Make sure you're writing and reading your objects back in the same order every time. In my case I realized I was writing to the file with optional parameters like this:
if(cacheAllItems) { // <-- BREAKS READING FILE WHEN FALSE
objectOutputStream.writeObject(itemsList);
objectOutputStream.writeObject(itemNamesList);
}
objectOutputStream.writeObject(currentItem);
Then I was attempting to read the file with:
itemsList = (ArrayList<Item>) objectInputStream.readObject(); // MIGHT NOT EXIST
itemNames = (ArrayList<String>) objectInputStream.readObject(); // MIGHT NOT EXIST
currentItem = (Item) objectInputStream.readObject();
So if I had last run my cacheItems() function with the cacheAllItems = true, everything worked fine, but if it had last run just saving currentItem, the readObject() attempted to read the one object as the list that should come first.

how to read/write data dictionary in android programmatically

I want to read/write data dictionary in file which is in android internal/external memory. In WP7, they have used IsolatedStorage for storing the dictionary directly. In IOS, they can write NSDictionary directly to the file. Please anyone tell me the way to write DataDictionary into file.
Note: I have the keys and values in the Map variable.
how to store this Map directly to file
I would suggest putting your words into a database for the following reasons
DB lookups on android with SQLite are "fast enough" (~1ms) for even
the most impatient of users
Reading large files into memory is a dangerous practice in
memory-limited environments such as android.
Trying to read entries out of a file "in place" rather than "in
memory" is effectively trying to solve all the problems that SQLite
already solves for you.
Embed a database in the .apk of a distributed application [Android]
You can find more detailed examples by searching object serialization
[EDIT 1]
Map map = new HashMap();
map.put("1",new Integer(1));
map.put("2",new Integer(2));
map.put("3",new Integer(3));
FileOutputStream fos = new FileOutputStream("map.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(map);
oos.close();
FileInputStream fis = new FileInputStream("map.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Map anotherMap = (Map) ois.readObject();
ois.close();
System.out.println(anotherMap);
[EDIT 2]
try {
File file = new File(getFilesDir() + "/map.ser");
Map map = new HashMap();
map.put("1", new Integer(1));
map.put("2", new Integer(2));
map.put("3", new Integer(3));
Map anotherMap = null;
if (!file.exists()) {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(map);
oos.close();
System.out.println("added");
} else {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
anotherMap = (Map) ois.readObject();
ois.close();
System.out.println(anotherMap);
}
} catch (Exception e) {
}
[EDIT 3]
Iterator myVeryOwnIterator = meMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
// check for value
}
I'm unsure if using SharedPreferences (link) is something that is suitable for your usecase.
You store via a key-value pair, and can have multiple SharedPreferences per application. While both are stored as String objects, the value can be automatically cast to other primitives using built in methods.
Mark Murphy has written a library, cwac-loaderex (link), to facilitate access of SharedPreferences via the use of the Loader pattern (link), which offsets some of the work you need to do to keep IO off the main thread.

store object file when phone is shutted down and retrieve the file when the phone is rebooted

I have saved an object of a class in a file in my application, when the phone shuts down, what happens to the file? I think, the file get lost. because after reboot my phone, I get null values(which are saved in some variables in the class object) from the file. How can I make sure that, the file will not get lost if the phone is shutted down. Is it possible?
You may try this code:
String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
And make sure you have declared the permission in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You are better off using Preferences. Writing to external storage is generally a bad idea. Use SharedPreferences to save the state of the object and instantiating that object again with the data you saved.
SharedPreferences API
first i serialize my class like:
public class MyStore implements Serializable {
//this serialVersionUID will automatically generate
private static final long serialVersionUID = 3487640153579137276L;
......
......
}
then i have saved the object in internal memory like this:
File path = new File(getActivity().getFilesDir(), foldar_name);
path.mkdirs();
File file = new File(path,file_name);
file.createNewFile();
MyStore myStore = new MyStore();
myStore.setData(my_data);
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fout);
os.writeObject(myStore);
os.flush();
os.close();

Saving a string serialized and buffered android JAVA.IO ObjectInputStream

I am saving out and loading mixed data types. I either have the saving part wrong or the loading part wrong. I am using buffered serial save and load method.
Variable lastFetchDate is defined as a string and initialized as "00/00/00".
It throws an error when reloading the data after it has been saved. What is wrong? I would have thought the opposite to writeBytes would be readBytes for a string.
Saving is as follows:
FileOutputStream fos = new FileOutputStream("userPrefs.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeBytes(lastFetchDate);
// I close all streams
Loading is as follows:
FileInputStream fis = new FileInputStream("userPrefs.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
lastFetchDate=(String)ois.readObject(); //<<<<< Error thrown here
// I close all streams
You have written string as byte[] so need to read as byte[]
byte [] bString = new byte[lastFetchDate.length()*2];
ois.readFully(bString, 0, bString.length);
Or if you write as Object using writeObject method then you can read as object,
oos.writeObject(lastFetchDate);

Categories

Resources