Jenix Jenix - 11 months ago 59
Android Question

Saving Class Type info to file for later use

As you know, passing class types is important when programming Android applications.
One simple example is using an Intent.

Intent i = new Intent(this, MyActivity.class);

So it'll be kind of useful in some situations if I can save the class type info to a file for later use, for instance, after reboot.

void saveClassTypeInfo(Class<?> classType, String filename) {

String str = null;

// Some job with classType

FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
} catch (Exception e) {

If I could save in a certain way like above, then I would be able to put it back to an Intent like this in the future.

Intent i = new Intent(this, restoredClassInfoFromFile);

How I can achieve this kind of job? Because
is not an object, I don't know where to start at all.

Answer Source

This is posssible using ObjectOutputStream

public static void saveData(SaveState instance){
ObjectOutput out;
try {
     File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
     out = new ObjectOutputStream(new FileOutputStream(outFile));
 } catch (Exception e) {e.printStackTrace();}

public static SaveState loadData(){
 ObjectInput in;
 SaveState ss=null;
 try {
     in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));       
     ss=(SaveState) in.readObject();
 } catch (Exception e) {e.printStackTrace();}
 return ss;

Full Tutorial write to File available here And Read Object from File here