Java: Serialization and Deserialization objects on Android
Serialization and Deserialization objects on Android
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import android.content.Context; import com.AllErrorsJSON; import com.ErrorJSON; public class CacheControllerImpl implements CacheController{ private Context context; private final String CACHED_ERRORS_FILE_NAME = "cachedErrors.dat"; public CacheControllerImpl(Context context) { this.context = context; } @Override public boolean putErrorsToCache(AllErrorsJSON allErrorsJSON) { File cacheDir = context.getCacheDir(); File cachedDataFile = new File(cacheDir.getPath() + "/" + CACHED_ERRORS_FILE_NAME) ; FileOutputStream fos = null; ObjectOutputStream oos = null; boolean keep = true; try { fos = new FileOutputStream(cachedDataFile); fos.write((new String()).getBytes()); oos = new ObjectOutputStream(fos); oos.writeObject(allErrorsJSON); } catch (Exception e) { keep = false; } finally { try { if (oos != null) oos.close(); if (fos != null) fos.close(); if (keep == false) cachedDataFile.delete(); } catch (Exception e) { /* do nothing */ } } return keep; } @Override public AllErrorsJSON getErrorsFromCache() { AllErrorsJSON allErrorsJSON= null; FileInputStream fis = null; ObjectInputStream ois = null; File cacheDir = context.getCacheDir(); File cachedDataFile = new File(cacheDir.getPath() + "/" + CACHED_ERRORS_FILE_NAME) ; try { fis = new FileInputStream(cachedDataFile); ois = new ObjectInputStream(fis); allErrorsJSON = (AllErrorsJSON) ois.readObject(); } catch(Exception e) { } finally { try { if (fis != null) fis.close(); if (ois != null) ois.close(); } catch (Exception e) { } } return allErrorsJSON; }
Tag: Java, Android, Serialization
0 Comments