David
David

Reputation: 382

Android: how to access objects stored with FileOutputStream

I am able to store objects to an android device, but I'm having trouble retrieving them. Data within these objects is set by the user (ie String name, int day, ect). These objects are stored (with their key being their name) and later in a different activity they're supposed to be retrieved. I can't retrieve them because in the new activity I don't their name for it is determined by the user.

To store objects (object=person)

  FileOutputStream fStream = context.openFileOutput(name,Context.MODE_PRIVATE);
  ObjectOutputStream oStream = new ObjectOutputStream(fStream);
  oStream.writeObject(person);
  oStream.close();
  fStream.close();

To retrieve objects (done in a different class)

  FileInputStream fStream = context.openFileInput( //where the name of the object should be, here's where I'm stuck );
  ObjectInputStream oStream = new ObjectInputStream(fStream);
  person = oStream.readObject();

Since I'm in a new activity, I have no idea what the user had predetermined their name to be. I can't simply just name the key "person" in both because the user is making an undetermined amount of people and is constantly adding and deleting people. If there was a way to just count the amount of stored objects, or get a list of all the stored objects' names, my problem would be solved.

Upvotes: 0

Views: 189

Answers (1)

longwalker
longwalker

Reputation: 1664

I am assuming you are trying to get the list the files from a certain directory. You can do so this way:

// Get local files
File directory = new File(Environment.getExternalStorageDirectory().toString() + localDir);

File[] listOfLocalFilesArray = directory.listFiles();

// get the names of files
String[] fileArray = new String[listOfLocalFilesArray.length];
for (int i = 0; i < listOfLocalFilesArray.length; i++) {
 fileArray[i] = listOfLocalFilesArray[i].getName();
}

Upvotes: 1

Related Questions