How to cache listview data in android?

2019-04-07 00:55发布

I have a Listview that contains 100 rows. This is the first time I load all the data from a Webservice. I want to cache that data so that if I open that page I should get it from cache not from the Webservice. How can I do this?

4条回答
一夜七次
2楼-- · 2019-04-07 01:31

im assuming since you use the term cache - the data expires every x mins / hours

if the data changes every few mins simply save your webservice response in some local variable (if it only needs to be used for a single listview activity)

or save it in global variable (extend the application class and expose a public variable from here)

if your data changes every few hours then a better idea is to save it in sqlite (if your data needs complex querying / joins etc etc)

or simply save it as a file (either in json or xml format) and check for this file and expiry and if still valid simply decode it instead of calling your webservice again

查看更多
够拽才男人
3楼-- · 2019-04-07 01:34

If your data is simple enough, just store them in an array and use something like ArrayAdapter to bind the data to the list view.

If your data is more complex, then an SQLite table is probably preferable. In this case use something like SimpleCursorAdapter.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-07 01:35

You can store the data as a JSON file in your application's internal storage space. I find that this is a much easier approach, as you can easily map the JSON to Model classes using a library like Gson. You would typically follow this approach if the data you have will not be "updated" like you might do in a traditional database(although you are still able to update your JSON data, just differently).

查看更多
聊天终结者
5楼-- · 2019-04-07 01:45

Save your data in a SQLite table and use that as cache next time check if that table exists. If the table exists query that in stead of the webz :-)

查看更多
登录 后发表回答