I write this more for me than for anyone else. I am new to Android programming. I had the same problem and fixed it by passing context as a parameter to the method. In my case, the class tried to write the file to a piece of code that I found in a Java example. Since I just wanted to write the persistence of the object and did not want to worry about where the file is located, I changed it to the following:
public static void Test(Context fileContext) {
Employee e = new Employee();
e.setName("Joe");
e.setAddress("Main Street, Joeville");
e.setTitle("Title.PROJECT_MANAGER");
String filename = "employee.ser";
FileOutputStream fileOut = fileContext.openFileOutput(filename, Activity.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
}
and from the calling activity, I use the following:
SerializableEmployee.Test(this.getApplicationContext());
Worked like a charm. Then I could read it (simplified version):
public static String Test(Context fileContext) {
Employee e = new Employee();
String filename = "employee.ser";
File f = new File(filename);
if (f.isFile()) {
FileInputStream fileIn = fileContext.openFileInput(filename);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}
return e.toString();
}
source
share