qwertyuiop
qwertyuiop

Reputation: 13

How to cache objects into internal memory

I have one problem. I am creating some kind of heavy object every time when I open an activity. While using the program, this activity can be opened a lot of times, so every time I should wait while some heavy stuff is done. Is there any way to cache this large object into memory and get it from memory while activity is started for the second time. Or there is another way to do this ?

Upvotes: 0

Views: 94

Answers (2)

Matt Twig
Matt Twig

Reputation: 444

Save object as file:

FileOutputStream output = context.openFileOutput("object.bin", Context.MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(output);
outputStream.writeObject(objectToSave);
outputStream.close();

Load object from file

FileInputStream input = context.openFileInput(fileName);
ObjectInputStream inputStream = new ObjectInputStream(input);
Object obj = inputStream.readObject();
inputStream.close();
ObjectToSave ots;
if(obj instanceof ObjectToSave)
{
its = (ObjectToSave) obj;
}

Upvotes: 1

tsobe
tsobe

Reputation: 179

You can extend Application and store/retrieve arbitrary object(s) from anywhere, anytime.

So your activity will look like this

void onCreate(Bundle bundle) {
   GlobalState state = (GlobalState) getApplicationContext();
   MyObject obj = state.getMyObject();
   if (obj == null) {
      obj = createHeavyObject();
      state.setMyObject(obj);
   }
   // your business logic here
}

Upvotes: 0

Related Questions