Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Class Type info to file for later use

Tags:

java

android

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);
        fos.write(str.getBytes());
        fos.close();
    } 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 Class<?> is not an object, I don't know where to start at all.

[EDIT] .class is an object too, so we can save it just like saving an object.

like image 399
Jenix Avatar asked Dec 05 '25 16:12

Jenix


1 Answers

This is possible using ObjectOutputStream here SaveState is your Custom class

public static void saveData(SaveState instance){
ObjectOutput out;
try {
     File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
     out = new ObjectOutputStream(new FileOutputStream(outFile));
     out.writeObject(instance);
     out.close();
 } 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();
     in.close();
 } catch (Exception e) {e.printStackTrace();}
 return ss;
}

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

like image 182
Ganesh Pokale Avatar answered Dec 08 '25 05:12

Ganesh Pokale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!