1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.dreams.phototable; 17 18 import android.content.Context; 19 import android.content.SharedPreferences; 20 import android.database.Cursor; 21 22 /** 23 * Common implementation for sources that load images from a cursor. 24 */ 25 public abstract class CursorPhotoSource extends PhotoSource { 26 27 // An invalid cursor position to represent the uninitialized state. 28 protected static final int UNINITIALIZED = -1; 29 // An invalid cursor position to represent the error state. 30 protected static final int INVALID = -2; 31 32 public CursorPhotoSource(Context context, SharedPreferences settings) { 33 super(context, settings); 34 } 35 36 public CursorPhotoSource(Context context, SharedPreferences settings, PhotoSource fallback) { 37 super(context, settings, fallback); 38 } 39 40 @Override 41 protected ImageData naturalNext(ImageData current) { 42 if (current.cursor == null || current.cursor.isClosed()) { 43 openCursor(current); 44 } 45 findPosition(current); 46 current.cursor.moveToPosition(current.position); 47 current.cursor.moveToNext(); 48 ImageData data = null; 49 if (!current.cursor.isAfterLast()) { 50 data = unpackImageData(current.cursor, null); 51 data.cursor = current.cursor; 52 data.position = current.cursor.getPosition(); 53 } 54 return data; 55 } 56 57 @Override 58 protected ImageData naturalPrevious(ImageData current) { 59 if (current.cursor == null || current.cursor.isClosed()) { 60 openCursor(current); 61 } 62 findPosition(current); 63 current.cursor.moveToPosition(current.position); 64 current.cursor.moveToPrevious(); 65 ImageData data = null; 66 if (!current.cursor.isBeforeFirst()) { 67 data = unpackImageData(current.cursor, null); 68 data.cursor = current.cursor; 69 data.position = current.cursor.getPosition(); 70 } 71 return data; 72 } 73 74 @Override 75 protected void donePaging(ImageData current) { 76 if (current.cursor != null && !current.cursor.isClosed()) { 77 current.cursor.close(); 78 } 79 } 80 81 protected abstract void openCursor(ImageData data); 82 protected abstract void findPosition(ImageData data); 83 protected abstract ImageData unpackImageData(Cursor cursor, ImageData data); 84 } 85 86