Search code examples
androidcachingmemorycache

How to implement ListView caching in Android


I have a ListView which contains a large set of data.
At the first time, I load all the data from a Webservice.

Now I want to cache that data so that, if I'm to open that page again, I can fetch the data from the cache instead of querying the webservice again.

How do I do that?.


Solution

  • I assume you're storing the data retrieved from WebService in a serializable object (as you stated in your question before you edited it.)

    You can store serializable objects into a file and load them later:

    Store:

    FileOutputStream fileOutputStream = yourContext.openFileOutput(fileName, Context.MODE_PRIVATE);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(yourObject);
    objectOutputStream.close();
    

    Load:

    FileInputStream fileInputStream = yourContext.openFileInput(fileName);
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    Object yourObject = (Object)objectInputStream.readObject();
    objectInputStream.close();