Joe
Joe

Reputation: 301

Saving API Call Response in SharePreferences

SHORT QUESTION: Is it acceptable to store JSONString, returned from API Call, in Sharepreferences and use it for later use (and faster activity loading) or should I implement some kind of cache methods?

P.S Shareprefeferences will be updated with new JSONString if data is changed on Server.

LONG QUESTION: I've developed an app on Android where I'm using some online sources for data. Using Volley, I'm making API Calls and getting the response in JSONString.

So the app workflow is like this, The user opens the app and an API call is fired to fetch new data from the server, it takes between 2 - 5 seconds for API to get the response from. Now sometime the delay goes double of 2-5 seconds and the user can't do anything before the data is fetched and is available. In short, the user is stuck for 5 seconds on a blank screen with loading spinner(BAD USER EXPERIENCE). To avoid this delay, I'm saving the response from the server to Sharepreferences and load the data locally while the API call is executed in the background. Now when the API Call returns fresh data from the server, Only if the data is changed, I'm updating the Shareprefs and a toast/pop-up is displayed with some string like "refresh now".

My question is Is it ok to use shareprefes for storing this kind of data or should I use some sort of caching methods to store and view the data.

Data is mostly Strings, no images or icons so I can load from sharedprefs even if no internet is available.

Upvotes: 0

Views: 245

Answers (2)

Vinay Jayaram
Vinay Jayaram

Reputation: 1005

My recommendation is to use the standard caching technology available in inbuild libraries like Retrofit or Volley.

I hope you will be making use of anyone of them for your API calls, Here is one small example of doing it in Retrofit

int cacheSize = 10 * 1024 * 1024; // 10 MB  
Cache cache = new Cache(getCacheDir(), cacheSize);

OkHttpClient okHttpClient = new OkHttpClient.Builder()  
        .cache(cache)
        .build();

Retrofit.Builder builder = new Retrofit.Builder()  
        .baseUrl("http://10.0.2.2:3000/")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();  

For caching in Volley you can refer to Android set up Volley to use from cache

Upvotes: 2

Viswanath Kumar Sandu
Viswanath Kumar Sandu

Reputation: 2274

Storing JSON response in Shared Preference is a bad practice. You can use a caching mechanism to store it.

Adding to it, SharedPreference has a limit of 8192 characters for each value. Hence it is not prefered to store json string

Upvotes: 0

Related Questions