How to implement ListView caching in Android

I have a ListView that contains a large dataset.
The first time I load all the data from the Webservice.

Now I want to cache this data so that if I open this page again, I can retrieve the data from the cache and not request the web service again.

How to do it?

+5
source share
3 answers

I assume that you save the data received from the WebService in a serializable object (as you indicated in your question before editing it.)

You can store serializable objects in 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(); 
+11
source

You can do this by saving the data received through the web service to a SQLite database structured accordingly. If you want to get newer data than the last record in your database, you must save the key value in the SharedPreferences file. Example:

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

Today, the user was only viewing January events from the no event. 1 to the event number. 10 (the first time they are received through the web service, stored locally in the SQLite database, and then displayed using the cursor).

Tomorrow, as soon as the user downloads the application, the data already received will be downloaded from the SQLite database ("cache"), and the user will receive events that are newer than 10 through the web service; and repeat the process the day before (that is, save the received queries in SQLite DB, and then display them all from 1 to "x").

In this case, you save events 1-10 in the database, and you save “11” in your general preferences so that you know the starting point for your next batch of entities. 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 :)

0
source

Your case is similar to this:

How to cache list data in android?

You must decide if you intend to use the SQL database if you want to keep the information longer than the application lifetime, otherwise the adapter will be fine.

The Api examples provided in the Samples for SDK package have some list examples using ListAdapters. For example, List5.java.

0
source

Source: https://habr.com/ru/post/885510/


All Articles