In this Android tip, I am going to show you how to cache an image from url so that the image can be displayed quickly without internet connection. In a chat application, typically, profile pictures are downloaded at the first time and cached in memory or disc to load quickly in an ImageView. A popular library that I always use in my projects to achieve the goal is
Universal Image Loader. It can download and cache multiple images asynchronously. There are many configuration options of an ImageLoader instance to meet your requirements.
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
// Configure image loader
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
// Thread priority
.threadPriority(Thread.NORM_PRIORITY)
// Deny cache multiple image sizes on memory
.denyCacheImageMultipleSizesInMemory()
// Processing order like a stack (last in, first out)
.tasksProcessingOrder(QueueProcessingType.LIFO)
// Max image size to cache on memory
.memoryCacheSize(1*1024*2014)
// Max image size to cache on disc
.diskCacheSize(2*1024*1024)
// Write log messages
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
// Get ImageLoader instance
ImageLoader imageLoader=ImageLoader.getInstance();
// Define image display options
DisplayImageOptions options = new DisplayImageOptions.Builder()
// Cache loaded image in memory and disc
.cacheOnDisk(true)
.cacheInMemory(true)
// Show Android icon while loading
.showImageOnLoading(R.drawable.ic_launcher)
.build();
String imgUrl="http://www.keralahouseplanner.com/wp-content/uploads/2012/09/kerala-house-plan-duplex1.jpg";
imageLoader.displayImage(imgUrl, imageView, options);
}
}
|
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.