Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
helper class for Pixabay Response. Since we need to cache query results for 24 hours, this method will be used for caching a result. It will also fetch all the bitmaps and cache these too, since those fetches can be long running and can be initiating from a backround task.
package edu.ggc.lutz.pixabay;
import android.util.Log;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import edu.ggc.lutz.pixabay.json.Hit;
import edu.ggc.lutz.pixabay.json.PixabayHttpResponse;
import static edu.ggc.lutz.pixabay.Pixabay.TAG;
public class PixabayQueryResult {
private static long DAY_MILLIS;
private static final Gson gson;
private int responseCode;
private long created;
private PixabayHttpResponse response; // taken from jsonschema2pojo without mod
private HashMap<Long,Bitmap> bitmaps;
private String responseMethod;
static {
gson = new Gson();
long DAY_MILLIS = TimeUnit.DAYS.toMillis(1);
public PixabayQueryResult(String json) throws IOException {
this.response= gson.fromJson(json, PixabayHttpResponse.class);
this.created = System.currentTimeMillis(); // birthday!
private void cacheBitmaps() throws IOException {
this.bitmaps = new HashMap<>();
for (Hit hit : response.getHits()) {
InputStream stream = new URL(hit.getWebformatURL()).openStream();
bitmaps.put(hit.getId(), BitmapFactory.decodeStream(stream));
public boolean isExpired() {
return created - System.currentTimeMillis() > DAY_MILLIS ? true : false;
public long size() {
return response.getHits().size();
public String getTags(int index) {
return getHit(index).getTags();
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
Log.v(TAG, "responseCode = " + this.responseCode);
public void setResponseMethod(String responseMethod) {
this.responseMethod = responseMethod;
Log.v(TAG, "responseMethod = " + this.responseMethod);
public Hit getHit(int index) {
return response.getHits().get(index);
public Bitmap getBitmap(int index) {
long id = getHit(index).getId(); // covert response index to Pixabay's id
return bitmaps.get(id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.