Giter Site home page Giter Site logo

webcachedimageview's Introduction

#WebCachedImageView

WebCachedImageView logo

An ImageView capable of downloading images from the web and caching them for faster and offline access.

##Purpose Mobile devices have limited processor power, battery and data connectivity. Hence, it's never a good idea to download images over and over again when they need to be displayed.

A simple but common reproduction of this problem is when you have a ListView with images. Since Android's Adapter recycles the list's views when the user scrolls, the images have to be downloaded and re-downloaded for each scroll action.

WebCachedImageView solves this problem by downloading the image and caching it on memory and on disk. So subsequent displays of the same image don't need to download data nor require a lot of processor power.

##How it works WebCachedImageView downloads the image on a background thread, without blocking the UI. After the image is downloaded for the first time, it is cached on memory and on disk, according to the current configuration.

When the image needs to be loaded again, WebCachedImageView will first look for it on memory, because it's faster. If the image was garbage collected, it will look for it on disk.

##Pro features

###Caching The WebCachedImageView's cache is a LRU cache, which means that the images that were least recently used will be the first ones to be purged.

###Concurrency WebCachedImageView handles concurrency, so you can use it inside AdapterViews (like ListView) and recycle it without worrying about mismatched threads.

###Image sampling according to the view size WebCachedImageView will download and cache only the amount of pixels that actually need to be displayed. It means that if you have a WebCachedImageView of 100dp x 100dp on a hdpi screen, and have to download a 500px x 500px image, the library will sample the image, resize it and only download a subset of 150px x 150px.

##Usage You can find a whole working example on the DumbledroidExample folder of the Dumbledroid repository. It's a working Android project that uses WebCachedImageView to download the images. You can see the correct usage at flickr_result_row.xml and FlickrAdapter.java.

But for the purposes of this manual, following are step by step instructions.

###Step 1: Add the library to your Android project

In Android Studio, add this to your project's build.gradle:

repositories {
    maven { url 'http://leocad.io/mvn' }
}

dependencies {
    compile 'io.leocad:webcachedimageview:2.0.0'
}

###Step 2: Add the permissions to your AndroidManifest.xml WebCachedImageView requires the following permissions to work:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

The WRITE_EXTERNAL_STORAGE is only required if you enable the disk cache.

###Step 3: Add the view to your XML layout You need to add the WebCachedImageView tag to your XML layout file:

<io.leocad.view.WebCachedImageView
    android:id="@+id/wciv"
    android:layout_width="90dp"
    android:layout_height="90dp" />

Note: if you're upgrading from version 1.0, you should replace your <WebCachedImageView /> tags with the one above (with the io.leocad.view prefix).

###Step 4 (optional): Fine-tuning If you want to, you can fine-tune WebCachedImageView's settings. To do that, first you'll have to add the following attribute to your root XML node:

xmlns:app="http://schemas.android.com/apk/res-auto"

####Memory allocation By default, WebCachedImageView allocates 1/8 (12.5%) of the phone's memory to the memory cache. To change that, set a float value to the app:memoryPercentToUse attribute.

####Caching mode WebCachedImageView can cache in two levels: memory and disk. By default, it uses both. But you can set the app:cache_mode value to no_cache, memory or disk.

When it's all set, your XML will look something like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <io.leocad.view.WebCachedImageView
        android:id="@+id/wciv"
        android:layout_width="90dp"
        android:layout_height="90dp"
        app:memoryPercentToUse="20.0"
        app:cache_mode="memory" />
        
</RelativeLayout>

###Step 5: Download the image Just call the following code whenever you need to download an image:

WebCachedImageView wciv = (WebCachedImageView) findViewById(R.id.wciv);
wciv.setImageUrl(YOUR_IMAGE_URL);

You don't have to spawn a new thread or create an AsyncTask to do that. WebCachedImageView does that for you.

###Proguard If you use Proguard, you have to add this line to your proguard-rules.txt:

-keep class io.leocad.view.WebCachedImageView { *; }

##License WebCachedImageView source code is released under BSD 2-clause license. Check LICENSE file for more information.

If you use this code, I'd appreciate you refer my name (Leocadio Tiné) and the link to this project's page in your project's website or credits screen. Though you don't have any legal/contractual obligation to do so, just good karma.

##Suggestions? Comments? Pull requests are always welcome. So are donations :)

To find me, buzz at me[at]leocad.io or follow me on Twitter. To read interesting stuff, go to my blog.

:::::::::::::
::         ::
:: Made at ::
::         ::
:::::::::::::
     ::
Hacker School
:::::::::::::

Donate button

webcachedimageview's People

Contributors

leocadiotine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

webcachedimageview's Issues

Error initializing

Im try you library. Im use Emulator, API level 17, add WebCachedImageView to ListView throw ListViewAdapter

public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.sent_listview_item, null);
            mHolder = new Holder();
            mHolder.txt_fileName    = (TextView) child.findViewById(R.id.txt_sentLV_fileName);
            mHolder.img_preview     = (WebCachedImageView) child.findViewById(R.id.wciv);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_fileName.setText(fileName.get(pos));
        return child;
    }

    public class Holder {
        WebCachedImageView img_preview;
        TextView txt_fileName;
    }

And I get this error:

11-28 15:47:51.767: ERROR/AndroidRuntime(1432): FATAL EXCEPTION: AsyncTask #1
        java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
        Caused by: java.lang.NoClassDefFoundError: com.jakewharton.DiskLruCache
        at io.leocad.webcachedimageview.CacheManager$2.doInBackground(CacheManager.java:93)
        at io.leocad.webcachedimageview.CacheManager$2.doInBackground(CacheManager.java:86)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)
        ... 4 more

I htink error at this:

mDiskCache = DiskLruCache.open(cacheDir, 1, 1, DISK_CACHE_SIZE);

https://github.com/leocadiotine/WebCachedImageView/blob/master/code/src/io/leocad/webcachedimageview/CacheManager.java#L93
Plase help me

Cache image cap when 404

Hello, please tell me in my case.
How to implement a replacement cap image if it was removed on server and receives the response 404

Adding a WebCachedImageView programatically

Hi there! I try add a WebCachedImageView programatically in the instantiateItem method of my PageAdapter like this:

@OverRide
public Object instantiateItem(ViewGroup container, int position) {
WebCachedImageView imageView = new WebCachedImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageUrl(images.get(position).getUrl());
((ViewPager) container).addView(imageView, 0);
return imageView;
}

I tried in several ways with several ScaleType's but the result was the same, show only a color, or nothing. Then I changed the method to this:

@OverRide
public Object instantiateItem(ViewGroup container, int position) {
WebCachedImageView imageView = (WebCachedImageView) inflater.inflate(R.layout.item_viewpager_page, null);
imageView.setImageUrl(images.get(position).getUrl());
((ViewPager) container).addView(imageView, 0);
return imageView;
}

And now It's working, but isn't too nice given that I have to inflate a new View in each instantiateItem call. Maybe I'm using wrong the library?. Thanks, your library rulez 👯

How to cacheImage when imageurl in JSON?

Direct image url is ok, I can cache it easily using this library. But my image url is listed in json, I can display it normally. But I happen to have problem to cache the image this way. Please advice.

A bug in BitmapWorkerTask.cancelPotentialWork

I suppose Strings are not to be checked using == or != operator. Following code would be better:
BitmapWorkerTask task = getBitmapWorkerTask();
if(task != null) {
if(task.url != null) {
if(task.url.equals(url))
return false;
else
task.cancel(true);
}
}
return true;

Error:(33, 13) Failed to resolve: io.leocad:webcachedimageview:2.0.0

I get the following error:
Error:(33, 13) Failed to resolve: io.leocad:webcachedimageview:2.0.0
Show in File
Show in Project Structure dialog

Here are the details:
classpath 'com.android.tools.build:gradle:2.2.3'

compileSdkVersion 23
buildToolsVersion '23.0.3'

defaultConfig {
    applicationId "com.saediworks.maruti"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 13
    multiDexEnabled true
    versionName "1.12"
}
buildTypes {
    release {
        minifyEnabled false
         consumerProguardFiles 'proguard-rules.txt'
    }
}

repositories {
maven { url 'http://leocad.io/mvn' }
}

dependencies {
compile 'io.leocad:webcachedimageview:2.0.0'
}

Q: Use caching image from Cache in another ImageView

Hi!
Tell me plase, Is there a way Use caching image from Cache in another WebCachedImageView, because caching encoded filenames and I can not directly access the downloaded file, since I do not know his new filename, that would show this picture to a another ImageView.
Or how set disable encoded filename?
Thank you!

NullPointerException while inflating WebCachedImageView

Hello there

I am currently working on an app and I am using this framework to get Images from the web. Unfortunately this framework throws an exception while inflating the WebCachedImageView. It is caused by a NullPointerException while getting the External Cache dir. According to the Android Context API the Method getExternalCacheDir(), which you are using and probably is returning null, returns null in case there is no external storage is mounted. To ensure that this is the problem, I’ve tested the application on a Device using an SD card as external storage and one without. Both are throwing the same following exception:

08-10 14:20:54.985  12255-12255/ch.upndown.upndown E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ch.upndown.upndown/ch.upndown.upndown.MainActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class com.android.internal.widget.ActionBarOverlayLayout
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
            at android.app.ActivityThread.access$700(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class com.android.internal.widget.ActionBarOverlayLayout
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
            at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3553)
            at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3616)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:357)
            at android.app.Activity.setContentView(Activity.java:1956)
            at ch.upndown.upndown.MainActivity.onCreate(MainActivity.java:18)
            at android.app.Activity.performCreate(Activity.java:5372)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
            at android.app.ActivityThread.access$700(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at io.leocad.webcachedimageview.CacheManager.getCacheDir(CacheManager.java:117)
            at io.leocad.webcachedimageview.CacheManager.<init>(CacheManager.java:85)
            at io.leocad.webcachedimageview.CacheManager.getInstance(CacheManager.java:43)
            at android.view.WebCachedImageView.init(WebCachedImageView.java:84)
            at android.view.WebCachedImageView.<init>(WebCachedImageView.java:37)
            at ch.upndown.upndown.MainActivity.onCreateView(MainActivity.java:39)
            at android.app.Activity.onCreateView(Activity.java:4924)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
            at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3553)
            at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3616)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:357)
            at android.app.Activity.setContentView(Activity.java:1956)
            at ch.upndown.upndown.MainActivity.onCreate(MainActivity.java:18)
            at android.app.Activity.performCreate(Activity.java:5372)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
            at android.app.ActivityThread.access$700(ActivityThread.java:159)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)

The code in the layout file:

<WebCachedImageView
    android:id="@+id/website_images"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="5dp"/>

Best Regards
Huo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.