Cache object in Android? - android

Im wondering whats the best way to cache objects in an Android application? I am working with a REST application and have written a notification class that fetches number of new messages, events, guestbookposts etc from our API in JSON-format.
I use these numbers to display a badge on the icons so users can see if they have any new undread messages, events etc...
I would however like to cache this object for about 5 minutes or so to save performance, but its not as easy as just to set an expire date on the sharedpreferences class...so how do i do it i ask you?

You have a lot of options, your choice depends on application needs:
caching using SQLite database
caching to a file (internal/external storage)
LruCache util from support package
If you're going to cache images, you can use one of 'all-in-one' libraries:
UniversalImageLoader
Picasso
If you use HttpUrlConnection class to interact with server, take a look at HttpResponseCache class.
But none of these options provide built-in support of setting cache lifetime, you have to implement it by yourself if needed.

Related

Cache HTTP response or store in database in mobile apps?

For better UX mobile apps store data on the client side (on the device) to provide immediate information when loading an app without having to wait for data from the internet and providing data even when the device is offline. Of course data is updated/fetched whenever possible later on.
I am building an app (in flutter) which is a social network/information feed like app: there are users, profiles, feed, posts etc. When the user opens the app I would like to show data that was available the last time the app ran.
My question is what is the right way to implement cache? There are two main ways I can think of, an easier/uncertain way and a more difficult/stable way, and I would like your opinion about them. I have time/resource constraints ofc. Most information is through HTTP requests, so:
The easier way: HTTP Cache interception
I would use an out-of-the-box cache plugin for my HTTP client. I think I can just cache the response for each request I make (for some time) and rely on the cached info. Images are also cached based on url. When I make a request on application load I return the cached result if there's any, and if it was a cache hit I fire the request again, so when you open the app you will see immediate information, but after a sec or so you will get the fresh data too. Usability of this solution ofc depends on how well I design my API.
Harder: Store data in a structured database.
This is the option I try to avoid, because it's more time implementing this. It could be either a SQL or document store, and I would have to implement the cache look up/save/update mechanism. Since I am just building the app, I think this would slow me down because data types/ architecture might still change. But is this the ultimate way to go with mobile side caching?
Thank you
I think the easier way is your best bet the only time i can think of that cache could be a problem is if you need critical data that has to be correct and not a old cache value, but you can avoid this problem by not caching the critical values.
Also if you use firebase it does some automatic caching which might be useful.

How can I regularly update a database of content on an Android app?

So the app is for a Parrot Rescue. It will contain profiles for each of the birds that we currently have for adoption. So a picture of the bird, and then basic info about the bird. It needs to be regularly updated as the birds are adopted out and new ones come in. What route should I go? My main concern is that I want it to be relatively easy to update so that some of the less technically inclined could use it, as I won't always be available to help them.
Instead of loading a new version of the application every time, you should implement a database on a parrot information server. Then the application (the client) will ask the server to receive parrot information.
Just implement a mySQL database and a PHP page that returns the information in JSON format. Then through the application you will make a request to the server using the volley library or okHTTP and enter the information into a list.
As there are also pictures, use the glide library to download the images.
Also remember to upload small images to the server.
This way the app is always up to date
The easiest way is to update the app on the play store with the newest db, and let auto-update update the app with the new db.
Next easiest is to have a nightly (or whatever frequency) service download a new db and replace the old one from your servers
If you want it to be as easy as possible to update for everyone I would recommend a little app that has two main activities. One for displaying the entries of the database (and maybe also giving the ability to delete the entry) and another with a template to fill with all information and the image.
Then like Raffaele D'Arco explained use a little server. You could also delay the updates to be in a 5 minute routine or the like so that you put as little stress as possible on the server.
There are multiple good ways to update the interface without updating the app constantly.
Use a database which the app will download after a fixed amount of time which will be located on the server.
Secondly, if you have a website you can convert the web pages to XML or JSON or something like that and can update the app UI as per the data downloaded from the website.
I would recommend the second option as it is quite easy than the first one...

Android light and fast way to implement data storage from Api Rest service

I'd have to implement a simple app that retrieves some data from Api Rest service through JSON and save them to internal data storage.
Until now, I'm using AsynTask custom class for each call but it seems a complicated and slow process to retrieve json, check, parse and save it to storage ( I'm usic DBHelper with an SQLLite DB ).
I don't need to manage a large amount of data, I need to manage events with some strings, an image url, and some dates.
The important is having a fast process to load/update/storage/retrieve information from API Rest Service to android internal storage.
What is the best solution to implement it?
Thank you guys
First of all: Don't reinvent the wheel and use successful libraries for API / database handling. This will save you tons of (debugging) time. Have a look at the Android Arsenal for the libraries fitting your needs. For a clean architecture have a look at these samples.
To get information from RestApi I would recommend a retrofit. It let you get data very easy and convert it to lot's of different format.
If you will use gson then retrofit can convert your data from server directly to objects. And then just sabe this objects to you local db.
Different ORM libraries let you do that very easy.

Persisting ListView

I'm building a listview and getting it's data from Parse.com. At the moment, every time the app loads up it queries for new data from Parse.com, causing the whole listview to load.
I'd like a situation where the listview references a local datasource and only go to Parse.com if new data is available. Somewhat similar to what the instagram app does whereby when you load it up, the list view is already populated and would get updated if needed.
I have tried ParseQuery Cache policies but the behavior still stays the same. What would be the most efficient way of implementing this feature?
Thanks in advance.
Sync Adapters can help you with your your problem. It is generally used for account and cloud synchronization. But there is no limitation using it.
http://developer.android.com/training/sync-adapters/index.html
Synchronizing data between an Android device and web servers can make
your application significantly more useful and compelling for your
users. For example, transferring data to a web server makes a useful
backup, and transferring data from a server makes it available to the
user even when the device is offline. In some cases, users may find it
easier to enter and edit their data in a web interface and then have
that data available on their device, or they may want to collect data
over time and then upload it to a central storage area.
Although you can design your own system for doing data transfers in
your app, you should consider using Android's sync adapter framework.
This framework helps manage and automate data transfers, and
coordinates synchronization operations across different apps. When you
use this framework, you can take advantage of several features that
aren't available to data transfer schemes you design yourself
You can access sample project here: http://developer.android.com/shareables/training/BasicSyncAdapter.zip
Note: Sync adapters run asynchronously, so you should use them with the
expectation that they transfer data regularly and efficiently, but not
instantaneously. If you need to do real-time data transfer, you should
do it in an AsyncTask or an IntentService.

Caching strategy for Android app

I am thinking about how to ideally implement a cache layer in my Android app.
Currently I have generic Activities which display data coming from a remote server. The data is represented by a DTO TemplateInstance. Each TemplateInstance has a Map with Components in it and each of the components can have child components. The components themselves can be Text (String), Image (ByteArray) or Time (or whatever by sub-classing Component).
Currently my app loads a TemplateInstance from the server each time an Activity is started.
I would now like to implement a cache layer in the app, so that
the time to display data is reduced to a minimum,
the data is refreshed when it is changed on the server.
My strategy for this looks like this:
The started Activity loads the TemplateInstance from a local storage by an ID (if exists)
A UpdateService checks in the background if the TemplateInstance has changed on the server (using a version field in the database)
If the server version is greater than the local one or there is no local TemplateInstance then retrieve the data from the server, update the local store and update the view
I implemented this already successfully with db4o. There are just two problems with this solution:
db4o is under GPL (I cannot use it)
db4o is really slow when I load TemplateInstances which have many images (4 seconds for a query)
Now I am looking for the best replacement for db4o. My ideas about that are until now:
SQLite is not suitable because of the structure of the data
I donĀ“t need database functionality - retrieving objects by ID would be enough
Holding the objects in memory would be significantly faster
The memory state should be saved to disk when application exits, so the objects can be reinstantiated at startup
What do you think is the best solution for this?
My research on this brought me to EHCache and JCS, which I have never used. Do you think they are appropriate, also in respect of resources on an Android phone? Or do you have other suggestions?
If I understand your situation correctly, I think you should implement your own caching solution.
I would use an HashMap<id, TemplateInstance>. The HashMap is serializable and you could store/load it using ObjectOutputStream and ObjectInputStream, respectively.
db4o is not limited to GPL, via its dOCL you can opt for other open source licenses and, if you can't go open source at all, it's also totally free for Android apps
You can use my fork of
simple-disk-cache This is an easy to use disk cache which uses DiskLruCache under the hood.
I have replace Apache Commons IO dependence with google guava. And have add new public methods:
put(String key, String value, Object[] array) - the value I have use to put the timestamp for max TTL (after this time in ms the cache expired)
and: T getArray(String key, Class type)
You can put array from Serializable objects like this:
cache.put("key", String.valueOf(new Date().getTime() + 60000), Groups[] arrayGroups);
and get it: Groups[] cacheArray = getCacheArray("key", Groups[].class);
you can put in cache Bitmap images too.

Categories

Resources