Decoding image in AsyncTask - android

I'm new to android development and I'm a bit confused regarding decoding and scaling bitmaps using AsyncTask. I've read the android development site and it didn't help my understanding. My question is how exactly is this done? My goal is to decode and scale multiple images and placed them in ImageViews.
Do I code the decoding and scaling within a doInBackground method? Any help will be great appreciated!

Yes, you should do anything you can on the doInBackground. Only when your image is ready than use "return" to call onPostExecute and in onPostExecute you should set the bitmap to the imageView.

This code sample is from my recipe app, and should illustrate what you are asking. The images are read in as base64 encoded data from a web service, so need to be decoded before they can be shown within a ListView.
The code first of all checks for cached images, if not it decodes them in the background using AsyncTask, and writes the result to cache for future use.
The decoding is done in doInBackground, and the display/write to cache is done in onPostExecute.
Hole this helps.
mRecipeAdapter = new ArrayAdapter<Recipe>(getActivity(), R.layout.listrow, mData2){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (null == convertView) {
row = mInflater.inflate(R.layout.recipe_listrow, null);
} else {
row = convertView;
}
TextView tv = (TextView) row.findViewById(R.id.recipe_title);
ImageView iv = (ImageView) row.findViewById(R.id.recipe_image);
iv.setImageBitmap(null);
Recipe r = getItem(position);
tv.setText(r.title);
File cacheFile = new File(mCacheDir, ""+r.identity.hashCode());
if (cacheFile.exists()){
FileInputStream fis;
try {
fis = new FileInputStream(cacheFile);
Bitmap bmp = BitmapFactory.decodeStream(fis);
iv.setImageBitmap(bmp);
bmp = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
// Get image asynchronously from database
new AsyncImages(iv).execute(r);
}
return row;
}
class AsyncImages extends AsyncTask<Recipe, Void, Recipe> {
private static final long MAX_SIZE = 5242880L; // 5MB
private final WeakReference<ImageView> imageViewReference;
public AsyncImages(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Recipe doInBackground(Recipe... r) {
Recipe recipe = r[0];
double heapRemaining = Runtime.getRuntime().freeMemory(); //amount available in heap
Log.i("MEM REM", Double.toString(heapRemaining));
String imageString = SchwartzRecipesBaseActivity.getThumbnailImageFor(recipe.identity);
recipe.thumb = StringToBitMap(imageString);
imageString = null;
return recipe;
}
protected void onPostExecute(Recipe r) {
if (isCancelled()) {
r.thumb = null;
return;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(r.thumb);
// Write to cache file
// Make space if needed
long sz = getDirSize();
if (sz>MAX_SIZE){
makeSomeSpace(r.thumb.getByteCount());
}
File cacheFile = new File(mCacheDir, ""+r.identity.hashCode());
try {
// Create a file at the file path, and open it for writing obtaining the output stream
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
// Write the bitmap to the output stream (and thus the file) in PNG format (lossless compression)
r.thumb.compress(CompressFormat.JPEG, 100, fos);
// Flush and close the output stream
fos.flush();
fos.close();
} catch (Exception e) {
// Log anything that might go wrong with IO to file
Log.e("CACHE", "Error when saving image to cache. ", e);
}
}
}
}
private void makeSomeSpace(long bytes) {
long bytesDeleted = 0;
File[] files = mCacheDir.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
} });
for (File file : files) {
bytesDeleted += file.length();
file.delete();
if (bytesDeleted >= bytes) {
break;
}
}
}
private long getDirSize() {
if (mCacheDir == null) return 0;
long size = 0;
File[] files = mCacheDir.listFiles();
for (File file : files) {
if (file.isFile()) {
size += file.length();
}
}
return size;
}
}
private Bitmap StringToBitMap(String encodedString) {
try{
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
};
setListAdapter(mRecipeAdapter);

Do all the heavy loading stuff in the doInBackground method, and just set the image afterwards in the onPostExecute method.
Enable the strict mode (http://developer.android.com/reference/android/os/StrictMode.html) to make sure you have done everything right (will write a warning into your logcat in case you are doing something on the UI thread you shouldn't be doing):
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
But I highly recommend to use a library like volley or Picasso whenever you are working with images from external sources. Take a look at the following question: Local image caching solution for Android: Square Picasso vs Universal Image Loader

Related

Screenshot of custom view in Android generates blank image

I have a view MyCustomView which extends FrameLayout. The view creates image views dynamically within.
private void setModel(Model m) {
for (Element elem : m.getImageElements()) {
elem.iv = new ImageView();
addView(elem.iv);
}
...
// Load images into the image views
int count = 0;
for (Element elem : m.getImageElements()) {
Picasso.with(mContext)
.load("file://" + elem.photo.getLocalUri())
.skipMemoryCache()
.noFade()
.into(elem.iv, new Callback() {
#Override
public void onSuccess() {
// When all images have been downloaded successfully
if (++count == m.getImageElements().size) {
generatePreview(this, m.getId());
}
}
#Override
public void onError() {
}
});
}
}
private static Drawable generatePreview(View targetView, int id) {
Bitmap b = Bitmap.createBitmap(targetView.getLayoutParams().width,
targetView.getLayoutParams().height,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
targetView.draw(c);
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "image-preview" + id + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 95,fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using the above MyCustomView inside a RecyclerView.
#Override
public void onBindViewHolder(final MyViewHolder holder) {
...
holder.mCustomView.setModel(model);
...
}
The problem is for some rows the preview image is coming out as blank (transparent) which seems to indicate that during draw of MyCustomView in generatePreview the images of elements within MyCustomView weren't drawn yet even though Picasso onSuccess got called.
I have tried putting the generatePreview block in a postDelayed and calling it after 1000 ms but that also fails for some rows.

How to load Media Metadata Smoothly in a RecyclerView

I have a Music class that needs to return its cover art as a bitmap in order to use it on a RecylerView. I am using an AsyncTask inner class in the class to perform the retrieval, however, my app freezes once the list is being created from cover arts. Please see the code below for Music.java:
public class Music {
private static final String LOG_TAG = Music.class.getSimpleName();
private String mId;
private String mTitle;
private String mUrl;
private Bitmap mCoverArt;
public Music(String id, String title, String url) {
mId = id;
mTitle = title;
mUrl = url;
mCoverArt = null; //Initialize with null
}
String getId() {
return mId;
}
String getTitle() {
return mTitle;
}
String getUrl() {
return mUrl;
}
Bitmap getCoverArt() {
if(mCoverArt != null) {
return mCoverArt;
}
else {
Bitmap bmp = null;
try {
bmp = new GetCoverArt().execute(mUrl).get();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "InterruptedException: " + e.getMessage());
} catch (ExecutionException e) {
Log.e(LOG_TAG, "ExecutionException: " + e.getMessage());
}
return bmp;
}
}
public void setCoverArt(Bitmap bmp) { mCoverArt = bmp; }
private static class GetCoverArt extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... paths) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(paths[0], new HashMap<String,String>());
byte[] picData = mmr.getEmbeddedPicture();
return BitmapFactory.decodeByteArray(picData, 0, picData.length);
}
}
}
I am calling getCoverArt() in onBindViewHolder for my RecyclerView this way:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Music song = mDataset.get(position);
Bitmap songCoverArt = song.getCoverArt();
String songTitle = song.getTitle();
String songId = song.getId();
String songUrl = song.getUrl();
if(songCoverArt != null) {
Glide.with(mContext).load(songCoverArt).into(holder.coverArt);
}
else {
holder.coverArt.setImageResource(R.drawable.coverart_fallback);
}
Bitmap bmp = song.getCoverArt();
if(bmp != null) {
Glide.with(mContext).load(bmp).into(holder.coverArt);
}
else {
Glide.with(mContext).load(R.drawable.coverart_fallback).into(holder.coverArt);
}
I do not understand why doInBackground in AsyncTask might cause the UI thread to freeze. I thought it all runs in the background, but it seems my RecyclerView is waiting for it to finish the job before it can use the value returned. Currently, as an a bad workaround, I am doing such processing in another AsyncTask in the main activity along with other network operations when I construct Music objects and add them to an ArrayList:
for( int j = 0 ; j < songs.length() ; j++) {
JSONObject song = songs.getJSONObject(j); //get song at index j
String songId = song.getString( getString(R.string.json_song_id) );
String title = song.getString( getString(R.string.json_song_title));
String path = song.getString( getString(R.string.json_filepath) );
//Create a temp Music object to extract Music info
Music songObj = new Music(songId, title, path);
Bitmap bmp = createCoverArtBmp(path);
songObj.setCoverArt(bmp);
mMusicTrackArray.add(songObj); //Add the music object into array
}
You don't need to convert it to bitmap from the url to show the images. Simply pass the image url to Glide and it will load it for you.
By calling bitmap making in the getCoverArt() you are not doing it async but waiting for the task to finish as a result freezing your view.
See here how to use Glide with url : https://github.com/bumptech/glide#how-do-i-use-glide
#Umar Hussain is correct with passing urls, but Glide can also use local files or URI's doing so is covered in:
Glide load local image by Uri.
The benefit here of using local files (I suggest saving to your cache) is that you don't have to pass around bulky bitmaps. Out of memory exceptions make developers sad.
I have noticed you are also using fallbacks from if statements, but Glide has a placeholder method
Glide.with(getContext())
.load(some_bitmap_file_url_or_drawable)
.placeholder(some_placeholder_drawable)
.into(view_you_want_it_to_appear);
This should transition to the image you want when it loads, plus provide a fallback if it doesn't

Using Picasso with custom disk cache

In Volley library, the NetworkImageView class requires an ImageLoader that handles all the image requests by searching for them inside an ImageCache implementation, the user is free to choose how the cache should work, the location and the name of the images.
I'm switching from Volley to Retrofit, and for the images I decided to try Picasso.
With the former library, I had a String parameter in each of my items containing the image URL, then I used myNetworkImageView.setImageUrl(item.getURL()) and it was able to determine if image was cached on disk. If the image existed in cache folder, the image was loaded, otherwise it was downloaded and loaded.
I would like to be able to do the same with Picasso, is it possible with Picasso APIs or should I code such feature by myself?
I was thinking to download the image to a folder (the cache folder), and use Picasso.with(mContext).load(File downloadedimage) on completion. Is this the proper way or are there any best practices?
Picasso doesn't have a disk cache. It delegates to whatever HTTP client you are using for that functionality (relying on HTTP cache semantics for cache control). Because of this, the behavior you seek comes for free.
The underlying HTTP client will only download an image over the network if one does not exist in its local cache (and that image isn't expired).
That said, you can create custom cache implementation for java.net.HttpUrlConnection (via ResponseCache or OkHttp (via ResponseCache or OkResponseCache) which stores files in the format you desire. I would strongly advise against this, however.
Let Picasso and the HTTP client do the work for you!
You can call setIndicatorsEnabled(true) on the Picasso instance to see an indicator from where images are being loaded. It looks like this:
If you never see a blue indicator, it's likely that your remote images do not include proper cache headers to enable caching to disk.
If your project is using the okhttp library then picasso will automatically use it as the default downloader and the disk caché will work automagically.
Assuming that you use Android Studio, just add these two lines under dependencies in the build.gradle file and you will be set. (No extra configurations with picasso needed)
dependencies {
[...]
compile 'com.squareup.okhttp:okhttp:2.+'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.+'
}
As rightly pointed out by many people here, OkHttpClient is the way to go for caching.
When caching with OkHttp you might also want to gain more control on Cache-Control header in the HTTP response using OkHttp interceptors, see my response here
How it is was written previously, Picasso uses a cache of the underlying Http client.
HttpUrlConnection's built-in cache isn't working in truly offline mode and If using of OkHttpClient is unwanted by some reasons, it is possible to use your own implementation of disk-cache (of course based on DiskLruCache).
One of ways is subclassing com.squareup.picasso.UrlConnectionDownloader and programm whole logic at:
#Override
public Response load(final Uri uri, int networkPolicy) throws IOException {
...
}
And then use your implementation like this:
new Picasso.Builder(context).downloader(<your_downloader>).build();
Here is my implementation of UrlConnectionDownloader, that works with disk-cache and ships to Picasso bitmaps even in total offline mode:
public class PicassoBitmapDownloader extends UrlConnectionDownloader {
private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
#NonNull private Context context;
#Nullable private DiskLruCache diskCache;
public class IfModifiedResponse extends Response {
private final String ifModifiedSinceDate;
public IfModifiedResponse(InputStream stream, boolean loadedFromCache, long contentLength, String ifModifiedSinceDate) {
super(stream, loadedFromCache, contentLength);
this.ifModifiedSinceDate = ifModifiedSinceDate;
}
public String getIfModifiedSinceDate() {
return ifModifiedSinceDate;
}
}
public PicassoBitmapDownloader(#NonNull Context context) {
super(context);
this.context = context;
}
#Override
public Response load(final Uri uri, int networkPolicy) throws IOException {
final String key = getKey(uri);
{
Response cachedResponse = getCachedBitmap(key);
if (cachedResponse != null) {
return cachedResponse;
}
}
IfModifiedResponse response = _load(uri);
if (cacheBitmap(key, response.getInputStream(), response.getIfModifiedSinceDate())) {
IfModifiedResponse cachedResponse = getCachedBitmap(key);
if (cachedResponse != null) {return cachedResponse;
}
}
return response;
}
#NonNull
protected IfModifiedResponse _load(Uri uri) throws IOException {
HttpURLConnection connection = openConnection(uri);
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage(),
0, responseCode);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
String lastModified = connection.getHeaderField(Constants.HEADER_LAST_MODIFIED);
return new IfModifiedResponse(connection.getInputStream(), false, contentLength, lastModified);
}
#Override
protected HttpURLConnection openConnection(Uri path) throws IOException {
HttpURLConnection conn = super.openConnection(path);
DiskLruCache diskCache = getDiskCache();
DiskLruCache.Snapshot snapshot = diskCache == null ? null : diskCache.get(getKey(path));
if (snapshot != null) {
String ifModifiedSince = snapshot.getString(1);
if (!isEmpty(ifModifiedSince)) {
conn.addRequestProperty(Constants.HEADER_IF_MODIFIED_SINCE, ifModifiedSince);
}
}
return conn;
}
#Override public void shutdown() {
try {
if (diskCache != null) {
diskCache.flush();
diskCache.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
super.shutdown();
}
public boolean cacheBitmap(#Nullable String key, #Nullable InputStream inputStream, #Nullable String ifModifiedSince) {
if (inputStream == null || isEmpty(key)) {
return false;
}
OutputStream outputStream = null;
DiskLruCache.Editor edit = null;
try {
DiskLruCache diskCache = getDiskCache();
edit = diskCache == null ? null : diskCache.edit(key);
outputStream = edit == null ? null : new BufferedOutputStream(edit.newOutputStream(0));
if (outputStream == null) {
return false;
}
ChatUtils.copy(inputStream, outputStream);
outputStream.flush();
edit.set(1, ifModifiedSince == null ? "" : ifModifiedSince);
edit.commit();
return true;
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (edit != null) {
edit.abortUnlessCommitted();
}
ChatUtils.closeQuietly(outputStream);
}
return false;
}
#Nullable
public IfModifiedResponse getCachedBitmap(String key) {
try {
DiskLruCache diskCache = getDiskCache();
DiskLruCache.Snapshot snapshot = diskCache == null ? null : diskCache.get(key);
InputStream inputStream = snapshot == null ? null : snapshot.getInputStream(0);
if (inputStream == null) {
return null;
}
return new IfModifiedResponse(inputStream, true, snapshot.getLength(0), snapshot.getString(1));
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Nullable
synchronized public DiskLruCache getDiskCache() {
if (diskCache == null) {
try {
File file = new File(context.getCacheDir() + "/images");
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.mkdirs();
}
long maxSize = calculateDiskCacheSize(file);
diskCache = DiskLruCache.open(file, BuildConfig.VERSION_CODE, 2, maxSize);
}
catch (Exception e) {
e.printStackTrace();
}
}
return diskCache;
}
#NonNull
private String getKey(#NonNull Uri uri) {
String key = md5(uri.toString());
return isEmpty(key) ? String.valueOf(uri.hashCode()) : key;
}
#Nullable
public static String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
sb.append(String.format("%02X", aByte));
}
return sb.toString().toLowerCase();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
static long calculateDiskCacheSize(File dir) {
long available = ChatUtils.bytesAvailable(dir);
// Target 2% of the total space.
long size = available / 50;
// Bound inside min/max size for disk cache.
return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
}
}

How to efficiently store bitmaps in Android?

I'm building a relatively basic news-reader app that involves displaying news in a custom listview (Image + Title + Short Description per list element).
My question is How can I store the images I download from the server and then attach them to the listview? The images will be relatively small, 200 X 200 usually, in .jpeg format.
It's not so much a question of how as much as "how to do it efficiently", as I'm already noticing lag in lower-end phones when using the default "ic_launcher" icon instead of bitmaps.
Would it be faster to store them as files or into the news database along with other news data when the app starts and syncs up the news or cache them...?
How should I go about this?
better you can do it's use SoftReference via an ImageManager class.
In you ListAdpater getView() method call the displayImage() method of ImageManager.
ImageManager Coding Exemple :
public class ImageManagerExemple {
private static final String LOG_TAG = "ImageManager";
private static ImageManagerExemple instance = null;
public static ImageManagerExemple getInstance(Context context) {
if (instance == null) {
instance = new ImageManagerExemple(context);
}
return instance;
}
private HashMap<String, SoftReference<Bitmap>> imageMap = new HashMap<String, SoftReference<Bitmap>>();
private Context context;
private File cacheDir;
private ImageManagerExemple(Context context) {
this.context = context;
// Find the dir to save cached images
String sdState = android.os.Environment.getExternalStorageState();
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdDir = android.os.Environment.getExternalStorageDirectory();
cacheDir = new File(sdDir,"data/yourappname");
} else {
cacheDir = context.getCacheDir();
}
if(!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
/**
* Display web Image loading thread
* #param imageUrl picture web url
* #param imageView target
* #param imageWaitRef picture during loading
*/
public void displayImage(String imageUrl, ImageView imageView, Integer imageWaitRef) {
String imageKey = imageUrl;
imageView.setTag(imageKey);
if(imageMap.containsKey(imageKey) && imageMap.get(imageKey).get() != null) {
Bitmap bmp = imageMap.get(imageKey).get();
imageView.setImageBitmap(bmp);
} else {
queueImage(imageUrl, imageView);
if(imageWaitRef != null)
imageView.setImageResource(imageWaitRef);
}
}
private void queueImage(String url, ImageView imageView) {
ImageRef imgRef=new ImageRef(url, imageView);
// Start thread
Thread imageLoaderThread = new Thread(new ImageQueueManager(imgRef));
// Make background thread low priority, to avoid affecting UI performance
imageLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
imageLoaderThread.start();
}
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
try {
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if(bitmap != null) return bitmap;
// Nope, have to download it
bitmap = ImageServerUtils.pictureUrlToBitmap(url);
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
Log.e(LOG_TAG, ""+ex.getLocalizedMessage());
return null;
} catch (OutOfMemoryError e) {
Log.e(LOG_TAG, "OutOfMemoryError : "+e.getLocalizedMessage());
e.printStackTrace();
return null;
}
}
private void writeFile(Bitmap bmp, File f) {
if (bmp != null && f != null) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
//bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
bmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try { if (out != null ) out.close(); }
catch(Exception ex) {}
}
}
}
private class ImageRef {
public String imageUrl;
public ImageView imageView;
public ImageRef(String imageUrl, ImageView i) {
this.imageUrl=imageUrl;
this.imageView=i;
}
}
private class ImageQueueManager implements Runnable {
private ImageRef imageRef;
public ImageQueueManager(ImageRef imageRef) {
super();
this.imageRef = imageRef;
}
#Override
public void run() {
ImageRef imageToLoad = this.imageRef;
if (imageToLoad != null) {
Bitmap bmp = getBitmap(imageToLoad.imageUrl);
String imageKey = imageToLoad.imageUrl;
imageMap.put(imageKey, new SoftReference<Bitmap>(bmp));
Object tag = imageToLoad.imageView.getTag();
// Make sure we have the right view - thread safety defender
if (tag != null && ((String)tag).equals(imageKey)) {
BitmapDisplayer bmpDisplayer = new BitmapDisplayer(bmp, imageToLoad.imageView);
Activity a = (Activity)imageToLoad.imageView.getContext();
a.runOnUiThread(bmpDisplayer);
}
}
}
}
//Used to display bitmap in the UI thread
private class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap=b;
imageView=i;
}
#Override
public void run() {
if(bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
The trick to getting smooth ListView scrolling without stutter is to not update it in any way, shape or form while the user is scrolling it. Afaik, this is essentially how iOS manages to get its ListViews that smooth: it disallows any changes to it (and the UI in general) while the user has his finger on it.
Just comment out any code that changes your ListView while leaving all the bitmap loading code intact, and you'll see that the actual loading of the bitmaps in the background doesn't really impact performance at all. The problem is that the UI thread can't keep up with view updates and scrolling at the same time.
You can achieve the same thing by using a OnScrollListener that blocks all updates to the ListView while the User is scrolling it. As soon as the user stops, you can sneak in all pending updates.
For added performance, try not to use notifyDataSetChanged but iterate over the views of the ListView and only update the views that have actually changed.

Android: Make App accessible without internet connection

so I made an app which communicates with JSON on the web. It fetches images and texts from the JSON.
And now I got a task to make this app accessible without an internet connection.
it should be like this:
The first time it's launched, the app has to check if there's any internet connection or not. If not, pop up a dialog box 'Please check your internet connection'. If there's any, the app is opened and it has to download the images and texts from the JSON and save them into an external storage
The next time when the app is opened, when there's no internet it will load the images and text files from the external storage. And each time it's connected to the internet, it will download the files and replace the previous files.
Can anybody provide me a solution by modifying these classes below maybe?
public class ImageThreadLoader {
private static final String TAG = "ImageThreadLoader";
// Global cache of images.
// Using SoftReference to allow garbage collector to clean cache if needed
private final HashMap<String, SoftReference<Bitmap>> Cache = new HashMap<String, SoftReference<Bitmap>>();
private final class QueueItem {
public URL url;
public ImageLoadedListener listener;
}
private final ArrayList<QueueItem> Queue = new ArrayList<QueueItem>();
private final Handler handler = new Handler(); // Assumes that this is started from the main (UI) thread
private Thread thread;
private QueueRunner runner = new QueueRunner();;
/** Creates a new instance of the ImageThreadLoader */
public ImageThreadLoader() {
thread = new Thread(runner);
}
/**
* Defines an interface for a callback that will handle
* responses from the thread loader when an image is done
* being loaded.
*/
public interface ImageLoadedListener {
public void imageLoaded(Bitmap imageBitmap );
}
/**
* Provides a Runnable class to handle loading
* the image from the URL and settings the
* ImageView on the UI thread.
*/
private class QueueRunner implements Runnable {
public void run() {
synchronized(this) {
while(Queue.size() > 0) {
final QueueItem item = Queue.remove(0);
// If in the cache, return that copy and be done
if( Cache.containsKey(item.url.toString()) && Cache.get(item.url.toString()) != null) {
// Use a handler to get back onto the UI thread for the update
handler.post(new Runnable() {
public void run() {
if( item.listener != null ) {
// NB: There's a potential race condition here where the cache item could get
// garbage collected between when we post the runnable and it's executed.
// Ideally we would re-run the network load or something.
SoftReference<Bitmap> ref = Cache.get(item.url.toString());
if( ref != null ) {
item.listener.imageLoaded(ref.get());
}
}
}
});
} else {
final Bitmap bmp = readBitmapFromNetwork(item.url);
if( bmp != null ) {
Cache.put(item.url.toString(), new SoftReference<Bitmap>(bmp));
// Use a handler to get back onto the UI thread for the update
handler.post(new Runnable() {
public void run() {
if( item.listener != null ) {
item.listener.imageLoaded(bmp);
}
}
});
}
}
}
}
}
}
/**
* Queues up a URI to load an image from for a given image view.
*
* #param uri The URI source of the image
* #param callback The listener class to call when the image is loaded
* #throws MalformedURLException If the provided uri cannot be parsed
* #return A Bitmap image if the image is in the cache, else null.
*/
public Bitmap loadImage( final String uri, final ImageLoadedListener listener) throws MalformedURLException {
// If it's in the cache, just get it and quit it
if( Cache.containsKey(uri)) {
SoftReference<Bitmap> ref = Cache.get(uri);
if( ref != null ) {
return ref.get();
}
}
QueueItem item = new QueueItem();
item.url = new URL(uri);
item.listener = listener;
Queue.add(item);
// start the thread if needed
if( thread.getState() == State.NEW) {
thread.start();
} else if( thread.getState() == State.TERMINATED) {
thread = new Thread(runner);
thread.start();
}
return null;
}
/**
* Convenience method to retrieve a bitmap image from
* a URL over the network. The built-in methods do
* not seem to work, as they return a FileNotFound
* exception.
*
* Note that this does not perform any threading --
* it blocks the call while retrieving the data.
*
* #param url The URL to read the bitmap from.
* #return A Bitmap image or null if an error occurs.
*/
public static Bitmap readBitmapFromNetwork( URL url ) {
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
try {
URLConnection conn = url.openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is);
bmp = BitmapFactory.decodeStream(bis);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad ad URL", e);
} catch (IOException e) {
Log.e(TAG, "Could not get remote ad image", e);
} finally {
try {
if( is != null )
is.close();
if( bis != null )
bis.close();
} catch (IOException e) {
Log.w(TAG, "Error closing stream.");
}
}
return bmp;
}
}
and
public class ProjectAdapter extends ArrayAdapter<Project> {
int resource;
String response;
Context context;
private final static String TAG = "MediaItemAdapter";
private ImageThreadLoader imageLoader = new ImageThreadLoader();
//Initialize adapter
public ProjectAdapter(Context context, int resource, List<Project> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TextView textTitle;
final ImageView image;
Project pro = getItem(position);
LinearLayout projectView;
//Inflate the view
if(convertView==null)
{
projectView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, projectView, true);
}
else
{
projectView = (LinearLayout) convertView;
}
try {
textTitle = (TextView)projectView.findViewById(R.id.txt_title);
image = (ImageView)projectView.findViewById(R.id.image);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
Bitmap cachedImage = null;
try {
cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener() {
public void imageLoaded(Bitmap imageBitmap) {
image.setImageBitmap(imageBitmap);
notifyDataSetChanged(); }
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
}
textTitle.setText(pro.project_title);
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
return projectView;
}
}
Thank you!
Create a database with the names and paths of the downloaded images. Upon onCreate() (or wherever you want to do the check), read the database and check if it's empty or not. If not, then use the images.

Categories

Resources