├── settings.gradle
├── screenshots
├── 2-detail.png
├── icon-web.png
└── 1-gridview.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── Application
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ ├── tile.9.png
│ │ │ └── ic_launcher.png
│ │ ├── drawable-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-nodpi
│ │ │ └── empty_photo.png
│ │ ├── drawable-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ │ ├── base-colors.xml
│ │ │ └── base-template-styles.xml
│ │ ├── values-v11
│ │ │ ├── template-styles.xml
│ │ │ └── styles.xml
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ ├── strings.xml
│ │ │ ├── styles.xml
│ │ │ ├── template-dimens.xml
│ │ │ ├── base-strings.xml
│ │ │ └── template-styles.xml
│ │ ├── values-large
│ │ │ └── dimens.xml
│ │ ├── values-xlarge
│ │ │ └── dimens.xml
│ │ ├── values-sw600dp
│ │ │ ├── template-dimens.xml
│ │ │ └── template-styles.xml
│ │ ├── layout
│ │ │ ├── image_detail_pager.xml
│ │ │ ├── image_grid_fragment.xml
│ │ │ └── image_detail_fragment.xml
│ │ ├── menu
│ │ │ └── main_menu.xml
│ │ └── drawable
│ │ │ └── photogrid_list_selector.xml
│ │ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── android
│ │ │ ├── displayingbitmaps
│ │ │ ├── ui
│ │ │ │ ├── ImageGridActivity.java
│ │ │ │ ├── RecyclingImageView.java
│ │ │ │ ├── ImageDetailFragment.java
│ │ │ │ ├── ImageDetailActivity.java
│ │ │ │ └── ImageGridFragment.java
│ │ │ ├── util
│ │ │ │ ├── Utils.java
│ │ │ │ ├── RecyclingBitmapDrawable.java
│ │ │ │ ├── ImageResizer.java
│ │ │ │ ├── ImageFetcher.java
│ │ │ │ └── ImageWorker.java
│ │ │ └── provider
│ │ │ │ └── Images.java
│ │ │ └── common
│ │ │ └── logger
│ │ │ ├── LogNode.java
│ │ │ ├── MessageOnlyLogFilter.java
│ │ │ ├── LogWrapper.java
│ │ │ ├── LogFragment.java
│ │ │ ├── LogView.java
│ │ │ └── Log.java
│ │ └── AndroidManifest.xml
├── build.gradle
└── tests
│ ├── AndroidManifest.xml
│ └── src
│ └── com
│ └── example
│ └── android
│ └── displayingbitmaps
│ └── tests
│ └── SampleTests.java
├── README.md
├── packaging.yaml
├── .google
└── packaging.yaml
├── ABOUT.txt
├── CONTRIBUTING.md
├── CONTRIB.md
├── gradlew.bat
├── gradlew
└── LICENSE
/settings.gradle:
--------------------------------------------------------------------------------
1 | include 'Application'
2 |
--------------------------------------------------------------------------------
/screenshots/2-detail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/screenshots/2-detail.png
--------------------------------------------------------------------------------
/screenshots/icon-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/screenshots/icon-web.png
--------------------------------------------------------------------------------
/screenshots/1-gridview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/screenshots/1-gridview.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/tile.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-hdpi/tile.9.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-nodpi/empty_photo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-nodpi/empty_photo.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Application/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/googlearchive/android-DisplayingBitmaps/master/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Android DisplayingBitmaps Sample
3 | ================================
4 |
5 | This repo has been migrated to [github.com/android/graphics][1]. Please check that repo for future updates. Thank you!
6 |
7 | [1]: https://github.com/android/graphics
8 |
9 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 10 15:27:10 PDT 2013
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
--------------------------------------------------------------------------------
/packaging.yaml:
--------------------------------------------------------------------------------
1 | # GOOGLE SAMPLE PACKAGING DATA
2 | #
3 | # This file is used by Google as part of our samples packaging process.
4 | # End users may safely ignore this file. It has no relevance to other systems.
5 | ---
6 |
7 | status: PUBLISHED
8 | technologies: [Android]
9 | categories: [UI]
10 | languages: [Java]
11 | solutions: [Mobile]
12 | github: googlesamples/android-DisplayingBitmaps
13 | level: BEGINNER
14 | icon: DisplayingBitmapsSample/src/main/res/drawable-xxhdpi/ic_launcher.png
15 | license: apache2-android
16 |
--------------------------------------------------------------------------------
/Application/src/main/res/values-v21/base-colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
When this is set as the head of the list, 22 | * an instance of it can function as a drop-in replacement for {@link android.util.Log}. 23 | * Most of the methods in this class server only to map a method call in Log to its equivalent 24 | * in LogNode.
25 | */ 26 | public class Log { 27 | // Grabbing the native values from Android's native logging facilities, 28 | // to make for easy migration and interop. 29 | public static final int NONE = -1; 30 | public static final int VERBOSE = android.util.Log.VERBOSE; 31 | public static final int DEBUG = android.util.Log.DEBUG; 32 | public static final int INFO = android.util.Log.INFO; 33 | public static final int WARN = android.util.Log.WARN; 34 | public static final int ERROR = android.util.Log.ERROR; 35 | public static final int ASSERT = android.util.Log.ASSERT; 36 | 37 | // Stores the beginning of the LogNode topology. 38 | private static LogNode mLogNode; 39 | 40 | /** 41 | * Returns the next LogNode in the linked list. 42 | */ 43 | public static LogNode getLogNode() { 44 | return mLogNode; 45 | } 46 | 47 | /** 48 | * Sets the LogNode data will be sent to. 49 | */ 50 | public static void setLogNode(LogNode node) { 51 | mLogNode = node; 52 | } 53 | 54 | /** 55 | * Instructs the LogNode to print the log data provided. Other LogNodes can 56 | * be chained to the end of the LogNode as desired. 57 | * 58 | * @param priority Log level of the data being logged. Verbose, Error, etc. 59 | * @param tag Tag for for the log data. Can be used to organize log statements. 60 | * @param msg The actual message to be logged. 61 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 62 | * to extract and print useful information. 63 | */ 64 | public static void println(int priority, String tag, String msg, Throwable tr) { 65 | if (mLogNode != null) { 66 | mLogNode.println(priority, tag, msg, tr); 67 | } 68 | } 69 | 70 | /** 71 | * Instructs the LogNode to print the log data provided. Other LogNodes can 72 | * be chained to the end of the LogNode as desired. 73 | * 74 | * @param priority Log level of the data being logged. Verbose, Error, etc. 75 | * @param tag Tag for for the log data. Can be used to organize log statements. 76 | * @param msg The actual message to be logged. The actual message to be logged. 77 | */ 78 | public static void println(int priority, String tag, String msg) { 79 | println(priority, tag, msg, null); 80 | } 81 | 82 | /** 83 | * Prints a message at VERBOSE priority. 84 | * 85 | * @param tag Tag for for the log data. Can be used to organize log statements. 86 | * @param msg The actual message to be logged. 87 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 88 | * to extract and print useful information. 89 | */ 90 | public static void v(String tag, String msg, Throwable tr) { 91 | println(VERBOSE, tag, msg, tr); 92 | } 93 | 94 | /** 95 | * Prints a message at VERBOSE priority. 96 | * 97 | * @param tag Tag for for the log data. Can be used to organize log statements. 98 | * @param msg The actual message to be logged. 99 | */ 100 | public static void v(String tag, String msg) { 101 | v(tag, msg, null); 102 | } 103 | 104 | 105 | /** 106 | * Prints a message at DEBUG priority. 107 | * 108 | * @param tag Tag for for the log data. Can be used to organize log statements. 109 | * @param msg The actual message to be logged. 110 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 111 | * to extract and print useful information. 112 | */ 113 | public static void d(String tag, String msg, Throwable tr) { 114 | println(DEBUG, tag, msg, tr); 115 | } 116 | 117 | /** 118 | * Prints a message at DEBUG priority. 119 | * 120 | * @param tag Tag for for the log data. Can be used to organize log statements. 121 | * @param msg The actual message to be logged. 122 | */ 123 | public static void d(String tag, String msg) { 124 | d(tag, msg, null); 125 | } 126 | 127 | /** 128 | * Prints a message at INFO priority. 129 | * 130 | * @param tag Tag for for the log data. Can be used to organize log statements. 131 | * @param msg The actual message to be logged. 132 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 133 | * to extract and print useful information. 134 | */ 135 | public static void i(String tag, String msg, Throwable tr) { 136 | println(INFO, tag, msg, tr); 137 | } 138 | 139 | /** 140 | * Prints a message at INFO priority. 141 | * 142 | * @param tag Tag for for the log data. Can be used to organize log statements. 143 | * @param msg The actual message to be logged. 144 | */ 145 | public static void i(String tag, String msg) { 146 | i(tag, msg, null); 147 | } 148 | 149 | /** 150 | * Prints a message at WARN priority. 151 | * 152 | * @param tag Tag for for the log data. Can be used to organize log statements. 153 | * @param msg The actual message to be logged. 154 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 155 | * to extract and print useful information. 156 | */ 157 | public static void w(String tag, String msg, Throwable tr) { 158 | println(WARN, tag, msg, tr); 159 | } 160 | 161 | /** 162 | * Prints a message at WARN priority. 163 | * 164 | * @param tag Tag for for the log data. Can be used to organize log statements. 165 | * @param msg The actual message to be logged. 166 | */ 167 | public static void w(String tag, String msg) { 168 | w(tag, msg, null); 169 | } 170 | 171 | /** 172 | * Prints a message at WARN priority. 173 | * 174 | * @param tag Tag for for the log data. Can be used to organize log statements. 175 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 176 | * to extract and print useful information. 177 | */ 178 | public static void w(String tag, Throwable tr) { 179 | w(tag, null, tr); 180 | } 181 | 182 | /** 183 | * Prints a message at ERROR priority. 184 | * 185 | * @param tag Tag for for the log data. Can be used to organize log statements. 186 | * @param msg The actual message to be logged. 187 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 188 | * to extract and print useful information. 189 | */ 190 | public static void e(String tag, String msg, Throwable tr) { 191 | println(ERROR, tag, msg, tr); 192 | } 193 | 194 | /** 195 | * Prints a message at ERROR priority. 196 | * 197 | * @param tag Tag for for the log data. Can be used to organize log statements. 198 | * @param msg The actual message to be logged. 199 | */ 200 | public static void e(String tag, String msg) { 201 | e(tag, msg, null); 202 | } 203 | 204 | /** 205 | * Prints a message at ASSERT priority. 206 | * 207 | * @param tag Tag for for the log data. Can be used to organize log statements. 208 | * @param msg The actual message to be logged. 209 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 210 | * to extract and print useful information. 211 | */ 212 | public static void wtf(String tag, String msg, Throwable tr) { 213 | println(ASSERT, tag, msg, tr); 214 | } 215 | 216 | /** 217 | * Prints a message at ASSERT priority. 218 | * 219 | * @param tag Tag for for the log data. Can be used to organize log statements. 220 | * @param msg The actual message to be logged. 221 | */ 222 | public static void wtf(String tag, String msg) { 223 | wtf(tag, msg, null); 224 | } 225 | 226 | /** 227 | * Prints a message at ASSERT priority. 228 | * 229 | * @param tag Tag for for the log data. Can be used to organize log statements. 230 | * @param tr If an exception was thrown, this can be sent along for the logging facilities 231 | * to extract and print useful information. 232 | */ 233 | public static void wtf(String tag, Throwable tr) { 234 | wtf(tag, null, tr); 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageResizer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | 17 | package com.example.android.displayingbitmaps.util; 18 | 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.content.res.Resources; 22 | import android.graphics.Bitmap; 23 | import android.graphics.BitmapFactory; 24 | import android.os.Build; 25 | 26 | import com.example.android.common.logger.Log; 27 | import com.example.android.displayingbitmaps.BuildConfig; 28 | 29 | import java.io.FileDescriptor; 30 | 31 | /** 32 | * A simple subclass of {@link ImageWorker} that resizes images from resources given a target width 33 | * and height. Useful for when the input images might be too large to simply load directly into 34 | * memory. 35 | */ 36 | public class ImageResizer extends ImageWorker { 37 | private static final String TAG = "ImageResizer"; 38 | protected int mImageWidth; 39 | protected int mImageHeight; 40 | 41 | /** 42 | * Initialize providing a single target image size (used for both width and height); 43 | * 44 | * @param context 45 | * @param imageWidth 46 | * @param imageHeight 47 | */ 48 | public ImageResizer(Context context, int imageWidth, int imageHeight) { 49 | super(context); 50 | setImageSize(imageWidth, imageHeight); 51 | } 52 | 53 | /** 54 | * Initialize providing a single target image size (used for both width and height); 55 | * 56 | * @param context 57 | * @param imageSize 58 | */ 59 | public ImageResizer(Context context, int imageSize) { 60 | super(context); 61 | setImageSize(imageSize); 62 | } 63 | 64 | /** 65 | * Set the target image width and height. 66 | * 67 | * @param width 68 | * @param height 69 | */ 70 | public void setImageSize(int width, int height) { 71 | mImageWidth = width; 72 | mImageHeight = height; 73 | } 74 | 75 | /** 76 | * Set the target image size (width and height will be the same). 77 | * 78 | * @param size 79 | */ 80 | public void setImageSize(int size) { 81 | setImageSize(size, size); 82 | } 83 | 84 | /** 85 | * The main processing method. This happens in a background task. In this case we are just 86 | * sampling down the bitmap and returning it from a resource. 87 | * 88 | * @param resId 89 | * @return 90 | */ 91 | private Bitmap processBitmap(int resId) { 92 | if (BuildConfig.DEBUG) { 93 | Log.d(TAG, "processBitmap - " + resId); 94 | } 95 | return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, 96 | mImageHeight, getImageCache()); 97 | } 98 | 99 | @Override 100 | protected Bitmap processBitmap(Object data) { 101 | return processBitmap(Integer.parseInt(String.valueOf(data))); 102 | } 103 | 104 | /** 105 | * Decode and sample down a bitmap from resources to the requested width and height. 106 | * 107 | * @param res The resources object containing the image data 108 | * @param resId The resource id of the image data 109 | * @param reqWidth The requested width of the resulting bitmap 110 | * @param reqHeight The requested height of the resulting bitmap 111 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 112 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 113 | * that are equal to or greater than the requested width and height 114 | */ 115 | public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 116 | int reqWidth, int reqHeight, ImageCache cache) { 117 | 118 | // BEGIN_INCLUDE (read_bitmap_dimensions) 119 | // First decode with inJustDecodeBounds=true to check dimensions 120 | final BitmapFactory.Options options = new BitmapFactory.Options(); 121 | options.inJustDecodeBounds = true; 122 | BitmapFactory.decodeResource(res, resId, options); 123 | 124 | // Calculate inSampleSize 125 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 126 | // END_INCLUDE (read_bitmap_dimensions) 127 | 128 | // If we're running on Honeycomb or newer, try to use inBitmap 129 | if (Utils.hasHoneycomb()) { 130 | addInBitmapOptions(options, cache); 131 | } 132 | 133 | // Decode bitmap with inSampleSize set 134 | options.inJustDecodeBounds = false; 135 | return BitmapFactory.decodeResource(res, resId, options); 136 | } 137 | 138 | /** 139 | * Decode and sample down a bitmap from a file to the requested width and height. 140 | * 141 | * @param filename The full path of the file to decode 142 | * @param reqWidth The requested width of the resulting bitmap 143 | * @param reqHeight The requested height of the resulting bitmap 144 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 145 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 146 | * that are equal to or greater than the requested width and height 147 | */ 148 | public static Bitmap decodeSampledBitmapFromFile(String filename, 149 | int reqWidth, int reqHeight, ImageCache cache) { 150 | 151 | // First decode with inJustDecodeBounds=true to check dimensions 152 | final BitmapFactory.Options options = new BitmapFactory.Options(); 153 | options.inJustDecodeBounds = true; 154 | BitmapFactory.decodeFile(filename, options); 155 | 156 | // Calculate inSampleSize 157 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 158 | 159 | // If we're running on Honeycomb or newer, try to use inBitmap 160 | if (Utils.hasHoneycomb()) { 161 | addInBitmapOptions(options, cache); 162 | } 163 | 164 | // Decode bitmap with inSampleSize set 165 | options.inJustDecodeBounds = false; 166 | return BitmapFactory.decodeFile(filename, options); 167 | } 168 | 169 | /** 170 | * Decode and sample down a bitmap from a file input stream to the requested width and height. 171 | * 172 | * @param fileDescriptor The file descriptor to read from 173 | * @param reqWidth The requested width of the resulting bitmap 174 | * @param reqHeight The requested height of the resulting bitmap 175 | * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap 176 | * @return A bitmap sampled down from the original with the same aspect ratio and dimensions 177 | * that are equal to or greater than the requested width and height 178 | */ 179 | public static Bitmap decodeSampledBitmapFromDescriptor( 180 | FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) { 181 | 182 | // First decode with inJustDecodeBounds=true to check dimensions 183 | final BitmapFactory.Options options = new BitmapFactory.Options(); 184 | options.inJustDecodeBounds = true; 185 | BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); 186 | 187 | // Calculate inSampleSize 188 | options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 189 | 190 | // Decode bitmap with inSampleSize set 191 | options.inJustDecodeBounds = false; 192 | 193 | // If we're running on Honeycomb or newer, try to use inBitmap 194 | if (Utils.hasHoneycomb()) { 195 | addInBitmapOptions(options, cache); 196 | } 197 | 198 | return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); 199 | } 200 | 201 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 202 | private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { 203 | //BEGIN_INCLUDE(add_bitmap_options) 204 | // inBitmap only works with mutable bitmaps so force the decoder to 205 | // return mutable bitmaps. 206 | options.inMutable = true; 207 | 208 | if (cache != null) { 209 | // Try and find a bitmap to use for inBitmap 210 | Bitmap inBitmap = cache.getBitmapFromReusableSet(options); 211 | 212 | if (inBitmap != null) { 213 | options.inBitmap = inBitmap; 214 | } 215 | } 216 | //END_INCLUDE(add_bitmap_options) 217 | } 218 | 219 | /** 220 | * Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} object when decoding 221 | * bitmaps using the decode* methods from {@link android.graphics.BitmapFactory}. This implementation calculates 222 | * the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap 223 | * having a width and height equal to or larger than the requested width and height. 224 | * 225 | * @param options An options object with out* params already populated (run through a decode* 226 | * method with inJustDecodeBounds==true 227 | * @param reqWidth The requested width of the resulting bitmap 228 | * @param reqHeight The requested height of the resulting bitmap 229 | * @return The value to be used for inSampleSize 230 | */ 231 | public static int calculateInSampleSize(BitmapFactory.Options options, 232 | int reqWidth, int reqHeight) { 233 | // BEGIN_INCLUDE (calculate_sample_size) 234 | // Raw height and width of image 235 | final int height = options.outHeight; 236 | final int width = options.outWidth; 237 | int inSampleSize = 1; 238 | 239 | if (height > reqHeight || width > reqWidth) { 240 | 241 | final int halfHeight = height / 2; 242 | final int halfWidth = width / 2; 243 | 244 | // Calculate the largest inSampleSize value that is a power of 2 and keeps both 245 | // height and width larger than the requested height and width. 246 | while ((halfHeight / inSampleSize) > reqHeight 247 | && (halfWidth / inSampleSize) > reqWidth) { 248 | inSampleSize *= 2; 249 | } 250 | 251 | // This offers some additional logic in case the image has a strange 252 | // aspect ratio. For example, a panorama may have a much larger 253 | // width than height. In these cases the total pixels might still 254 | // end up being too large to fit comfortably in memory, so we should 255 | // be more aggressive with sample down the image (=larger inSampleSize). 256 | 257 | long totalPixels = width * height / inSampleSize; 258 | 259 | // Anything more than 2x the requested pixels we'll sample down further 260 | final long totalReqPixelsCap = reqWidth * reqHeight * 2; 261 | 262 | while (totalPixels > totalReqPixelsCap) { 263 | inSampleSize *= 2; 264 | totalPixels /= 2; 265 | } 266 | } 267 | return inSampleSize; 268 | // END_INCLUDE (calculate_sample_size) 269 | } 270 | } 271 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | -------------- 3 | 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "{}" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright {yyyy} {name of copyright owner} 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageFetcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | 17 | package com.example.android.displayingbitmaps.util; 18 | 19 | import android.content.Context; 20 | import android.graphics.Bitmap; 21 | import android.net.ConnectivityManager; 22 | import android.net.NetworkInfo; 23 | import android.os.Build; 24 | import android.widget.Toast; 25 | 26 | import com.example.android.common.logger.Log; 27 | import com.example.android.displayingbitmaps.BuildConfig; 28 | import com.example.android.displayingbitmaps.R; 29 | 30 | import java.io.BufferedInputStream; 31 | import java.io.BufferedOutputStream; 32 | import java.io.File; 33 | import java.io.FileDescriptor; 34 | import java.io.FileInputStream; 35 | import java.io.IOException; 36 | import java.io.OutputStream; 37 | import java.net.HttpURLConnection; 38 | import java.net.URL; 39 | 40 | /** 41 | * A simple subclass of {@link ImageResizer} that fetches and resizes images fetched from a URL. 42 | */ 43 | public class ImageFetcher extends ImageResizer { 44 | private static final String TAG = "ImageFetcher"; 45 | private static final int HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10MB 46 | private static final String HTTP_CACHE_DIR = "http"; 47 | private static final int IO_BUFFER_SIZE = 8 * 1024; 48 | 49 | private DiskLruCache mHttpDiskCache; 50 | private File mHttpCacheDir; 51 | private boolean mHttpDiskCacheStarting = true; 52 | private final Object mHttpDiskCacheLock = new Object(); 53 | private static final int DISK_CACHE_INDEX = 0; 54 | 55 | /** 56 | * Initialize providing a target image width and height for the processing images. 57 | * 58 | * @param context 59 | * @param imageWidth 60 | * @param imageHeight 61 | */ 62 | public ImageFetcher(Context context, int imageWidth, int imageHeight) { 63 | super(context, imageWidth, imageHeight); 64 | init(context); 65 | } 66 | 67 | /** 68 | * Initialize providing a single target image size (used for both width and height); 69 | * 70 | * @param context 71 | * @param imageSize 72 | */ 73 | public ImageFetcher(Context context, int imageSize) { 74 | super(context, imageSize); 75 | init(context); 76 | } 77 | 78 | private void init(Context context) { 79 | checkConnection(context); 80 | mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR); 81 | } 82 | 83 | @Override 84 | protected void initDiskCacheInternal() { 85 | super.initDiskCacheInternal(); 86 | initHttpDiskCache(); 87 | } 88 | 89 | private void initHttpDiskCache() { 90 | if (!mHttpCacheDir.exists()) { 91 | mHttpCacheDir.mkdirs(); 92 | } 93 | synchronized (mHttpDiskCacheLock) { 94 | if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) { 95 | try { 96 | mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE); 97 | if (BuildConfig.DEBUG) { 98 | Log.d(TAG, "HTTP cache initialized"); 99 | } 100 | } catch (IOException e) { 101 | mHttpDiskCache = null; 102 | } 103 | } 104 | mHttpDiskCacheStarting = false; 105 | mHttpDiskCacheLock.notifyAll(); 106 | } 107 | } 108 | 109 | @Override 110 | protected void clearCacheInternal() { 111 | super.clearCacheInternal(); 112 | synchronized (mHttpDiskCacheLock) { 113 | if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) { 114 | try { 115 | mHttpDiskCache.delete(); 116 | if (BuildConfig.DEBUG) { 117 | Log.d(TAG, "HTTP cache cleared"); 118 | } 119 | } catch (IOException e) { 120 | Log.e(TAG, "clearCacheInternal - " + e); 121 | } 122 | mHttpDiskCache = null; 123 | mHttpDiskCacheStarting = true; 124 | initHttpDiskCache(); 125 | } 126 | } 127 | } 128 | 129 | @Override 130 | protected void flushCacheInternal() { 131 | super.flushCacheInternal(); 132 | synchronized (mHttpDiskCacheLock) { 133 | if (mHttpDiskCache != null) { 134 | try { 135 | mHttpDiskCache.flush(); 136 | if (BuildConfig.DEBUG) { 137 | Log.d(TAG, "HTTP cache flushed"); 138 | } 139 | } catch (IOException e) { 140 | Log.e(TAG, "flush - " + e); 141 | } 142 | } 143 | } 144 | } 145 | 146 | @Override 147 | protected void closeCacheInternal() { 148 | super.closeCacheInternal(); 149 | synchronized (mHttpDiskCacheLock) { 150 | if (mHttpDiskCache != null) { 151 | try { 152 | if (!mHttpDiskCache.isClosed()) { 153 | mHttpDiskCache.close(); 154 | mHttpDiskCache = null; 155 | if (BuildConfig.DEBUG) { 156 | Log.d(TAG, "HTTP cache closed"); 157 | } 158 | } 159 | } catch (IOException e) { 160 | Log.e(TAG, "closeCacheInternal - " + e); 161 | } 162 | } 163 | } 164 | } 165 | 166 | /** 167 | * Simple network connection check. 168 | * 169 | * @param context 170 | */ 171 | private void checkConnection(Context context) { 172 | final ConnectivityManager cm = 173 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 174 | final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 175 | if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { 176 | Toast.makeText(context, R.string.no_network_connection_toast, Toast.LENGTH_LONG).show(); 177 | Log.e(TAG, "checkConnection - no connection found"); 178 | } 179 | } 180 | 181 | /** 182 | * The main process method, which will be called by the ImageWorker in the AsyncTask background 183 | * thread. 184 | * 185 | * @param data The data to load the bitmap, in this case, a regular http URL 186 | * @return The downloaded and resized bitmap 187 | */ 188 | private Bitmap processBitmap(String data) { 189 | if (BuildConfig.DEBUG) { 190 | Log.d(TAG, "processBitmap - " + data); 191 | } 192 | 193 | final String key = ImageCache.hashKeyForDisk(data); 194 | FileDescriptor fileDescriptor = null; 195 | FileInputStream fileInputStream = null; 196 | DiskLruCache.Snapshot snapshot; 197 | synchronized (mHttpDiskCacheLock) { 198 | // Wait for disk cache to initialize 199 | while (mHttpDiskCacheStarting) { 200 | try { 201 | mHttpDiskCacheLock.wait(); 202 | } catch (InterruptedException e) {} 203 | } 204 | 205 | if (mHttpDiskCache != null) { 206 | try { 207 | snapshot = mHttpDiskCache.get(key); 208 | if (snapshot == null) { 209 | if (BuildConfig.DEBUG) { 210 | Log.d(TAG, "processBitmap, not found in http cache, downloading..."); 211 | } 212 | DiskLruCache.Editor editor = mHttpDiskCache.edit(key); 213 | if (editor != null) { 214 | if (downloadUrlToStream(data, 215 | editor.newOutputStream(DISK_CACHE_INDEX))) { 216 | editor.commit(); 217 | } else { 218 | editor.abort(); 219 | } 220 | } 221 | snapshot = mHttpDiskCache.get(key); 222 | } 223 | if (snapshot != null) { 224 | fileInputStream = 225 | (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); 226 | fileDescriptor = fileInputStream.getFD(); 227 | } 228 | } catch (IOException e) { 229 | Log.e(TAG, "processBitmap - " + e); 230 | } catch (IllegalStateException e) { 231 | Log.e(TAG, "processBitmap - " + e); 232 | } finally { 233 | if (fileDescriptor == null && fileInputStream != null) { 234 | try { 235 | fileInputStream.close(); 236 | } catch (IOException e) {} 237 | } 238 | } 239 | } 240 | } 241 | 242 | Bitmap bitmap = null; 243 | if (fileDescriptor != null) { 244 | bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, 245 | mImageHeight, getImageCache()); 246 | } 247 | if (fileInputStream != null) { 248 | try { 249 | fileInputStream.close(); 250 | } catch (IOException e) {} 251 | } 252 | return bitmap; 253 | } 254 | 255 | @Override 256 | protected Bitmap processBitmap(Object data) { 257 | return processBitmap(String.valueOf(data)); 258 | } 259 | 260 | /** 261 | * Download a bitmap from a URL and write the content to an output stream. 262 | * 263 | * @param urlString The URL to fetch 264 | * @return true if successful, false otherwise 265 | */ 266 | public boolean downloadUrlToStream(String urlString, OutputStream outputStream) { 267 | disableConnectionReuseIfNecessary(); 268 | HttpURLConnection urlConnection = null; 269 | BufferedOutputStream out = null; 270 | BufferedInputStream in = null; 271 | 272 | try { 273 | final URL url = new URL(urlString); 274 | urlConnection = (HttpURLConnection) url.openConnection(); 275 | in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); 276 | out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); 277 | 278 | int b; 279 | while ((b = in.read()) != -1) { 280 | out.write(b); 281 | } 282 | return true; 283 | } catch (final IOException e) { 284 | Log.e(TAG, "Error in downloadBitmap - " + e); 285 | } finally { 286 | if (urlConnection != null) { 287 | urlConnection.disconnect(); 288 | } 289 | try { 290 | if (out != null) { 291 | out.close(); 292 | } 293 | if (in != null) { 294 | in.close(); 295 | } 296 | } catch (final IOException e) {} 297 | } 298 | return false; 299 | } 300 | 301 | /** 302 | * Workaround for bug pre-Froyo, see here for more info: 303 | * http://android-developers.blogspot.com/2011/09/androids-http-clients.html 304 | */ 305 | public static void disableConnectionReuseIfNecessary() { 306 | // HTTP connection reuse which was buggy pre-froyo 307 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { 308 | System.setProperty("http.keepAlive", "false"); 309 | } 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/ui/ImageGridFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | 17 | package com.example.android.displayingbitmaps.ui; 18 | 19 | import android.annotation.TargetApi; 20 | import android.app.ActivityOptions; 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.os.Build.VERSION_CODES; 24 | import android.os.Bundle; 25 | import android.support.v4.app.Fragment; 26 | import android.util.TypedValue; 27 | import android.view.LayoutInflater; 28 | import android.view.Menu; 29 | import android.view.MenuInflater; 30 | import android.view.MenuItem; 31 | import android.view.View; 32 | import android.view.ViewGroup; 33 | import android.view.ViewGroup.LayoutParams; 34 | import android.view.ViewTreeObserver; 35 | import android.widget.AbsListView; 36 | import android.widget.AdapterView; 37 | import android.widget.BaseAdapter; 38 | import android.widget.GridView; 39 | import android.widget.ImageView; 40 | import android.widget.Toast; 41 | 42 | import com.example.android.common.logger.Log; 43 | import com.example.android.displayingbitmaps.BuildConfig; 44 | import com.example.android.displayingbitmaps.R; 45 | import com.example.android.displayingbitmaps.provider.Images; 46 | import com.example.android.displayingbitmaps.util.ImageCache; 47 | import com.example.android.displayingbitmaps.util.ImageFetcher; 48 | import com.example.android.displayingbitmaps.util.Utils; 49 | 50 | /** 51 | * The main fragment that powers the ImageGridActivity screen. Fairly straight forward GridView 52 | * implementation with the key addition being the ImageWorker class w/ImageCache to load children 53 | * asynchronously, keeping the UI nice and smooth and caching thumbnails for quick retrieval. The 54 | * cache is retained over configuration changes like orientation change so the images are populated 55 | * quickly if, for example, the user rotates the device. 56 | */ 57 | public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener { 58 | private static final String TAG = "ImageGridFragment"; 59 | private static final String IMAGE_CACHE_DIR = "thumbs"; 60 | 61 | private int mImageThumbSize; 62 | private int mImageThumbSpacing; 63 | private ImageAdapter mAdapter; 64 | private ImageFetcher mImageFetcher; 65 | 66 | /** 67 | * Empty constructor as per the Fragment documentation 68 | */ 69 | public ImageGridFragment() {} 70 | 71 | @Override 72 | public void onCreate(Bundle savedInstanceState) { 73 | super.onCreate(savedInstanceState); 74 | setHasOptionsMenu(true); 75 | 76 | mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size); 77 | mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing); 78 | 79 | mAdapter = new ImageAdapter(getActivity()); 80 | 81 | ImageCache.ImageCacheParams cacheParams = 82 | new ImageCache.ImageCacheParams(getActivity(), IMAGE_CACHE_DIR); 83 | 84 | cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory 85 | 86 | // The ImageFetcher takes care of loading images into our ImageView children asynchronously 87 | mImageFetcher = new ImageFetcher(getActivity(), mImageThumbSize); 88 | mImageFetcher.setLoadingImage(R.drawable.empty_photo); 89 | mImageFetcher.addImageCache(getActivity().getSupportFragmentManager(), cacheParams); 90 | } 91 | 92 | @Override 93 | public View onCreateView( 94 | LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 95 | 96 | final View v = inflater.inflate(R.layout.image_grid_fragment, container, false); 97 | final GridView mGridView = (GridView) v.findViewById(R.id.gridView); 98 | mGridView.setAdapter(mAdapter); 99 | mGridView.setOnItemClickListener(this); 100 | mGridView.setOnScrollListener(new AbsListView.OnScrollListener() { 101 | @Override 102 | public void onScrollStateChanged(AbsListView absListView, int scrollState) { 103 | // Pause fetcher to ensure smoother scrolling when flinging 104 | if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { 105 | // Before Honeycomb pause image loading on scroll to help with performance 106 | if (!Utils.hasHoneycomb()) { 107 | mImageFetcher.setPauseWork(true); 108 | } 109 | } else { 110 | mImageFetcher.setPauseWork(false); 111 | } 112 | } 113 | 114 | @Override 115 | public void onScroll(AbsListView absListView, int firstVisibleItem, 116 | int visibleItemCount, int totalItemCount) { 117 | } 118 | }); 119 | 120 | // This listener is used to get the final width of the GridView and then calculate the 121 | // number of columns and the width of each column. The width of each column is variable 122 | // as the GridView has stretchMode=columnWidth. The column width is used to set the height 123 | // of each view so we get nice square thumbnails. 124 | mGridView.getViewTreeObserver().addOnGlobalLayoutListener( 125 | new ViewTreeObserver.OnGlobalLayoutListener() { 126 | @TargetApi(VERSION_CODES.JELLY_BEAN) 127 | @Override 128 | public void onGlobalLayout() { 129 | if (mAdapter.getNumColumns() == 0) { 130 | final int numColumns = (int) Math.floor( 131 | mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing)); 132 | if (numColumns > 0) { 133 | final int columnWidth = 134 | (mGridView.getWidth() / numColumns) - mImageThumbSpacing; 135 | mAdapter.setNumColumns(numColumns); 136 | mAdapter.setItemHeight(columnWidth); 137 | if (BuildConfig.DEBUG) { 138 | Log.d(TAG, "onCreateView - numColumns set to " + numColumns); 139 | } 140 | if (Utils.hasJellyBean()) { 141 | mGridView.getViewTreeObserver() 142 | .removeOnGlobalLayoutListener(this); 143 | } else { 144 | mGridView.getViewTreeObserver() 145 | .removeGlobalOnLayoutListener(this); 146 | } 147 | } 148 | } 149 | } 150 | }); 151 | 152 | return v; 153 | } 154 | 155 | @Override 156 | public void onResume() { 157 | super.onResume(); 158 | mImageFetcher.setExitTasksEarly(false); 159 | mAdapter.notifyDataSetChanged(); 160 | } 161 | 162 | @Override 163 | public void onPause() { 164 | super.onPause(); 165 | mImageFetcher.setPauseWork(false); 166 | mImageFetcher.setExitTasksEarly(true); 167 | mImageFetcher.flushCache(); 168 | } 169 | 170 | @Override 171 | public void onDestroy() { 172 | super.onDestroy(); 173 | mImageFetcher.closeCache(); 174 | } 175 | 176 | @TargetApi(VERSION_CODES.JELLY_BEAN) 177 | @Override 178 | public void onItemClick(AdapterView> parent, View v, int position, long id) { 179 | final Intent i = new Intent(getActivity(), ImageDetailActivity.class); 180 | i.putExtra(ImageDetailActivity.EXTRA_IMAGE, (int) id); 181 | if (Utils.hasJellyBean()) { 182 | // makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may 183 | // show plus the thumbnail image in GridView is cropped. so using 184 | // makeScaleUpAnimation() instead. 185 | ActivityOptions options = 186 | ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()); 187 | getActivity().startActivity(i, options.toBundle()); 188 | } else { 189 | startActivity(i); 190 | } 191 | } 192 | 193 | @Override 194 | public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 195 | inflater.inflate(R.menu.main_menu, menu); 196 | } 197 | 198 | @Override 199 | public boolean onOptionsItemSelected(MenuItem item) { 200 | switch (item.getItemId()) { 201 | case R.id.clear_cache: 202 | mImageFetcher.clearCache(); 203 | Toast.makeText(getActivity(), R.string.clear_cache_complete_toast, 204 | Toast.LENGTH_SHORT).show(); 205 | return true; 206 | } 207 | return super.onOptionsItemSelected(item); 208 | } 209 | 210 | /** 211 | * The main adapter that backs the GridView. This is fairly standard except the number of 212 | * columns in the GridView is used to create a fake top row of empty views as we use a 213 | * transparent ActionBar and don't want the real top row of images to start off covered by it. 214 | */ 215 | private class ImageAdapter extends BaseAdapter { 216 | 217 | private final Context mContext; 218 | private int mItemHeight = 0; 219 | private int mNumColumns = 0; 220 | private int mActionBarHeight = 0; 221 | private GridView.LayoutParams mImageViewLayoutParams; 222 | 223 | public ImageAdapter(Context context) { 224 | super(); 225 | mContext = context; 226 | mImageViewLayoutParams = new GridView.LayoutParams( 227 | LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 228 | // Calculate ActionBar height 229 | TypedValue tv = new TypedValue(); 230 | if (context.getTheme().resolveAttribute( 231 | android.R.attr.actionBarSize, tv, true)) { 232 | mActionBarHeight = TypedValue.complexToDimensionPixelSize( 233 | tv.data, context.getResources().getDisplayMetrics()); 234 | } 235 | } 236 | 237 | @Override 238 | public int getCount() { 239 | // If columns have yet to be determined, return no items 240 | if (getNumColumns() == 0) { 241 | return 0; 242 | } 243 | 244 | // Size + number of columns for top empty row 245 | return Images.imageThumbUrls.length + mNumColumns; 246 | } 247 | 248 | @Override 249 | public Object getItem(int position) { 250 | return position < mNumColumns ? 251 | null : Images.imageThumbUrls[position - mNumColumns]; 252 | } 253 | 254 | @Override 255 | public long getItemId(int position) { 256 | return position < mNumColumns ? 0 : position - mNumColumns; 257 | } 258 | 259 | @Override 260 | public int getViewTypeCount() { 261 | // Two types of views, the normal ImageView and the top row of empty views 262 | return 2; 263 | } 264 | 265 | @Override 266 | public int getItemViewType(int position) { 267 | return (position < mNumColumns) ? 1 : 0; 268 | } 269 | 270 | @Override 271 | public boolean hasStableIds() { 272 | return true; 273 | } 274 | 275 | @Override 276 | public View getView(int position, View convertView, ViewGroup container) { 277 | //BEGIN_INCLUDE(load_gridview_item) 278 | // First check if this is the top row 279 | if (position < mNumColumns) { 280 | if (convertView == null) { 281 | convertView = new View(mContext); 282 | } 283 | // Set empty view with height of ActionBar 284 | convertView.setLayoutParams(new AbsListView.LayoutParams( 285 | LayoutParams.MATCH_PARENT, mActionBarHeight)); 286 | return convertView; 287 | } 288 | 289 | // Now handle the main ImageView thumbnails 290 | ImageView imageView; 291 | if (convertView == null) { // if it's not recycled, instantiate and initialize 292 | imageView = new RecyclingImageView(mContext); 293 | imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 294 | imageView.setLayoutParams(mImageViewLayoutParams); 295 | } else { // Otherwise re-use the converted view 296 | imageView = (ImageView) convertView; 297 | } 298 | 299 | // Check the height matches our calculated column width 300 | if (imageView.getLayoutParams().height != mItemHeight) { 301 | imageView.setLayoutParams(mImageViewLayoutParams); 302 | } 303 | 304 | // Finally load the image asynchronously into the ImageView, this also takes care of 305 | // setting a placeholder image while the background thread runs 306 | mImageFetcher.loadImage(Images.imageThumbUrls[position - mNumColumns], imageView); 307 | return imageView; 308 | //END_INCLUDE(load_gridview_item) 309 | } 310 | 311 | /** 312 | * Sets the item height. Useful for when we know the column width so the height can be set 313 | * to match. 314 | * 315 | * @param height 316 | */ 317 | public void setItemHeight(int height) { 318 | if (height == mItemHeight) { 319 | return; 320 | } 321 | mItemHeight = height; 322 | mImageViewLayoutParams = 323 | new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight); 324 | mImageFetcher.setImageSize(height); 325 | notifyDataSetChanged(); 326 | } 327 | 328 | public void setNumColumns(int numColumns) { 329 | mNumColumns = numColumns; 330 | } 331 | 332 | public int getNumColumns() { 333 | return mNumColumns; 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /Application/src/main/java/com/example/android/displayingbitmaps/util/ImageWorker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | 17 | package com.example.android.displayingbitmaps.util; 18 | 19 | import android.content.Context; 20 | import android.content.res.Resources; 21 | import android.graphics.Bitmap; 22 | import android.graphics.BitmapFactory; 23 | import android.graphics.drawable.BitmapDrawable; 24 | import android.graphics.drawable.ColorDrawable; 25 | import android.graphics.drawable.Drawable; 26 | import android.graphics.drawable.TransitionDrawable; 27 | import android.support.v4.app.FragmentActivity; 28 | import android.support.v4.app.FragmentManager; 29 | import android.widget.ImageView; 30 | 31 | import com.example.android.common.logger.Log; 32 | import com.example.android.displayingbitmaps.BuildConfig; 33 | 34 | import java.lang.ref.WeakReference; 35 | 36 | /** 37 | * This class wraps up completing some arbitrary long running work when loading a bitmap to an 38 | * ImageView. It handles things like using a memory and disk cache, running the work in a background 39 | * thread and setting a placeholder image. 40 | */ 41 | public abstract class ImageWorker { 42 | private static final String TAG = "ImageWorker"; 43 | private static final int FADE_IN_TIME = 200; 44 | 45 | private ImageCache mImageCache; 46 | private ImageCache.ImageCacheParams mImageCacheParams; 47 | private Bitmap mLoadingBitmap; 48 | private boolean mFadeInBitmap = true; 49 | private boolean mExitTasksEarly = false; 50 | protected boolean mPauseWork = false; 51 | private final Object mPauseWorkLock = new Object(); 52 | 53 | protected Resources mResources; 54 | 55 | private static final int MESSAGE_CLEAR = 0; 56 | private static final int MESSAGE_INIT_DISK_CACHE = 1; 57 | private static final int MESSAGE_FLUSH = 2; 58 | private static final int MESSAGE_CLOSE = 3; 59 | 60 | protected ImageWorker(Context context) { 61 | mResources = context.getResources(); 62 | } 63 | 64 | /** 65 | * Load an image specified by the data parameter into an ImageView (override 66 | * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and 67 | * disk cache will be used if an {@link ImageCache} has been added using 68 | * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the 69 | * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask} 70 | * will be created to asynchronously load the bitmap. 71 | * 72 | * @param data The URL of the image to download. 73 | * @param imageView The ImageView to bind the downloaded image to. 74 | * @param listener A listener that will be called back once the image has been loaded. 75 | */ 76 | public void loadImage(Object data, ImageView imageView, OnImageLoadedListener listener) { 77 | if (data == null) { 78 | return; 79 | } 80 | 81 | BitmapDrawable value = null; 82 | 83 | if (mImageCache != null) { 84 | value = mImageCache.getBitmapFromMemCache(String.valueOf(data)); 85 | } 86 | 87 | if (value != null) { 88 | // Bitmap found in memory cache 89 | imageView.setImageDrawable(value); 90 | if (listener != null) { 91 | listener.onImageLoaded(true); 92 | } 93 | } else if (cancelPotentialWork(data, imageView)) { 94 | //BEGIN_INCLUDE(execute_background_task) 95 | final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView, listener); 96 | final AsyncDrawable asyncDrawable = 97 | new AsyncDrawable(mResources, mLoadingBitmap, task); 98 | imageView.setImageDrawable(asyncDrawable); 99 | 100 | // NOTE: This uses a custom version of AsyncTask that has been pulled from the 101 | // framework and slightly modified. Refer to the docs at the top of the class 102 | // for more info on what was changed. 103 | task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR); 104 | //END_INCLUDE(execute_background_task) 105 | } 106 | } 107 | 108 | /** 109 | * Load an image specified by the data parameter into an ImageView (override 110 | * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and 111 | * disk cache will be used if an {@link ImageCache} has been added using 112 | * {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}. If the 113 | * image is found in the memory cache, it is set immediately, otherwise an {@link AsyncTask} 114 | * will be created to asynchronously load the bitmap. 115 | * 116 | * @param data The URL of the image to download. 117 | * @param imageView The ImageView to bind the downloaded image to. 118 | */ 119 | public void loadImage(Object data, ImageView imageView) { 120 | loadImage(data, imageView, null); 121 | } 122 | 123 | /** 124 | * Set placeholder bitmap that shows when the the background thread is running. 125 | * 126 | * @param bitmap 127 | */ 128 | public void setLoadingImage(Bitmap bitmap) { 129 | mLoadingBitmap = bitmap; 130 | } 131 | 132 | /** 133 | * Set placeholder bitmap that shows when the the background thread is running. 134 | * 135 | * @param resId 136 | */ 137 | public void setLoadingImage(int resId) { 138 | mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId); 139 | } 140 | 141 | /** 142 | * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap 143 | * caching. 144 | * @param fragmentManager 145 | * @param cacheParams The cache parameters to use for the image cache. 146 | */ 147 | public void addImageCache(FragmentManager fragmentManager, 148 | ImageCache.ImageCacheParams cacheParams) { 149 | mImageCacheParams = cacheParams; 150 | mImageCache = ImageCache.getInstance(fragmentManager, mImageCacheParams); 151 | new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE); 152 | } 153 | 154 | /** 155 | * Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap 156 | * caching. 157 | * @param activity 158 | * @param diskCacheDirectoryName See 159 | * {@link ImageCache.ImageCacheParams#ImageCacheParams(android.content.Context, String)}. 160 | */ 161 | public void addImageCache(FragmentActivity activity, String diskCacheDirectoryName) { 162 | mImageCacheParams = new ImageCache.ImageCacheParams(activity, diskCacheDirectoryName); 163 | mImageCache = ImageCache.getInstance(activity.getSupportFragmentManager(), mImageCacheParams); 164 | new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE); 165 | } 166 | 167 | /** 168 | * If set to true, the image will fade-in once it has been loaded by the background thread. 169 | */ 170 | public void setImageFadeIn(boolean fadeIn) { 171 | mFadeInBitmap = fadeIn; 172 | } 173 | 174 | public void setExitTasksEarly(boolean exitTasksEarly) { 175 | mExitTasksEarly = exitTasksEarly; 176 | setPauseWork(false); 177 | } 178 | 179 | /** 180 | * Subclasses should override this to define any processing or work that must happen to produce 181 | * the final bitmap. This will be executed in a background thread and be long running. For 182 | * example, you could resize a large bitmap here, or pull down an image from the network. 183 | * 184 | * @param data The data to identify which image to process, as provided by 185 | * {@link ImageWorker#loadImage(Object, android.widget.ImageView)} 186 | * @return The processed bitmap 187 | */ 188 | protected abstract Bitmap processBitmap(Object data); 189 | 190 | /** 191 | * @return The {@link ImageCache} object currently being used by this ImageWorker. 192 | */ 193 | protected ImageCache getImageCache() { 194 | return mImageCache; 195 | } 196 | 197 | /** 198 | * Cancels any pending work attached to the provided ImageView. 199 | * @param imageView 200 | */ 201 | public static void cancelWork(ImageView imageView) { 202 | final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 203 | if (bitmapWorkerTask != null) { 204 | bitmapWorkerTask.cancel(true); 205 | if (BuildConfig.DEBUG) { 206 | final Object bitmapData = bitmapWorkerTask.mData; 207 | Log.d(TAG, "cancelWork - cancelled work for " + bitmapData); 208 | } 209 | } 210 | } 211 | 212 | /** 213 | * Returns true if the current work has been canceled or if there was no work in 214 | * progress on this image view. 215 | * Returns false if the work in progress deals with the same data. The work is not 216 | * stopped in that case. 217 | */ 218 | public static boolean cancelPotentialWork(Object data, ImageView imageView) { 219 | //BEGIN_INCLUDE(cancel_potential_work) 220 | final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 221 | 222 | if (bitmapWorkerTask != null) { 223 | final Object bitmapData = bitmapWorkerTask.mData; 224 | if (bitmapData == null || !bitmapData.equals(data)) { 225 | bitmapWorkerTask.cancel(true); 226 | if (BuildConfig.DEBUG) { 227 | Log.d(TAG, "cancelPotentialWork - cancelled work for " + data); 228 | } 229 | } else { 230 | // The same work is already in progress. 231 | return false; 232 | } 233 | } 234 | return true; 235 | //END_INCLUDE(cancel_potential_work) 236 | } 237 | 238 | /** 239 | * @param imageView Any imageView 240 | * @return Retrieve the currently active work task (if any) associated with this imageView. 241 | * null if there is no such task. 242 | */ 243 | private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { 244 | if (imageView != null) { 245 | final Drawable drawable = imageView.getDrawable(); 246 | if (drawable instanceof AsyncDrawable) { 247 | final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; 248 | return asyncDrawable.getBitmapWorkerTask(); 249 | } 250 | } 251 | return null; 252 | } 253 | 254 | /** 255 | * The actual AsyncTask that will asynchronously process the image. 256 | */ 257 | private class BitmapWorkerTask extends AsyncTask458 | * If work is paused, be sure setPauseWork(false) is called again 459 | * before your fragment or activity is destroyed (for example during 460 | * {@link android.app.Activity#onPause()}), or there is a risk the 461 | * background thread will never finish. 462 | */ 463 | public void setPauseWork(boolean pauseWork) { 464 | synchronized (mPauseWorkLock) { 465 | mPauseWork = pauseWork; 466 | if (!mPauseWork) { 467 | mPauseWorkLock.notifyAll(); 468 | } 469 | } 470 | } 471 | 472 | protected class CacheAsyncTask extends AsyncTask