Disclaimer: I’ve went over many examples and read the docs.
This question entails 3 classes. My serialized class, a helper class that handles I/O, and an activity for interfacing.
My serialized class looks something like this:
public class EntityPlayer implements Serializable {
private static final long serialVersionUID = -7671612522335708108L;
String name = "foo";
public EntityPlayer() {
name = "foo";
}
}
My helper class looks like this (this is where the heavy lifting is done):
public class Main {
static Object loadPlayer(Context c, String name) throws IOException,
ClassNotFoundException {
FileInputStream f = c.openFileInput(name);
ObjectInputStream i = new ObjectInputStream(f);
Object player = i.readObject();
i.close();
return player;
}
static void savePlayer(Context c, String name, EntityPlayer player) throws IOException {
FileOutputStream f = c.openFileOutput(name, Context.MODE_PRIVATE);
ObjectOutputStream o = new ObjectOutputStream(f);
o.writeObject(player);
o.flush();
o.close();
}
}
and then finally, this is how I’m accesing (in a nut shell):
public class DisplayInteract extends Activity implements OnClickListener {
EntityPlayer player = new EntityPlayer(); //by editing this line, my issue was fixed
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.g_interact);
player = new EntityPlayer(ID, this);
try {
Main.savePlayer(player.name, player);
} catch (IOException e) {
}
try {
player = (EntityPlayer) Main.loadPlayer("Derp");
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
}
}
Basically I’m getting a NPE when I make any calls concerning the serialized class after loading it. I know the issue is in the way that I’m saving the file because I can tell that there is no file through the Android file explorer in eclipse. I know the problem also is in how I’m loading the file because (I have no ideal how) I got it to work at one point (it created a file) but I still couldn’t access any of the data without it throwing an NPE (because I wasn’t accessing the class correctly)
You’re not specifying a path where the file should be saved to.
Use the
openFileOutput()from Context which will save it to your applications data folder.