I really had this problem, and since my application wants to save a more complex object, I did it, I took the object serialized, then saved it to a file. Then I can check from any activity of this file and get the full object. There is no need to use garbage from string keys of prefixes and packets.
public static void setInFile(Activity act, Object_VO obj) { ((Object) act.getApplication()).setObjectState(obj); String ser = SerializeObject.objectToString(obj); if (ser!= null && !ser.equalsIgnoreCase("")) { SerializeObject.WriteSettings(act, ser, "android.dat"); } else { SerializeObject.WriteSettings(act, "", "android.dat"); } }
You will need this for serialization and deserialization:
public class SerializeObject { public static String objectToString(Serializable object) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { new ObjectOutputStream(out).writeObject(object); byte[] data = out.toByteArray(); out.close(); out = new ByteArrayOutputStream(); Base64OutputStream b64 = new Base64OutputStream(out,0); b64.write(data); b64.close(); out.close(); return new String(out.toByteArray()); } catch (IOException e) { e.printStackTrace(); } return null; } public static Object stringToObject(String encodedObject) { try { return new ObjectInputStream(new Base64InputStream( new ByteArrayInputStream(encodedObject.getBytes()), 0)).readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void WriteSettings(Context context, String data, String filename){ FileOutputStream fOut = null; OutputStreamWriter osw = null; try{ fOut = context.openFileOutput(filename, Context.MODE_PRIVATE); osw = new OutputStreamWriter(fOut); osw.write(data); osw.flush();
and finally, you need to create a global state of the object that you can reference.
package com.utils; public class ObjectState extends Application { private Object_VO obj; public Object_VO getObjectState() { return this.obj; } public void setObjectState(Object_VO o) { this.obj = o; } }
Oh yes, and you need to update the AndroidManifest.xml file to include a link to the ObjectState, as it refers to an application like this ...
<application android:name="com.utils.ObjectState" android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>