How to implement ListView caching in Android

2020-03-23 17:57发布

问题:

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?.

回答1:

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();


回答2:

You can do this by saving the data obtainted through the web service into an SQLite Database, structured accordingly. If you would like to get newer data than the last record in your database, than you should save a key value in your SharedPreferences file. Example:

I would like to get all calendar events from a web service,

Today the user only accessed January's events from event no. 1 to event no. 10 (for the first time, these are obtained through the web service, stored locally in the SQLite Database, and then displayed with the use of a cursor).

Tomorrow, once the user loads the application, the already retrieved data will load from the SQLite Database ('the cache') and the user will only get events which are newer than 10 through the web service; and repeat the process of the day before (i.e. store retrieved entites in the SQLite DB, and then display them all from 1 to 'x').

In this case you store events 1 to 10 in the database and you store '11' in your shared preferences so you would know the starting point for your next batch of entities to obtained. I hope I managed to guide you.

Take a look at the storage options available on Android: http://developer.android.com/guide/topics/data/data-storage.html

All the best :)



回答3:

Your case is like that one:

How to cache listview data in android?

You have to decide if you are going to use a SQL database if you want to mantain the info longer than the lifetime of the app, otherwise an adapter will be ok.

On the Api Demos provided on the Samples for SDK package there are several examples of List using ListAdapters. For example the List5.java.